How to add elements in a Java swing List Box

  • Java
  • Thread starter zak100
  • Start date
  • #26
zak100
Gold Member
462
11
Hi,
Thanks my friend but it does not solve my problem. Because it says that:
  • Initially the list is empty.
Actually this was the problem with the code which i was using.

However I am now able to solve this problem. I checked a video on You-tube & i got the solution. Thanks everybody. The solution lies in clearing the initially created list box & this is not mentioned in the tutorial. After creating the list box, i went to properties->model & erased the contents across this field. After that my program ran correctly. I would suggest tuning the documentation for NetBeans users.

My code corresponding to the two Buttons are:
Java:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                    
        // TODO add your handling code here:
   
        for (int i=0;i<5; ++i)
            model.addElement("Zulfi item" +i);
        jList1.setModel(model);
    }                                   
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                    
        // TODO add your handling code here:
        String str=jTextField1.getText();
        model.addElement(str);
        jList1.setModel(model);
    }
& the constructor is:
Java:
public class JavaListBox1 extends javax.swing.JFrame {
private DefaultListModel model;
    /**
     * Creates new form JavaListBox1
     */
    public JavaListBox1() {
       model = new DefaultListModel();
        initComponents();
    }
Variables corresponding to the components are:
Java:
private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JList<String> jList1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
Problem solved now.

Zulfi.
 
  • #27
11,881
5,532
That's great! Thanks for the update.
 

Related Threads on How to add elements in a Java swing List Box

  • Last Post
Replies
1
Views
2K
Replies
9
Views
871
Replies
3
Views
4K
Replies
9
Views
619
  • Last Post
Replies
18
Views
964
Replies
6
Views
12K
Replies
5
Views
13K
Replies
3
Views
620
Replies
6
Views
4K
Top