Java JFrame-等待用户按下按钮

Java JFrame-等待用户按下按钮,java,swing,jframe,Java,Swing,Jframe,我目前正在开发一个聊天程序的登录表单,希望该程序加载框架并等待用户输入。 不幸的是,程序打开了框架,但同时恢复了主方法。 我希望你有一些想法来帮助我 问候 public static void main(String[] args){ boolean running = true; //Starting JFrame chatFrame.loginFrame(); //Processing - Receivi

我目前正在开发一个聊天程序的登录表单,希望该程序加载框架并等待用户输入。 不幸的是,程序打开了框架,但同时恢复了主方法。 我希望你有一些想法来帮助我

问候

public static void main(String[] args){  

        boolean running = true;  

        //Starting JFrame
        chatFrame.loginFrame(); 

            //Processing - Receiving Status from Login method
            if(getStatus() == 1){  

                ... 
            } else { 
                System.out.println("An Error occured.."); 
                System.exit(0); 
            }

        }
JFrame类:

public class chatFrame{ 

    private static String sLogin;  
    private static String password; 


    public static void loginFrame(){ 
        System.out.println("Launching Frame"); 
        JFrame loginFrame = new JFrame();
        loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

        JTextField user = new JTextField("Username");
        JTextField pass = new JTextField("Password");
        JButton login = new JButton("Login");

        loginFrame.setLayout(new BorderLayout());
        loginFrame.add(user, BorderLayout.NORTH);
        loginFrame.add(pass, BorderLayout.CENTER);
        loginFrame.add(login, BorderLayout.SOUTH);

        loginFrame.pack();  
        loginFrame.setSize(250, 150);
        loginFrame.setVisible(true);   

            login.addActionListener(new ActionListener(){ 

                public void actionPerformed(ActionEvent e){
                    System.out.println("Action performed"); 
                    String sLogin = user.getText();  
                    String password = pass.getText(); 

                    //Calling Login method
                    ClEngine.login(sLogin, password);
                    System.out.println("dataIn:" + dataIn);
                    loginFrame.setVisible(false);
                } 
            });   
    } 
}

发生这种情况是因为您正在通过调用

chatFrame.loginFrame(); 
但程序继续,然后退出主方法并结束应用程序


使用回调来验证用户事件…

发生这种情况是因为您正在通过调用

chatFrame.loginFrame(); 
但程序继续,然后退出主方法并结束应用程序


使用回调来验证用户事件…

您希望等待用户完成对应用程序窗口的操作的响应,有几种可能的方法来解决此问题。最简单的,也是我推荐的一种方法是将登录窗口设置为模式JDialog,而不是JFrame。这样,当对话框可见时,调用代码的程序流将停止,一旦关闭,调用程序的代码流将恢复,然后它可以查询对话框的状态,找出是否输入了数据,以及数据是否有效

另一个选项是允许外部类将监听器添加到登录窗口中,例如将ActionListener添加到其按钮或WindowListener中,但处理起来有点复杂

比如说

import java.awt.Window;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;

import javax.swing.*;

public class ChatLogin extends JPanel {
    private static JDialog dialog;
    private static ChatLogin chatLogin;
    private static boolean loginValid;
    private JTextField userNameField = new JTextField(10);
    private JPasswordField passwordField = new JPasswordField(10);

    public ChatLogin() {
        JPanel inputPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(2, 10, 2, 2);
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        inputPanel.add(new JLabel("User Name:"), gbc);

        gbc.gridy = 1;
        inputPanel.add(new JLabel("Password:"), gbc);

        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.EAST;
        gbc.insets = new Insets(2, 2, 2, 2);
        inputPanel.add(userNameField, gbc);

        gbc.gridy = 1;
        inputPanel.add(passwordField, gbc);

        JPanel btnPanel = new JPanel(new GridLayout(1, 0, 2, 2));
        btnPanel.add(new JButton(new LoginAction()));

        setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
        setLayout(new BorderLayout());
        add(inputPanel, BorderLayout.CENTER);
        add(btnPanel, BorderLayout.PAGE_END);
    }

    public String getUserName() {
        return userNameField.getText();
    }

    public char[] getPassword() {
        return passwordField.getPassword();
    }

    public static boolean isLoginValid() {
        return loginValid;
    }

    private class LoginAction extends AbstractAction {
        public LoginAction() {
            super("Login");
            putValue(MNEMONIC_KEY, KeyEvent.VK_L);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            loginValid = true;
            Window win = SwingUtilities.getWindowAncestor(ChatLogin.this);
            win.dispose();
        }
    }

    public static JDialog getInstance(Window win, String title) {
        dialog = new JDialog(win, title, ModalityType.APPLICATION_MODAL) {
            @Override
            public void setVisible(boolean b) {
                loginValid = false;
                super.setVisible(b);
            }
        };
        chatLogin = new ChatLogin();
        dialog.add(chatLogin);
        dialog.pack();
        dialog.setLocationRelativeTo(win);
        return dialog;
    }

    public static JDialog getInstance() {
        if (dialog == null) {
            return getInstance(null, "Login");
        } else {
            return dialog;
        }
    }

    public static ChatLogin getChatLoginInstance() {
        return chatLogin;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            ChatLogin.getInstance().setVisible(true);
            if (ChatLogin.isLoginValid()) {
                ChatLogin chatLogin = ChatLogin.getChatLoginInstance();
                String userName = chatLogin.getUserName();
                String password = new String(chatLogin.getPassword()); // not a safe thing to do

                // here test that user name and password are valid
                System.out.println("user name: " + userName);
                System.out.println("Password:  " + password);
            }
        });
    }

}

您的愿望是等待用户完成应用程序窗口工作后的响应,有几种可能的方法可以解决这个问题。最简单的,也是我推荐的一种方法是将登录窗口设置为模式JDialog,而不是JFrame。这样,当对话框可见时,调用代码的程序流将停止,一旦关闭,调用程序的代码流将恢复,然后它可以查询对话框的状态,找出是否输入了数据,以及数据是否有效

另一个选项是允许外部类将监听器添加到登录窗口中,例如将ActionListener添加到其按钮或WindowListener中,但处理起来有点复杂

比如说

import java.awt.Window;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;

import javax.swing.*;

public class ChatLogin extends JPanel {
    private static JDialog dialog;
    private static ChatLogin chatLogin;
    private static boolean loginValid;
    private JTextField userNameField = new JTextField(10);
    private JPasswordField passwordField = new JPasswordField(10);

    public ChatLogin() {
        JPanel inputPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(2, 10, 2, 2);
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        inputPanel.add(new JLabel("User Name:"), gbc);

        gbc.gridy = 1;
        inputPanel.add(new JLabel("Password:"), gbc);

        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.EAST;
        gbc.insets = new Insets(2, 2, 2, 2);
        inputPanel.add(userNameField, gbc);

        gbc.gridy = 1;
        inputPanel.add(passwordField, gbc);

        JPanel btnPanel = new JPanel(new GridLayout(1, 0, 2, 2));
        btnPanel.add(new JButton(new LoginAction()));

        setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
        setLayout(new BorderLayout());
        add(inputPanel, BorderLayout.CENTER);
        add(btnPanel, BorderLayout.PAGE_END);
    }

    public String getUserName() {
        return userNameField.getText();
    }

    public char[] getPassword() {
        return passwordField.getPassword();
    }

    public static boolean isLoginValid() {
        return loginValid;
    }

    private class LoginAction extends AbstractAction {
        public LoginAction() {
            super("Login");
            putValue(MNEMONIC_KEY, KeyEvent.VK_L);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            loginValid = true;
            Window win = SwingUtilities.getWindowAncestor(ChatLogin.this);
            win.dispose();
        }
    }

    public static JDialog getInstance(Window win, String title) {
        dialog = new JDialog(win, title, ModalityType.APPLICATION_MODAL) {
            @Override
            public void setVisible(boolean b) {
                loginValid = false;
                super.setVisible(b);
            }
        };
        chatLogin = new ChatLogin();
        dialog.add(chatLogin);
        dialog.pack();
        dialog.setLocationRelativeTo(win);
        return dialog;
    }

    public static JDialog getInstance() {
        if (dialog == null) {
            return getInstance(null, "Login");
        } else {
            return dialog;
        }
    }

    public static ChatLogin getChatLoginInstance() {
        return chatLogin;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            ChatLogin.getInstance().setVisible(true);
            if (ChatLogin.isLoginValid()) {
                ChatLogin chatLogin = ChatLogin.getChatLoginInstance();
                String userName = chatLogin.getUserName();
                String password = new String(chatLogin.getPassword()); // not a safe thing to do

                // here test that user name and password are valid
                System.out.println("user name: " + userName);
                System.out.println("Password:  " + password);
            }
        });
    }

}