2016-12-18 175 views
1

這是我使用swing創建窗口的代碼。爲什麼我的組件不可見?

我可以看到已定義大小的窗口,但窗口中沒有任何組件。爲什麼組件不可見?

我有單獨的方法用於創建,初始化和添加組件。這些方法是從構造函數調用的。標題和定義大小的窗口在輸出中可見。我錯過了什麼?

package swing_basics; 

import java.awt.FlowLayout; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPasswordField; 
import javax.swing.JTextField; 

public class MySwingDemo extends JFrame { 

    JLabel lblName, lblPassword; //Declaration of variables 
    JTextField txtfName; 
    JPasswordField pwdfPassword; 
    JButton btnSubmit, btnCancel, btnReset; 

    public void createComponents(){ //method to initialise the components 

     lblName = new JLabel(); 
     lblPassword = new JLabel(); 
     txtfName = new JTextField(); 
     pwdfPassword = new JPasswordField(); 
     btnSubmit = new JButton(); 
     btnCancel = new JButton(); 
     btnReset = new JButton(); 
    } 

    public void setComponents(){ //method to set the components 
     setVisible(true); 
     setSize(400, 400); 
     setTitle("My Swing Demo"); 
     setLayout(new FlowLayout()); 

     lblName.setText("Name"); 
     lblPassword.setText("Password"); 

     txtfName.setText("Name");// try 

     pwdfPassword.setText("Password"); 

     btnSubmit.setText("Submit"); 
     btnCancel.setText("Cancel"); 
     btnReset.setText("Reset"); 
    } 

    public void addComponents(JFrame frame){ //method to add the components 
     frame.add(lblName); 
     frame.add(txtfName); 

     frame.add(lblPassword); 
     frame.add(pwdfPassword); 

     frame.add(btnSubmit); 
     frame.add(btnCancel); 
     frame.add(btnReset); 
    } 

    public static void main(String[] args) { 
     new MySwingDemo(); 
    } 

    public MySwingDemo() { //Constructor 
     createComponents(); 
     setComponents(); 
     addComponents(this); 
    } 

} 

回答

3

這是操作的,你設置frame可見您添加(和設置)之前,你的組件的順序。在之後,請將setVisible(true);移至您已設置好組件。 ,請確保您致電addComponents(this);之前您撥打setComponents();

public MySwingDemo() { // Constructor 
    createComponents(); 
    addComponents(this); 
    setComponents(); 
} 

我還想添加默認frame關閉操作

public void setComponents() { // method to set the components 
    setSize(400, 400); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    setTitle("My Swing Demo"); 
    setLayout(new FlowLayout()); 

    lblName.setText("Name"); 
    lblPassword.setText("Password"); 

    txtfName.setText("Name");// try 

    pwdfPassword.setText("Password"); 

    btnSubmit.setText("Submit"); 
    btnCancel.setText("Cancel"); 
    btnReset.setText("Reset"); 
    setVisible(true); 
}