我正在嘗試將 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);
}
}
uj5u.com熱心網友回復:
你在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);
}
}
uj5u.com熱心網友回復:
import javax.swing.JLabel;
public class MyLabel extends JLabel {
public MyLabel() {
super();
setText("Welcome");
}
}
是你需要的。您將代碼隱藏在另一個不是JLabel您的子類中。不過,它有點引出了一個問題:你為什么要創建一個子類?為什么不直接使用右關?JLabel
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/489650.html
上一篇:如何在標題邊框內設定背景?
