Dies ist mein Code zum Erstellen eines Fensters mit Swing.Warum sind meine Komponenten unsichtbar?
Ich kann das Fenster der definierten Größe sehen, aber keine der Komponenten sind im Fenster vorhanden.
Warum sind die Komponenten nicht sichtbar?
Ich habe separate Methoden zum Erstellen, Initialisieren und Hinzufügen der Komponenten. Diese Methoden werden vom Konstruktor aufgerufen. Das Fenster mit Titel und definierter Größe ist in der Ausgabe sichtbar. Was vermisse ich?
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);
}
}