JTable 没有出现在 UI 中?

JTable doesn't show up in UI?

我想在 UI 上创建一个示例 table。但无论我尝试什么,它都没有出现。也许有人可以帮助我?

public void createGUI(){
        JFrame myframe = new JFrame("Frame");
        JButton firstButton = new JButton("Connect");


        myframe.setLayout(null);
        myframe.setVisible(true);
        myframe.setSize(500, 500);
        //myframe.add(firstButton);


        firstButton.addActionListener(new handler("ConnectButton"));
        firstButton.setSize(150, 100);
        firstButton.setLocation(100, 100);

        String[] columnNames = {"First Name",
                "Last Name",
                "Sport",
                "# of Years",
                "Vegetarian"};

        Object[][] data = {
                {"Kathy", "Smith",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"John", "Doe",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Sue", "Black",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Jane", "White",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Joe", "Brown",
                 "Pool", new Integer(10), new Boolean(false)}
            };

        JTable table = new JTable(data, columnNames);
        table.setVisible(true);

        //JScrollPane scrollPane = new JScrollPane(table);
        //scrollPane.setVisible(true);
        table.setFillsViewportHeight(true);
        myframe.add(table);
    }

问题是当您在以下行中将布局设置为 null 时:

myframe.setLayout(null);

只要删除这一行,它就会很好地工作。因为 window 无法在布局设置为 null 时显示。因此,一旦您删除此行,将使用默认布局。

以下是您可能想要阅读的有关布局管理器的更多信息:https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

我删除的第二件事是这一行:

table.setFillsViewportHeight(true);

您应该改用 myframe.pack();,这样它可以将所有组件打包到您的框架上。

所以我最终得到了:

public static void createGUI() {
        JFrame myframe = new JFrame("Frame");
        JButton firstButton = new JButton("Connect");

        myframe.setSize(500, 500);

        String[] columnNames = {"First Name",
            "Last Name",
            "Sport",
            "# of Years",
            "Vegetarian"};

        Object[][] data = {
            {"Kathy", "Smith",
                "Snowboarding", new Integer(5), new Boolean(false)},
            {"John", "Doe",
                "Rowing", new Integer(3), new Boolean(true)},
            {"Sue", "Black",
                "Knitting", new Integer(2), new Boolean(false)},
            {"Jane", "White",
                "Speed reading", new Integer(20), new Boolean(true)},
            {"Joe", "Brown",
                "Pool", new Integer(10), new Boolean(false)}
        };

        JTable table = new JTable(data, columnNames);
        table.setVisible(true);

        myframe.add(table);
        myframe.pack();           // added this
        myframe.setVisible(true); // and moved this from top
    }

所以最终结果是这样的:

您没有使用布局管理器 [myframe.setLayout(null)],因此您必须自己处理位置和大小。

尝试添加:

  table.setLocation(1, 1);
  table.setSize(200,200);

它会起作用。