How to add elements in a Java swing List Box

  • Java
  • Thread starter zak100
  • Start date
  • #1
zak100
Gold Member
462
11

Main Question or Discussion Point

Hi,
I am using NetBeans 8.1. I want to add elements in a list Box on a Button press. My code would read text from textField & then insert into list box:

private void button1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String str=jTF.getText();
list.??
}

I dont know the list box method for this purpose. My variables are:
private javax.swing.JButton button1;
private javax.swing.JButton button2;
private javax.swing.JButton button3;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollBar jScrollBar1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField jTF;
private javax.swing.JList<String> list;

From netBeans, i found following methods:


add(Component comp)

add(PopupMenu comp)

add(Component comp, Object o)

add(String str, Component comp)<----------

add(Component comp, Object o, int i)
The method :
add(String str, Component comp)
can be used but what is the value of:
comp object??

Some body please guide me.

Zulfi.
 

Answers and Replies

  • #2
11,882
5,533
  • #3
zak100
Gold Member
462
11
Hi,
Thanks for your response. I am doing it for JList. I have made some changes:
added a variable i & modified the constructor to:
int i;
public JavaListAddDelEdit() {
initComponents();
model = new DefaultListModel();
list = new JList<String>(model);
i=0;
}
Wrote the add button handler:


private void button1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String str=jTF.getText();
model.add(i, str);
i++;


}

added a declaration for:
DefaultListModel model;

But when i execute the program, I am getting following er
One or more projects were compiled with error:

When i press cancel, i am directed to this

run:

C:\Users\HP\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:48:

Cancelled by user
BUILD FAILED (total time: 1 minute 25 seconds)
When i pressed the above line, i am directed to:

<translate-classpath classpath="${classpath}" targetProperty="classpath-translated" />

Kindly guide me how to fix this problem.
Zulfi.
 
  • #4
33,721
5,418
I'm going to take a guess that the problem is your i variable. You don't show all of your code, but it looks like i is a variable in whatever class you have defined, that has the JavaListAddDelEdit() method and the button1ActionPerformed() handler. I suspect that since you haven't specified otherwise in your declaration for i, its access level is private, so when you attempt to increment i in JavaListAddDelEdit() and button1ActionPerformed(), the compiler quits and issues the error.

In addition, when you post code, please use [code] tags around your code, like this:
[code=java]
// Your java code
[/code]

With code tags here is how one of your methods should look:
Java:
public JavaListAddDelEdit() {
     initComponents();
     model = new DefaultListModel();
     list = new JList<String>(model);
     i=0;
}
 
  • #5
zak100
Gold Member
462
11
Hi,
I am getting error with DefaultListModel. I am using java NetBeans

Code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package jListAddDelEdit;

/**
*
* @author HP
*/
public class JavaListAddDelEdit extends javax.swing.JFrame {
public DefaultListModel<String> model = new DefaultListModel<>(); 
    /**
     * Creates new form JavaListAddDelEdit
     */
    //int i;
    public JavaListAddDelEdit() {
        initComponents();
        //model = new DefaultListModel();
        list = new JList<String>(model);
        //i=0;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTF = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        list = new javax.swing.JList<>();
        button1 = new javax.swing.JButton();
        button2 = new javax.swing.JButton();
        button3 = new javax.swing.JButton();
        jScrollBar1 = new javax.swing.JScrollBar();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Java List Add Delete Edit Elements");

        jLabel1.setText("Item Name");

        list.setModel(new javax.swing.AbstractListModel<String>() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public String getElementAt(int i) { return strings[i]; }
        });
        jScrollPane1.setViewportView(list);

        button1.setText("Add");
        button1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                button1ActionPerformed(evt);
            }
        });

        button2.setText("Delete");
        button2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                button2ActionPerformed(evt);
            }
        });

        button3.setText("Edit");
        button3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                button3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(jTF, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(button2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(button1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(button3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(0, 9, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(button1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(button2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(button3))
                    .addComponent(jScrollBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(21, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                       

    private void button1ActionPerformed(java.awt.event.ActionEvent evt) {                                       
        // TODO add your handling code here:
        String str=jTF.getText();
        model.addElement( str);
        list.setModel(model);
       // i++;

       
    }                                      

    private void button2ActionPerformed(java.awt.event.ActionEvent evt) {                                       
        // TODO add your handling code here:
    }                                      

    private void button3ActionPerformed(java.awt.event.ActionEvent evt) {                                       
        // TODO add your handling code here:
    }                                      

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JavaListAddDelEdit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JavaListAddDelEdit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JavaListAddDelEdit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JavaListAddDelEdit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JavaListAddDelEdit().setVisible(true);
            }
        });
    }
   
    // Variables declaration - do not modify                    
    private javax.swing.JButton button1;
    private javax.swing.JButton button2;
    private javax.swing.JButton button3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollBar jScrollBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTF;
    private javax.swing.JList<String> list;
    // End of variables declaration                  
}
I am getting the following error message:
Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - cannot find symbol
symbol: class DefaultListModel
location: class jListAddDelEdit.JavaListAddDelEdit
at jListAddDelEdit.JavaListAddDelEdit.<init>(JavaListAddDelEdit.java:13)
at jListAddDelEdit.JavaListAddDelEdit$5.run(JavaListAddDelEdit.java:186)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
BUILD SUCCESSFUL (total time: 2 seconds)

Somebody please guide m.
Zulfi.
 
  • #6
33,721
5,418
Java:
public class JavaListAddDelEdit extends javax.swing.JFrame {
public DefaultListModel<String> model = new DefaultListModel<>();
It looks like you just stuck the 2nd line in here. The problem is that there is no definition for a DefaultListModel class, and that's what the first error in your list of errors is telling you.
 
  • #7
11,882
5,533
You need an import statement for DefaultListModel or you need to specify where its comes from as in java.swing.DefaultListModel
 
  • #8
zak100
Gold Member
462
11
Hi,
Thanks my friend. I have added the import statement. Its not giving any error now but its not adding elements in the list. Its retrieving the value from textField & displaying it using JOptionPane but not adding it in the listBox. My modified code is:
Java:
package jListAddDelEdit;
import javax.swing.*;
/**
*
* @author HP
*/
public class JavaListAddDelEdit extends javax.swing.JFrame {
public DefaultListModel<String> model = new DefaultListModel<>();
    /**
     * Creates new form JavaListAddDelEdit
     */
    //int i;
    public JavaListAddDelEdit() {
        initComponents();
        //model = new DefaultListModel();
        list = new JList<String>(model);
        //i=0;
    }



    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                        
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTF = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        list = new javax.swing.JList<>();
        button1 = new javax.swing.JButton();
        button2 = new javax.swing.JButton();
        button3 = new javax.swing.JButton();
        jScrollBar1 = new javax.swing.JScrollBar();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Java List Add Delete Edit Elements");

        jLabel1.setText("Item Name");

        list.setModel(new javax.swing.AbstractListModel<String>() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public String getElementAt(int i) { return strings[i]; }
        });
        jScrollPane1.setViewportView(list);

        button1.setText("Add");
        button1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                button1ActionPerformed(evt);
            }
        });

        button2.setText("Delete");
        button2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                button2ActionPerformed(evt);
            }
        });

        button3.setText("Edit");
        button3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                button3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(jTF, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(button2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(button1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(button3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(0, 9, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(button1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(button2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(button3))
                    .addComponent(jScrollBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(21, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                      

    private void button1ActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // TODO add your handling code here:
        String str=jTF.getText();
        JOptionPane.showMessageDialog(null,str);
        model.addElement( str);
        list.setModel(model);
       // i++;

      
    }                                     

    private void button2ActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // TODO add your handling code here:
    }                                     

    private void button3ActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // TODO add your handling code here:
    }                                     

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JavaListAddDelEdit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JavaListAddDelEdit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JavaListAddDelEdit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JavaListAddDelEdit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JavaListAddDelEdit().setVisible(true);
            }
        });
    }
  
    // Variables declaration - do not modify                   
    private javax.swing.JButton button1;
    private javax.swing.JButton button2;
    private javax.swing.JButton button3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollBar jScrollBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTF;
    private javax.swing.JList<String> list;
    // End of variables declaration                 
}
Some body please guide me.

Zulfi.
 
  • #10
33,721
5,418
Java:
   private void button1ActionPerformed(java.awt.event.ActionEvent evt) {                                      
         // TODO add your handling code here:
         String str=jTF.getText();
         JOptionPane.showMessageDialog(null,str);
         model.addElement( str);
         list.setModel(model);
        // i++;

       
     }
As far as I can tell, the method above needs to insert the string into your list variable, and this would likely happen in the method above.
 
  • #11
zak100
Gold Member
462
11
Hi,
I have added the JOptionPane for the sake of debugging. Its displaying the value retrieved from JTextField but why its not displaying it in JListBox is a programming error. Please check the following method:
privatevoid button1ActionPerformed(java.awt.event.ActionEvent evt){
// TODO add your handling code here:
String str=jTF.getText();
JOptionPane.showMessageDialog(null,str);
model.addElement( str);
list.setModel(model);
// i++;


}
Zulfi.
 
  • #12
33,721
5,418
Netbeans 8.1 and earlier have a debug facility that can help you discover what is going on with your code. We can't simply look at it each time you make a change and then tell you what is going on and why it isn't working.
Excellent advice. If you're writing code in any language, it pays to get familiar with whatever debugger is present. Virtually all modern programming languages have some sort of debugger that you can use to set a breakpoint and inspect the value of a given variable.
 
  • #13
zak100
Gold Member
462
11
Hi,
I have checked the value of list & model objects
list type(JList) value(1700)
model type(DefaultListModel) value(1619)
They are negative, so they are correct. str is also correct. So which other value should i check?

Zulfi.
 
  • #14
33,721
5,418
Hi,
I have checked the value of list & model objects
list type(JList) value(1700)
model type(DefaultListModel) value(1619)
They are negative, so they are correct. str is also correct. So which other value should i check?

Zulfi.
How do you figure they're negative? 1700 and 1619 are positive, but I suspect these values either represent addresses or if not addresses, just uninitialized "garbage" values.You have a list variable. What methods are available on a JList object to insert values into it?
 
  • #15
zak100
Gold Member
462
11
Hi,
I mean its not negative so its correct object address. I tried this:

private void button1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String str=jTF.getText();
JOptionPane.showMessageDialog(null,str);
model.addElement( str);
list.add(model,1);
// i++;


}
but its giving errors:
thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: javax.swing.JList.add
at jListAddDelEdit.JavaListAddDelEdit.button1ActionPerformed(JavaListAddDelEdit.java:143)
at jListAddDelEdit.JavaListAddDelEdit.access$000(JavaListAddDelEdit.java:12)
at jListAddDelEdit.JavaListAddDelEdit$2.actionPerformed(JavaListAddDelEdit.java:59)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6535)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6300)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4891)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2750)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)


Zulfi.
 
  • #16
33,721
5,418
Java:
list = new javax.swing.JList<>();
You have to specify the type of list; in other words what type of objects will go into the list?
 
  • #17
zak100
Gold Member
462
11
Hi,
Thanks. I already did this in the constructor.
Java:
 public JavaListAddDelEdit() {
        initComponents();
        //model = new DefaultListModel();
        list = new JList<String>(model);
        //i=0;
    }
Please guide me.
Zulfi.
 
  • #19
zak100
Gold Member
462
11
Hi,
Yes i saw this example, & but it does not tell how we can use it for NetBeans. Now i am trying to use it for Netbeans. I created a project & provided a Frame & then a penal & then inserted components in the panel. But i have following class signature using a project named ListBox2:

public class CListBox2 extends javax.swing.JFrame {

where as the tutorial project has following class signature:

/* ListDemo.java requires no other files. */

public class ListDemo extends JPanel implements ListSelectionListener {

I think this is the problem.
Although, I have created a Panel using NetBeans & I am putting my controls in this panel:

My variable declaration shows this:
Java:
private javax.swing.JButton jButton1;
    private javax.swing.JList<String> jList1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
When I converted the class signature into :
Java:
public class CListBox2 extends JPanel
                      implements ListSelectionListener

manually, I am getting following errors:

java.lang.ExceptionInInitializerError

Caused by: java.lang.RuntimeException: Uncompilable source code - JavaListBox2.CListBox2 is not abstract and does not override abstract method valueChanged(javax.swing.event.ListSelectionEvent) in javax.swing.event.ListSelectionListener

at JavaListBox2.CListBox2.<clinit>(CListBox2.java:15)

Exception in thread "main" C:\Users\HP\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1

BUILD FAILED (total time: 1 second)

My complete NetBeans code is:

Java:
package JavaListBox2;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.event.*;

/**

*

* @author HP

*/

public class CListBox2 extends JPanel

  implements ListSelectionListener

{


  /**

  * Creates new form CListBox2

  */

  public CListBox2() {

  initComponents();

  }


  /**

  * This method is called from within the constructor to initialize the form.

  * WARNING: Do NOT modify this code. The content of this method is always

  * regenerated by the Form Editor.

  */

  @SuppressWarnings("unchecked")

  // <editor-fold defaultstate="collapsed" desc="Generated Code">

  private void initComponents() {


  jPanel1 = new javax.swing.JPanel();

  jScrollPane1 = new javax.swing.JScrollPane();

  jList1 = new javax.swing.JList<>();

  jButton1 = new javax.swing.JButton();


  setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);


  jList1.setModel(new javax.swing.AbstractListModel<String>() {

  String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };

  public int getSize() { return strings.length; }

  public String getElementAt(int i) { return strings; }

   });

  jScrollPane1.setViewportView(jList1);


  jButton1.setText("jButton1");


  javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);

  jPanel1.setLayout(jPanel1Layout);

  jPanel1Layout.setHorizontalGroup(

  jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

  .addGroup(jPanel1Layout.createSequentialGroup()

  .addContainerGap()

  .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)

  .addGap(60, 60, 60)

  .addComponent(jButton1)

  .addContainerGap(75, Short.MAX_VALUE))

  );

  jPanel1Layout.setVerticalGroup(

  jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

  .addGroup(jPanel1Layout.createSequentialGroup()

  .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

  .addGroup(jPanel1Layout.createSequentialGroup()

  .addContainerGap()

  .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE))

  .addGroup(jPanel1Layout.createSequentialGroup()

  .addGap(45, 45, 45)

  .addComponent(jButton1)))

  .addContainerGap(39, Short.MAX_VALUE))

  );


  javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

  getContentPane().setLayout(layout);

  layout.setHorizontalGroup(

  layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

  .addGroup(layout.createSequentialGroup()

  .addGap(48, 48, 48)

  .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

  .addContainerGap(115, Short.MAX_VALUE))

  );

  layout.setVerticalGroup(

  layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

  .addGroup(layout.createSequentialGroup()

  .addGap(19, 19, 19)

  .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

  .addContainerGap(41, Short.MAX_VALUE))

  );


  pack();

  }// </editor-fold>


  /**

  * [USER=541057]@param[/USER] args the command line arguments

  */

  public static void main(String args[]) {

  /* Set the Nimbus look and feel */

  //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">

  /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.

  * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html

  */

   try {

  for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {

  if ("Nimbus".equals(info.getName())) {

  javax.swing.UIManager.setLookAndFeel(info.getClassName());

  break;

  }

  }

  } catch (ClassNotFoundException ex) {

  java.util.logging.Logger.getLogger(CListBox2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

  } catch (InstantiationException ex) {

  java.util.logging.Logger.getLogger(CListBox2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

  } catch (IllegalAccessException ex) {

  java.util.logging.Logger.getLogger(CListBox2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

  } catch (javax.swing.UnsupportedLookAndFeelException ex) {

  java.util.logging.Logger.getLogger(CListBox2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

  }

  //</editor-fold>


  /* Create and display the form */

  java.awt.EventQueue.invokeLater(new Runnable() {

  public void run() {

  new CListBox2().setVisible(true);

  }

  });

   }


  // Variables declaration - do not modify

  private javax.swing.JButton jButton1;

  private javax.swing.JList<String> jList1;

  private javax.swing.JPanel jPanel1;

  private javax.swing.JScrollPane jScrollPane1;

  // End of variables declaration

}
Some body please guide me how can i extend my class from JPanel & implementsListSelectionListener.



Zulfi.
 
Last edited by a moderator:
  • #20
11,882
5,533
When I've used the Netbeans forms builder "Matisse", I don't place a lot of code inside the generated form ie I don't use the form as a basis for my program.

Instead I write a main class that instantiates the form and then links the form to my code ie I connect up listeners for any component activities in the form.

isnt netbeans providing error markers to help you resolve some of these issues you're having?

I often use the error messages and Google to find others with the same problem and usually a solution.

In your get string method you need to return a string not a string array i.e. You need to say

return strings;
 
  • #21
33,721
5,418
Java:
 public class CListBox2 extends JPanel  implementsListSelectionListener
zak100 said:
I am getting following errors:

java.lang.ExceptionInInitializerError

Caused by: java.lang.RuntimeException: Uncompilable source code - JavaListBox2.CListBox2 is not abstract and does not override abstract method valueChanged(javax.swing.event.ListSelectionEvent) in javax.swing.event.ListSelectionListener

at JavaListBox2.CListBox2.<clinit>(CListBox2.java:15)

Exception in thread "main" C:\Users\HP\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1

BUILD FAILED (total time: 1 second)
I believe that this error occurs because you are telling the compiler that you are implementing the ListSelectionListener interface, but you aren't actually doing so.

An interface in Java is a collection of one or more method declarations or signatures. To implement an interface you have to provide definitions for all of the methods that are listed in the interface. In this case, ListSelectionListener has only one method -- valueChanged (see http://docs.oracle.com/javase/7/docs/api/javax/swing/event/ListSelectionListener.html). Your code for CListBox2 has to include a definition for a method named valueChanged.
 
  • #22
zak100
Gold Member
462
11
Hi,
I have got a program from internet. There is no error, but its still not able to add elements in the list:
Java:
package jListBox4;
import javax.swing.*;
public class CListBox4 extends javax.swing.JFrame {

    /**
     * Creates new form CListBox4
     */
    public CListBox4() {
        initComponents();
         DefaultListModel<String> listModel = new DefaultListModel<>();
          listModel.removeAllElements();
        listModel.addElement("USA");
        listModel.addElement("India");
        listModel.addElement("Vietnam");
        listModel.addElement("Canada");
        listModel.addElement("Denmark");
        listModel.addElement("France");
        listModel.addElement("Great Britain");
        listModel.addElement("Japan");
        //create the list
        jList = new JList<>(listModel);
        add(jList);
        
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setTitle("JList Example");      
        this.setSize(200,200);
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jList = new javax.swing.JList<>();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jList.setModel(new javax.swing.AbstractListModel<String>() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public String getElementAt(int i) { return strings[i]; }
        });
        jScrollPane1.setViewportView(jList);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(47, 47, 47)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(236, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(138, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                       

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CListBox4.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CListBox4.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CListBox4.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CListBox4.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CListBox4().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                    
    private javax.swing.JList<String> jList;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration                  
}
Somebody please guide me how to add elements in the list & whats the problem with code. I am working on netBeans and i cant edit the "void initComponents() " code. Currently its showing me item 1, item2, .... item 5. Its not invoking the code written after initComponents( ) in the constructor.

Zulf.
 
  • #23
zak100
Gold Member
462
11
Hi,
why my code in reply# 22 not working??
Some body please guide me.

Zulfi.
 
  • #24
33,721
5,418
Hi,
why my code in reply# 22 not working??
Some body please guide me.

Zulfi.
Not sure, but the line where you create a jList variable is probably not right-- this line:
Java:
jList = new JList<>(listModel);
The empty angle brackets should not be there, I don't believe. Also, I don't know what you're doing in the following line -- add(jList); --

The biggest problem I see is that you are declaring jList too many times. It should be declared only once.
This one is in the CListBox4() constructor. See the snippet I'm including for the correct way to do this.
Java:
//create the list
  jList = new JList<>(listModel);
This one is in your initComponents method.
Java:
jScrollPane1 = new javax.swing.JScrollPane();
  jList = new javax.swing.JList<>();
Here is a declaration at the bottom of your code. I haven't written any Java code for about 20 years, but I think that these declarations of private variables should be at the top, just after where your class starts, not at the bottom.
Java:
// Variables declaration - do not modify 
  private javax.swing.JList<String> jList;
Here's a snippet of code from this page, http://docs.oracle.com/javase/tutor.../ListDemoProject/src/components/ListDemo.java, that might be helpful.
Java:
public class ListDemo extends JPanel
 implements ListSelectionListener {
 private JList list;
 private DefaultListModel listModel;

 private static final String hireString = "Hire";
 private static final String fireString = "Fire";
 private JButton fireButton;
 private JTextField employeeName;

 public ListDemo() {
 super(new BorderLayout());

 listModel = new DefaultListModel();
 listModel.addElement("Jane Doe");
 listModel.addElement("John Smith");
 listModel.addElement("Kathy Green");

 //Create the list and put it in a scroll pane.
 list = new JList(listModel);
 list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
 list.setSelectedIndex(0);
 list.addListSelectionListener(this);
 list.setVisibleRowCount(5);
.
.
.
In this sample they declare list at the top (private JList list;). Near the bottom of the code above, they allocate space for list, list = new JList(listModel);
 
  • #25
11,882
5,533
Here's an example of a dynamically adjustable list:

http://www.cs.cf.ac.uk/Dave/HCI/HCI_Handout_CALLER/node144.html [Broken]
 
Last edited by a moderator:

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