这个类的构造有问题吗?我正在尝试将其实例添加到另一个类中的 JPanel:
public class calculator2 extends JPanel {
public calculator2() {
JPanel x = new JPanel();
x.setLayout(new GridLayout(0,5));
x.add(new JLabel());
x.add(new JButton("<<"));
x.add(new JLabel());
x.add(new JButton(">>"));
x.add(new JLabel());
}
}
这就是我尝试使用它的地方:
calculator2 test = new calculator2();
JPanel panel3 = new JPanel(new BorderLayout());
panel3.add(test, BorderLayout.SOUTH);
我没有收到任何类型的运行时错误,它只是没有显示出来。当我将计算器2类中的代码放入我在代码的第二部分中使用的同一个类中时,它就会显示出来。感谢您的考虑。
这实际上只是一个例子,我有一个完整的类,包含大约 25 个使用 Action 监听器等的组件,并希望使用上述方法将其添加到面板中。
最佳答案
在这里,您只是创建面板,而不将其添加到任何可见的地方。尝试使用从 JPanel 继承的父方法,而不是在构造函数中创建另一个 JPanel 的新实例。
这就是,只需删除名为 x 的实例即可。
public class calculator2 extends JPanel {
public calculator2() {
super();
setLayout(new GridLayout(0,5));
add(new JLabel());
add(new JButton("<<"));
add(new JLabel());
add(new JButton(">>"));
add(new JLabel());
}
}
关于java - 将另一个类的面板实例添加到父面板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12185623/