简体   繁体   中英

Java - Gui Components do not show up

I have this code to create a simple gui (by hand) and I am trying to display gui components on the frame. However, when I run the program, only the frame shows without showing the components, such as the JTable.

Any idea why ?

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*;

public class GUI extends JFrame {
    public void buildGui() {
        JFrame frame = new JFrame("Hotel TV Scheduler");    
        frame.setVisible(true);

        Container contentPane = frame.getContentPane();

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());

        JPanel listPanel = new JPanel();
        listPanel.setLayout(new FlowLayout());

        JTable chOneTable = new JTable();
        JTable chTwoTable = new JTable();
        JTable listTable = new JTable();

        listPanel.add(chOneTable);
        listPanel.add(chTwoTable);
        listPanel.add(listTable);

        contentPane.add(listPanel);
    }
}

You should set a preferredSize() on the JTables and do a pack() afterwards.

Edit:

Moved setVisible(true) after pack() . This is the order which is used by Sun/Oracle .

public class GUI extends JFrame {
    public void buildGui() {
        JFrame frame = new JFrame("Hotel TV Scheduler");

        Container contentPane = frame.getContentPane();

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());

        JPanel listPanel = new JPanel();
        listPanel.setLayout(new FlowLayout());

        Dimension d = new Dimension(100, 100);

        JTable chOneTable = new JTable();
        chOneTable.setPreferredSize(d);

        JTable chTwoTable = new JTable();
        chTwoTable.setPreferredSize(d);

        JTable listTable = new JTable();
        listTable.setPreferredSize(d);

        listPanel.add(chOneTable);
        listPanel.add(chTwoTable);
        listPanel.add(listTable);

        contentPane.add(listPanel);

        frame.pack();
        frame.setVisible(true);
    }
}
  1. Construct the JFrame instance
  2. Add the components to the JFrame instance
  3. Realize the JFrame instance (ie setVisible(true) )

The reason none of the components show up when the JFrame instance is shown is because you add components to it after it has been realized. If you want to components to show up, either follow the steps above, or at the end of the buildGui method, revalidate/repaint the container.

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