метод создания простого логина неправильный - PullRequest
1 голос
/ 07 апреля 2020

Я новичок ie в Java GUI разработке и застрял в следующем коде.
Я открыт для предложений. Я на самом деле пытаюсь создать простой логин, который дает ОК, если пароль соответствует номеру 3124, и в противном случае показывает сообщение об ошибке. Пожалуйста, помогите мне.

    import java.awt.EventQueue;

        import javax.swing.JFrame;
        import javax.swing.JOptionPane;
        import javax.swing.JButton;
        import java.awt.event.ActionListener;
        import java.awt.event.ActionEvent;
        import javax.swing.JTextField;

    public class testing {

        private JFrame frame;
        private JTextField username;
        private JTextField password;

        /**
         * Launch the application.
         */
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        testing window = new testing();
                        window.frame.setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        /**
         * Create the application.
         */
        public testing() {
            initialize();
        }

        /**
         * Initialize the contents of the frame.
         */
        private void initialize() {
            frame = new JFrame();
            frame.setBounds(100, 100, 450, 300);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().setLayout(null);

            JButton btnNewButton_1 = new JButton("cancel");
            btnNewButton_1.setBounds(266, 181, 109, 56);
            frame.getContentPane().add(btnNewButton_1);

            username = new JTextField();
            username.setBounds(227, 11, 128, 39);
            frame.getContentPane().add(username);
            username.setColumns(10);

            password = new JTextField();
            password.setBounds(227, 76, 128, 39);
            frame.getContentPane().add(password);
                final int num;
                num=Integer.parseInt(password);
            password.setColumns(10);

            JButton btnNewButton = new JButton("login");
            btnNewButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if(num==3124)
                        {JOptionPane.showMessageDialog(null, "correct");}
                    else
                        {JOptionPane.showMessageDialog(null, "wrong");}
                }
            });
            btnNewButton.setBounds(62, 181, 123, 56);
            frame.getContentPane().add(btnNewButton);
        }
    }

1 Ответ

0 голосов
/ 07 апреля 2020

Вы проверяли пароль еще до того, как у пользователя была возможность ввести что-либо в текстовое поле. Вам необходимо получить и проверить значение num в коде прослушивателя событий, т.е. в actionPerformed. Кроме того, не конвертируйте пароль в int (кто-то может ввести некоторую строку без нумерации c)

Этот код ниже работает лучше.

    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JButton;
    import java.awt.event.ActionListener;
    import java.awt.EventQueue;
    import java.awt.event.ActionEvent;
    import javax.swing.JTextField;

    public class Testing {

        private JFrame frame;
        private JTextField username;
        private JTextField password;

        /**
         * Launch the application.
         */
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        Testing window = new Testing();
                        window.frame.setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        /**
         * Create the application.
         */
        public Testing() {
            initialize();
        }

        /**
         * Initialize the contents of the frame.
         */
        private void initialize() {
            frame = new JFrame();
            frame.setBounds(100, 100, 450, 300);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().setLayout(null);

            JButton btnNewButton_1 = new JButton("cancel");
            btnNewButton_1.setBounds(266, 181, 109, 56);
            frame.getContentPane().add(btnNewButton_1);

            username = new JTextField();
            username.setBounds(227, 11, 128, 39);
            frame.getContentPane().add(username);
            username.setColumns(10);

            password = new JTextField();
            password.setBounds(227, 76, 128, 39);
            frame.getContentPane().add(password);
            password.setColumns(10);

            JButton btnNewButton = new JButton("login");
            btnNewButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {

                    final String num;
                    num = (password.getText());

                    if (num.equalsIgnoreCase("3124")) {
                        JOptionPane.showMessageDialog(null, "correct");
                    } else {
                        JOptionPane.showMessageDialog(null, "wrong");
                    }
                }
            });
            btnNewButton.setBounds(62, 181, 123, 56);
            frame.getContentPane().add(btnNewButton);
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...