[英]Adding several Components to a Jpanel
我想将几个组件添加到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 in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: adding container's parent to itself
任何建议如何解决?
此行的原因return this; //do not know how to return the whole component?
return this; //do not know how to return the whole component?
您正在返回此->这是一个JPanel,因为您从JPanel继承了您的类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.