我想在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);
}
答案 0 :(得分:2)
问题是当您在此行中将布局设置为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
}
所以最终结果如下:
答案 1 :(得分:0)
您没有使用布局管理器[myframe.setLayout(null)],因此您必须自己处理位置和大小。
尝试添加:
table.setLocation(1, 1);
table.setSize(200,200);
它会起作用。