Home > Software engineering >  jbutton as method actionlistener doesnt work
jbutton as method actionlistener doesnt work

Time:07-17

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

CodePudding user response:

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.

  • Related