Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

How to add elements in a Java swing List Box

  1. Jul 5, 2016 #1
    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.
     
  2. jcsd
  3. Jul 5, 2016 #2

    jedishrfu

    Staff: Mentor

  4. Jul 6, 2016 #3
    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.
     
  5. Jul 6, 2016 #4

    Mark44

    Staff: Mentor

    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:
    Code (Java):
    public JavaListAddDelEdit() {
         initComponents();
         model = new DefaultListModel();
         list = new JList<String>(model);
         i=0;
    }
     
  6. Jul 7, 2016 #5
    Hi,
    I am getting error with DefaultListModel. I am using java NetBeans

    Code (Text):
    /*
    * 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:

    Somebody please guide m.
    Zulfi.
     
  7. Jul 7, 2016 #6

    Mark44

    Staff: Mentor

    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.
     
  8. Jul 7, 2016 #7

    jedishrfu

    Staff: Mentor

    You need an import statement for DefaultListModel or you need to specify where its comes from as in java.swing.DefaultListModel
     
  9. Jul 7, 2016 #8
    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:
    Code (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. Jul 7, 2016 #9

    jedishrfu

    Staff: Mentor

  11. Jul 7, 2016 #10

    Mark44

    Staff: Mentor

    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.
     
  12. Jul 7, 2016 #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.
     
  13. Jul 7, 2016 #12

    Mark44

    Staff: Mentor

    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.
     
  14. Jul 7, 2016 #13
    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.
     
  15. Jul 7, 2016 #14

    Mark44

    Staff: Mentor

    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?
     
  16. Jul 7, 2016 #15
    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.
     
  17. Jul 7, 2016 #16

    Mark44

    Staff: Mentor

    You have to specify the type of list; in other words what type of objects will go into the list?
     
  18. Jul 8, 2016 #17
    Hi,
    Thanks. I already did this in the constructor.
    Code (Java):
     public JavaListAddDelEdit() {
            initComponents();
            //model = new DefaultListModel();
            list = new JList<String>(model);
            //i=0;
        }
    Please guide me.
    Zulfi.
     
  19. Jul 8, 2016 #18

    Mark44

    Staff: Mentor

  20. Jul 9, 2016 #19
    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:
    Code (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 :
    Code (Java):
    public class CListBox2 extends JPanel
                          implements ListSelectionListener
     

    manually, I am getting following errors:


    My complete NetBeans code is:

    Code (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: Jul 9, 2016
  21. Jul 9, 2016 #20

    jedishrfu

    Staff: Mentor

    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;
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: How to add elements in a Java swing List Box
  1. Java linked list (Replies: 1)

  2. GUI on Java (Replies: 8)

Loading...