当在单独的类中实现时,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);
}
}

你在MyLabel类中有一个错误。如果扩展它,只需添加构造函数。但是您在构造函数中创建另一个标签,该标签不会添加到框架中。因此,正确的版本是:

import javax.swing.JLabel;
public class MyLabel extends JLabel {

public MyLabel(String text) {
super(text);
}

public MyLabel() {
}
}

之后:

public class App {
public static void main(String[] args) {

MyFrame frame1 = new MyFrame();
MyLabel label1 = new MyLabel("Welcome");
frame1.add(label1);
}
}
import javax.swing.JLabel;
public class MyLabel extends JLabel {
public MyLabel() {
super();
setText("Welcome");
}
}

是你需要的。您将代码隐藏在另一个不是子类的JLabel中。不过,这有点回避了一个问题:为什么要创建一个子类?为什么不直接使用JLabel呢?

最新更新