简体   繁体   中英

List box does not show up using java in netbeans

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM