gpt4 book ai didi

java - 向 Jpanel 添加多个组件

转载 作者:太空宇宙 更新时间:2023-11-04 06:39:21 26 4
gpt4 key购买 nike

我想向 JPanel 添加多个组件,然后将该面板添加到 JFrame。

这是一个简短的示例程序:

public class Test extends JPanel {

private static final long serialVersionUID = -5616883761578620198L;

static JPanel jpanel;
private static JLabel jLabel;

private static void createAndShowGUI() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//adding everything to the jpanel
jpanel = new JPanel();
jpanel.add(addLabel());
jpanel.add(addTable());

//adding the jpanel to the frame
frame.add(jpanel);

frame.pack();
frame.setVisible(true);
}

public static Component addTable() {

jLabel = new JLabel("Test");

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

final JTable table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);

JScrollPane scrollPane = new JScrollPane(table);

table.add(scrollPane);

return this; //do not know how to return the whole component?
}

public static Component addLabel() {

jLabel = new JLabel("Test1");

return jLabel;
}


public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

但是,我遇到了异常(exception):

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: adding container's parent to itself

有什么建议可以解决这个问题吗?

最佳答案

此行的原因 return this;//不知道如何返回整个组件?

你正在返回这个 --> 这是一个 JPanel,因为你从 JPanel 继承了你的类

关于java - 向 Jpanel 添加多个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24887508/

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