[英]How can I separate my swing components to different classes in java?
Just started to learn GUI, I've made a window with 2 buttons and 1 label and it worked.刚开始学习 GUI,我制作了一个带有 2 个按钮和 1 个标签的窗口,并且它工作正常。
After that I tried to separate the buttons to a different class and that worked too.之后,我尝试将按钮分离到不同的类,这也有效。
Then I wanted to separate my label to a different class (with the same strategy I used for buttons) but the text didn't show up.然后我想将我的标签分离到一个不同的类(使用与我用于按钮相同的策略)但文本没有显示。
My gui code:我的gui代码:
public class guiMain extends JFrame {
public guiMain(){
super("app");
setLayout(new BorderLayout());
Buttons buttons = new Buttons(); //I can see the buttons
add(buttons, BorderLayout.CENTER);
Labels label = new Labels();
add(label, BorderLayout.SOUTH);
// JLabel label = new JLabel("test");
// add(label, BorderLayout.SOUTH);
setSize(400,200);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
}
Labels class:标签类:
public class Labels extends JPanel {
public void Labels(){
setLayout(new FlowLayout(FlowLayout.LEFT));
JLabel label = new JLabel("bottom left label ");
add(label);
}
}
Sorry if this question is too simple, I didn't find any solution.对不起,如果这个问题太简单了,我没有找到任何解决方案。
Any suggestions for "good practice" would be appreciated also!对“良好做法”的任何建议也将不胜感激!
You've created a method你已经创建了一个方法
public void Labels() {
But what you want is a constructor但你想要的是一个构造函数
public Labels() {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.