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);
}
}