2017-07-30 61 views
0

我注意到的東西,我認爲是奇怪,這下面的代碼:Swing類中,JLabel的appearence異常

public class QuestionFour extends JFrame { 
    private JTextArea txta1; 
    private JTextField txt1; 
    private JButton btnSort; 
    private JButton btnShuffle; 
    private JButton btnReverse; 
    private JPanel pnl1; 
    private JLabel lbl1; 
    private LinkedList linkedList; 

    public QuestionFour() { 
     super(); 
     this.setLocationRelativeTo(null); 
     this.setSize(500, 200); 
     this.setVisible(true); 
     this.setLayout(new FlowLayout()); 
     txt1 = new JTextField(); // 1 
     lbl1 = new JLabel("Enter a number: "); // 2 
     this.add(lbl1); 
    } 

    public static void main(String args[]) { 
     QuestionFour ob = new QuestionFour(); 
    } 
} 

這是存在的是,當我運行代碼的JLabel不會出現問題,但如果我註釋鍵入1作爲註釋的行,JLabel出現,我認爲這很奇怪,因爲我只實例化了TextField,但沒有將它添加到JFrame中。

有人可以向我解釋這個嗎?

回答

0

可能是由UI線程以外調用setVisible(true)引起的異常。試試這個:

public QuestionFour() 
{ 
    setLocationRelativeTo(null); 
    this.setSize(500, 200); 
    setLayout(new FlowLayout()); 
    this.txt1 = new JTextField(); // 1 
    this.lbl1 = new JLabel("Enter a number: "); // 2 
    this.add(this.lbl1); 

    javax.swing.SwingUtilities.invokeLater(() -> setVisible(true)); 
} 

注意:讀/寫訪問到任何UI組件(如JTextField等)必須得到事件調度線程(UI線程)內完成。 SwingUtilities爲您提供了便捷的方法。您也應該在EDT內調用setVisible()

還有一個問題是,你在開始時調用setVisible(true),然後添加UI組件,遲到了。這表示對UI組件的「寫入權限」(「您正在向主面板添加內容」)。您的類構造函數不在EDT內運行,因此在這種情況下,您必須將this.add(this.lbl1)封裝到SwingUtilities的方法中。但是最好先構建整個UI,然後再將其設置爲可見。

有關Swing庫和線程安全的更多信息,請看看這個:https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html