简体   繁体   中英

jbutton as method actionlistener doesnt work

so I created JButton as a method like this

    private JButton loginButton() {
        JButton button = new JButton("Login");
        button.setFocusable(false);
        button.addActionListener(this);
        button.setFont(new Font("MV Boli", Font.PLAIN, 25));
        return button;
    }

when I try to test if the action listener works, it does nothing. Is this the wrong way how to create JButton and that's why it doesn't wrong or there is something wrong with my code?

    public void actionPerformed(ActionEvent e) {

        if (e.getSource() == loginButton()) {
            System.out.println("Test");
        }
    }
        this.setContentPane(mainPanel());
    }

    private JPanel mainPanel() {
        JPanel panel = new JPanel();
        panel.add(loginButton(), BorderLayout.SOUTH);
        panel.setVisible(true);
        return panel;
    }

Your loginButton() is creating a new button each time it is called. So, when you have

panel.add(loginButton(), BorderLayout.SOUTH);

in your mainPanel() method, you create the first button. But when you have

if (e.getSource() == loginButton())

in your actionPerformed() method you create a second button, which is different from the first one you created earlier. That's why your code will not enter the if() block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM