JButton出版社(未发布)

时间:2013-06-06 10:19:47

标签: java swing jbutton actionlistener

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

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

但我意识到,只要首先按下然后释放按钮,它就能完成我想要的东西。怎么能这样做呢? 谢谢

2 个答案:

答案 0 :(得分:3)

单击表示已按下并释放按钮。单击按钮时会触发单击事件,并且仅在释放鼠标时按钮仍处于布防状态(鼠标位于按钮范围内)时才会触发。要处理按下事件,请使用低级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*/

    });

答案 1 :(得分:1)

以上回答仅对鼠标事件做出反应,但是当它具有输入焦点时,可以使用空格键切换按钮按下状态。 要获得完整的实现,请使用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();
    }
});