0

So I have the following code which executes when a button is pressed. I have designed the rest of the GUI using the GUI builder within Netbeans.

    private void populateBtnActionPerformed(java.awt.event.ActionEvent evt) {                                            
        String query = "SELECT AccNo from accounts";
        try{
            connect.rs = connect.st.executeQuery(query);
            Vector<String> temp = new Vector<String>();

            while (connect.rs.next()){
                temp.add(connect.rs.getString("AccNo"));
            }

            JList accList = new JList(temp);
            jPanel4.add(accList, BorderLayout.CENTER);

        }catch(Exception e){
            JOptionPane.showMessageDialog(null, e);
    }
  }  

Why wont the list box show up? What am I doing wrong?

Thank you in advance.

camickr
  • 321,443
  • 19
  • 166
  • 288
BEE
  • 107
  • 1
  • 2
  • 13

1 Answers1

3

Why wont the list box show up? What am I doing wrong?

Because of this:

JList accList = new JList(temp);
jPanel4.add(accList, BorderLayout.CENTER);

These lines suggests that jPanel4 has already been displayed by the time you are trying to add the JList to it by clicking a button, thus invalidating the components hierarchy and in consequence you have to revalidate and repaint the panel like this:

 jPanel4.add(accList, BorderLayout.CENTER);
 jPanel4.revalidate();
 jPanel4.repaint();

However, while we can add components dynamically in Swing we tipically place all our components before the top-level container (window) is made visible. In this case you should place the list when you init your components (don't forget the scroll pane) and update its model when the button is pressed.

See How to Use Lists tutorial.

Other notes

Be aware that database calls are time consuming tasks and may block the Event Dispatch Thread (EDT) causing the GUI become unresponsive. The EDT is a single and special thread where Swing components creation and update take place. To avoid block this thread consider use a SwingWorker to perform database calls in a background thread and update Swing components in the EDT. See more in Concurrency in Swing lesson.

dic19
  • 17,821
  • 6
  • 40
  • 69
  • even when I add this code to revalidate and repaint the panel the listbox still wont show up. If I want to add the list when I init my components I can't as I have made the rest of the GUI using the builder. – BEE Oct 28 '14 at 15:49
  • *If I want to add the list when I init my components I can't as I have made the rest of the GUI using the builder.* Why you can't? Just drag and drop a list using GUI builder and place that list wherever you want. And then follow my other suggestion: update the list model on button clicks. @BEE – dic19 Oct 28 '14 at 15:55
  • Sorry I am very new to Java. Its only been 2 days. So I am still a little confused. If you could demonstrate with an example? Thank you very, very much. – BEE Oct 28 '14 at 16:23