gpt4 book ai didi

java - JTable 没有显示在 UI 中?

转载 作者:行者123 更新时间:2023-12-02 04:16:08 25 4
gpt4 key购买 nike

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

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

只需删除此行即可正常工作。因为布局设置为 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
}

所以最终结果如下所示:

enter image description here

关于java - JTable 没有显示在 UI 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33297123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com