2013-03-18 138 views
1

爲什麼我的GUI不顯示任何按鈕,標籤或文本字段?爲什麼我的JFrame中沒有顯示任何內容?

我想我已經設置了所有設置,但是當我運行它時,只有框架顯示,並且沒有內容出現。

package BasicGame; 

import java.awt.Container; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JTextField; 
import javax.swing.SwingConstants; 

public class Gui extends JFrame{ 
    private static final long serialVersionUID = 1L; 
    private JLabel label; 
    private JTextField textField; 
    private JButton button; 
    private buttonHandler bHandler; 

    public Gui(){ 
     setTitle("Basic Gui"); 
     setResizable(false); 
     setSize(500, 200); 
     setVisible(true); 
     setDefaultCloseOperation(EXIT_ON_CLOSE);  

     Container pane = getContentPane(); 
     pane.setLayout(null); 


     button = new JButton("button"); 
     button.setBounds(50, 60, 50, 70); 
     bHandler = new buttonHandler(); 
     button.addActionListener(bHandler); 

     label = new JLabel("Hello", SwingConstants.RIGHT); 
     label.setBounds(50, 60, 50, 70); 

     textField = new JTextField(10); 
     textField.setBounds(50, 60, 50, 70); 

     pane.add(button); 
     pane.add(label); 
     pane.add(textField); 

    } 

    public class buttonHandler implements ActionListener{ 
     public void actionPerformed(ActionEvent e){ 
      System.exit(0); 
     } 
    } 

    @SuppressWarnings("unused") 
    public static void main(String[] args){ 
     Gui gui = new Gui(); 
    } 

} 

回答

3

將您的setVisible()移動到構造函數的末尾。在將JFrame設置爲up並使make可見之後,您將添加所有組件,因此您看不到任何更改。

這應該與所有的組件顯示您JFrame

public Gui(){ 
    setTitle("Basic Gui"); 
    setResizable(false); 
    setSize(500, 200); 
    setDefaultCloseOperation(EXIT_ON_CLOSE);  

    Container pane = getContentPane(); 
    pane.setLayout(null); 


    button = new JButton("button"); 
    button.setBounds(50, 60, 50, 70); 
    bHandler = new buttonHandler(); 
    button.addActionListener(bHandler); 

    label = new JLabel("Hello", SwingConstants.RIGHT); 
    label.setBounds(50, 60, 50, 70); 

    textField = new JTextField(10); 
    textField.setBounds(50, 60, 50, 70); 

    pane.add(button); 
    pane.add(label); 
    pane.add(textField); 
    setVisible(true); // Move it to here 
} 

下面是框架的樣子之前和之後,我搬到了setVisible聲明和編譯代碼。

前:

enter image description here

後:

enter image description here

+1

+1你說動或只是打一遍? – Smit 2013-03-18 23:23:30

+1

移動它。編輯源代碼以刪除錯誤的行。 – syb0rg 2013-03-18 23:24:19

+0

謝謝。這解決了它! – user2184376 2013-03-19 12:17:50

相關問題