jbutton press(未发布)

qco9c6ql  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(324)

我有一个非常小的jbutton叫做“b”,我想在点击时做一些事情,而不是在发布时。我使用以下代码:

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

但我意识到,只要点击被按下,然后被释放,它就会做我想要的事情。我怎么能这么做?谢谢您

brc7rcf0

brc7rcf01#

点击意味着一个按钮被按下和释放。单击按钮时触发单击事件,并且仅当释放鼠标时按钮仍处于待命状态(鼠标位于按钮的边界内)。要处理pressed事件,请使用低级 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*/

    });
00jrzges

00jrzges2#

上面的答案只对鼠标事件有React,但当有输入焦点时,可以使用空格键切换按钮按下的状态。对于完整的实现,请使用mouselistener和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();
    }
});

相关问题