如何在构造函数外添加mouselisteners

时间:2016-09-07 13:41:10

标签: java jbutton mouselistener

在下面的示例中,当您按下它们时,按钮和按钮2都应该变得不可点击。当您按下重置按钮时,两个禁用的按钮应该再次起作用。

由于我通过删除mouseListeners使两个按钮不可点击,如何使用check()方法添加mouseListeners,以便它们仍以相同的方式再次运行?

public static boolean isreset = false;
public static JButton button = new JButton("Disable button 1");
public static JButton button2 = new JButton("Disable button 2");
public static JButton reset = new JButton("Reset all buttons");

Test() {
    setTitle("Button Test");
    setSize(420, 80);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel buttons = new JPanel(new GridBagLayout());
    GridBagConstraints gc = new GridBagConstraints();
    gc.fill = GridBagConstraints.BOTH;
    gc.gridheight = 1;
    gc.gridwidth = 1;

    gc.gridx = 0;
    gc.gridy = 0;
    buttons.add(button, gc);

    gc.gridx = 1;
    gc.gridy = 0;
    buttons.add(button2, gc);

    gc.gridx = 3;
    gc.gridy = 0;
    buttons.add(reset, gc);

    add(buttons);

    button.addMouseListener(new Mouse(){
        public void mousePressed(MouseEvent e){
            button.setEnabled(false);
            button.removeMouseListener(this);
            System.out.println("You pressed button 1.");
            isreset = false;
            check(isreset);
        }
    });

    button2.addMouseListener(new Mouse(){
        public void mousePressed(MouseEvent e){
            button2.setEnabled(false);
            button2.removeMouseListener(this);
            System.out.println("You pressed button 2.");
            isreset = false;
            check(isreset);
        }
    });

    reset.addMouseListener(new Mouse(){
        public void mousePressed(MouseEvent e){
            isreset = true;
            check(isreset);
        }
    });

    setVisible(true);
}

public static void check (boolean input){
    if(input == true){
        Test.button.setEnabled(true);
        Test.button.addMouseListener(this); //error here
        Test.button2.setEnabled(true);
        Test.button2.addMouseListener(this); //error here
    }
}   

1 个答案:

答案 0 :(得分:1)

代码中的所有内容都是static。那不是你编写JFrame子类的方式。我建议你先阅读一些示例代码。

您不必每次都删除鼠标侦听器。只需拨打setEnabled即可。

另外,您应该拨打addActionListener而不是addMouseListener

示例:

button.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        button.setEnabled(false);
        System.out.println("You pressed button 1.");
        isreset = false;
        check(isreset);
    }
});