简体   繁体   English

jbutton作为方法actionlistener不起作用

[英]jbutton as method actionlistener doesnt work

so I created JButton as a method like this所以我创建了 JButton 作为这样的方法

    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?这是如何创建 JButton 的错误方法,这就是为什么它没有错或者我的代码有问题?

    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.您的loginButton()每次调用时都会创建一个新按钮。 So, when you have所以,当你有

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

in your mainPanel() method, you create the first button.在您的mainPanel()方法中,您创建了第一个按钮。 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.在您的actionPerformed()方法中,您创建了第二个按钮,这与您之前创建的第一个按钮不同 That's why your code will not enter the if() block.这就是您的代码不会进入if()块的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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