Java - Gui组件不会显示

时间:2012-03-29 11:09:03

标签: java swing user-interface

我有这个代码来创建一个简单的gui(手工),我试图在框架上显示gui组件。但是,当我运行程序时,只显示框架而不显示组件,例如JTable。

知道为什么吗?

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);
    }
}

2 个答案:

答案 0 :(得分:3)

您应该在JTable上设置preferredSize()并在之后执行pack()

修改

setVisible(true)之后移动了pack()。这是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 :(得分:2)

  1. 构建JFrame实例
  2. 将组件添加到JFrame实例
  3. 实现JFrame个实例(即setVisible(true)
  4. 显示JFrame实例时没有显示任何组件的原因是因为在实现后向其添加组件。如果要显示组件,请按照上述步骤操作,或者在buildGui方法的末尾,重新验证/重新绘制容器。