4

我有一个非常小的 JButton,名为“b”,我想在点击时而不是在释放时做一些事情。我使用以下代码:

b.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e){
            //do some stuff
        }
    });

但我意识到,只要单击第一次按下然后释放,它就会执行我想要的操作。我怎么能这样做?谢谢

4

2 回答 2

4

单击表示按钮已被按下和释放。单击按钮时触发单击事件,并且仅当释放鼠标时按钮仍处于武装状态(鼠标在按钮范围内)时才会触发。要处理按下事件,请使用低级MouseListener

btn.addMouseListener(new MouseListener() {

    @Override
    public void mousePressed(MouseEvent e) {
        //do some stuff
    }

    /*Override other methods*/

});

或者更好地使用MouseAdapter

btn.addMouseListener(new MouseAdapter() {

        @Override
        public void mousePressed(MouseEvent e) {
            //do some stuff
        }

        /*No need to override other methods, `MouseAdapter` already does it*/

    });
于 2013-06-06T10:29:39.553 回答
2

上面的答案只对鼠标事件做出反应,但是当它具有输入焦点时,可以使用空格键来切换按钮按下状态。对于完整的实现,请使用 MouseListener AND KeyListener。

b.addMouseListener(new MouseListener() {

    public void mouseClicked(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {
        doOnPressedAction();
    }
    public void mouseReleased(MouseEvent e) {
        doOnReleasedAction();
    }
});
b.addKeyListener(new KeyListener(){
    public void keyTyped(KeyEvent e) {}

    public void keyPressed(KeyEvent e) {
        if (sendButton.getModel().isPressed()) {
            doOnPressedAction();
        } else {
            // just in case it can happen that the button is released on
            // a key press action (maybe another controls key listener...)
            doOnReleasedAction();
        }
    }

    public void keyReleased(KeyEvent e) {
        doOnReleasedAction();
    }
});
于 2014-09-20T12:02:52.660 回答