2017-03-16 64 views
-1

我在OSX上使用NetBeans 8.2,當我運行我的代碼時,我得到一個窗口,它具有正確的標題,但沒有組件出現。我確信我的所有框架都設置爲可見,但問題仍然存在。JFrame丟失內容GridBagLayout與面板

public Project(){ 
    setTitle("Panel"); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setSize(400, 200); 
    setLocationRelativeTo(null); 
    setLayout(new GridBagLayout()); 
    setVisible(true); 

    GridBagConstraints layout = new GridBagConstraints(); 
    layout.gridy = 3; 

    JPanel topPanel = new JPanel(); 
    topPanel.setVisible(true); 
    topPanel.setLayout(new GridLayout(2,1)); 
    topPanel.add(label1); 
    topPanel.add(textField1); 

    JPanel midPanel = new JPanel(); 
    midPanel.setVisible(true); 
    midPanel.setLayout(new GridLayout(1,1)); 
    midPanel.add(button1); 

    JPanel bottomPanel = new JPanel(); 
    bottomPanel.setVisible(true); 
    bottomPanel.setLayout(new GridLayout(2,1)); 
    bottomPanel.add(label2); 
    bottomPanel.add(textField2); 

    add(topPanel); 
    add(midPanel); 
    add(bottomPanel); 
    } 

    public static void main(String[] args) { 
    Project1 frame = new Project1(); 
    } 

回答

1

採取setVisible(true);並使其您可以在構造函數中調用的最後一件事

public Project(){ 
    setTitle("Panel"); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setSize(400, 200); 
    setLocationRelativeTo(null); 
    setLayout(new GridBagLayout()); 
    //setVisible(true); 
    //... 
    setVisible(true); 
} 

你也應該確保用戶界面是被事件的調度範圍內螺紋

內構建
public static void main(String[] args) { 
    SwingUtilities.invokeLater(new Runnable() { 
     @Override 
     public void run() { 
      Project1 frame = new Project1(); 
     } 
    }); 
} 

這將有助於防止可能發生的一些奇怪