java - JFrame - 等待用户按下按钮

标签 java swing jframe

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

问候

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

最佳答案

您的愿望是等待用户完成应用程序窗口工作的响应,有几种可能的方法可以解决此问题。最简单的方法(也是我推荐的方法)是将登录窗口设为模态 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);
            }
        });
    }

}

关于java - JFrame - 等待用户按下按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40810366/

相关文章:

java - JFrame 中的 NullPointerException

java-如何生成指定值范围内的随机十六进制值

Java netbeans 表单 - 从组合框中获取值

java - Spring - 从项目结构加载文件夹作为目录?

Java JTable 头不显示

java - 使用awt java选择后在字符串中保存值

java - 如何从函数返回 JButton 并使用它在 java 中的不同类中执行操作?

java - 将 JPanelForm 类转换为 JFrameForm 类

java - 应用程序关闭时 Android 警报管理器挂起 Intent

java - Spring Boot OAuth2 不重定向到 facebook