简体   繁体   English

Java-Gui组件不显示

[英]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. 我有这段代码可以手动创建一个简单的GUI,并且试图在框架上显示GUI组件。 However, when I run the program, only the frame shows without showing the components, such as the JTable. 但是,当我运行程序时,仅显示框架而不显示组件,例如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. 您应该在JTables上设置preferredSize() ,然后再执行pack()

Edit: 编辑:

Moved setVisible(true) after pack() . setVisible(true)移动到pack() This is the order which is used by Sun/Oracle . 这是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 构造JFrame实例
  2. Add the components to the JFrame instance 将组件添加到JFrame实例
  3. Realize the JFrame instance (ie setVisible(true) ) 实现JFrame实例(即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. 显示JFrame实例时,没有任何组件显示的原因是因为在实现JFrame实例后向其中添加了组件。 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. 如果要显示组件,请按照上述步骤操作,或者在buildGui方法的末尾重新验证/重新绘制容器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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