我一直在尝试用Java制作GUI,而不是一直使用“静态”,并且遇到了“SwingUtilities.invokeLater()”方法。我设法进行了所有设置,但是当要运行该应用程序时,在我调整窗口大小之前,JPanel上什么也没有出现。有没有解决的办法,或者我做错了吗?

这是我的代码:

public class main extends JPanel implements ActionListener{
public JLabel userLabel;
public JLabel passLabel;
public JTextField userField;
public JTextField passField;
public JButton login;
public JButton closeLogin;
public JButton help;

public main(){
    userLabel = new JLabel("Username: ");
    passLabel = new JLabel("Password: ");
    userField = new JTextField(16);
    passField = new JTextField(16);

    login = new JButton("Login");
    login.setActionCommand("login");
    login.setMnemonic(KeyEvent.VK_L);
    closeLogin = new JButton("Close");
    closeLogin.setActionCommand("closeLogin");
    closeLogin.setMnemonic(KeyEvent.VK_E);
    help = new JButton("Help");
    help.setActionCommand("helpLogin");
    help.setMnemonic(KeyEvent.VK_H);

    login.addActionListener(this);
    closeLogin.addActionListener(this);
    help.addActionListener(this);

    add(userLabel);
    add(userField);
    add(passLabel);
    add(passField);
    add(login);
    add(help);
    add(closeLogin);

}
public void actionPerformed(ActionEvent e){
}
public static void initComponents(){
    JFrame loginFrame = new JFrame("Encrypted Chat - Login");
    loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    main loginPanel = new main();
    loginPanel.setLayout(new FlowLayout());
    loginFrame.setSize(300, 125);
    loginFrame.setResizable(false);
    loginFrame.setVisible(true);
}
public static void main(String args[]){
    SwingUtilities.invokeLater(new Runnable(){
        public void run(){
            initComponents();
        }
    });
}

}

编辑:我知道密码JTextField是一个JPasswordField ..因此,请忽略它:P

最佳答案

您永远不会将内容添加到JFrame。您需要进行的最少更改:

  public static void main(String args[]){
    final main main = new main();
    SwingUtilities.invokeLater(new Runnable(){
      public void run(){
        initComponents(main);
      }
    });
  }

然后修改initComponents以采用main对象:
  public static void initComponents(main main){
    JFrame loginFrame = new JFrame("Encrypted Chat - Login");
    loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    main loginPanel = new main();
    loginPanel.setLayout(new FlowLayout());
    loginFrame.setSize(300, 125);
    loginFrame.setResizable(false);
    loginFrame.setVisible(true);
    loginFrame.add(main);  // <----- this line is added
  }

10-04 18:03