我想将几个组件添加到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
有任何建议如何解决?
答案 0 :(得分:1)
此行return this; //do not know how to return the whole component?
你要归还这个 - >这是一个JPanel,因为你从JPanel继承了你的类