Jlabel在单独的类中实现时不会出现在Jframe中
我正在尝试将Jlabel添加到我的Jframe中。我已经在单独的类中实现了它们,但是当我运行代码时,我看不到我的标签。
当我在app
类中实现帧和标签时,它运行良好。
import javax.swing.JFrame;
public class MyFrame extends JFrame {
public MyFrame() {
this.setSize(420, 420);
this.setTitle("First Java GUI");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
import javax.swing.JLabel;
public class MyLabel extends JLabel {
public MyLabel() {
JLabel label = new JLabel();
label.setText("Welcome");
}
}
public class App {
public static void main(String[] args) {
MyFrame frame1 = new MyFrame();
MyLabel label1 = new MyLabel();
frame1.add(label1);
}
}
I am trying to add a JLabel to my JFrame. I have implemented them in separate classes but when I run the code, I cannot see my label.
It worked well when I implemented both frame and label in the App
class.
import javax.swing.JFrame;
public class MyFrame extends JFrame {
public MyFrame() {
this.setSize(420, 420);
this.setTitle("First Java GUI");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
import javax.swing.JLabel;
public class MyLabel extends JLabel {
public MyLabel() {
JLabel label = new JLabel();
label.setText("Welcome");
}
}
public class App {
public static void main(String[] args) {
MyFrame frame1 = new MyFrame();
MyLabel label1 = new MyLabel();
frame1.add(label1);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您在
mylabel
类中遇到了错误。如果扩展它,只需添加构造函数即可。但是您在构造函数中创建了另一个标签,这不会添加到框架中。因此,正确的版本是:之后:
You have a mistake in
MyLabel
class. If you extend it, just add constructors. But you in your constructor create another label, that is not added to frame. So, correct version is:And after it:
是您需要的。您将代码隐藏在另一个
jlabel
中,它不是不是您的子类。不过,这是一个问题:您为什么要创建一个子类?为什么不立即使用jlabel
?is what you need. You hide your code inside another
JLabel
which is not your subclass. It sort of begs the question though: why are you creating a subclass? Why not just use aJLabel
right off?