I have a very small JButton called "b", which I want to do some things on click and not on release of it. I use the following code:
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
//do some stuff
}
});
But what I realize is that it does the stuff I want as soon as the click is first pressed and then released. How can this be done my way? Thank you
A click means that a button has been pressed and released. A click event is triggered when a button is clicked and only if the button is still armed(mouse within the bounds of the button) when mouse is released. To handle the pressed event, use the low-level MouseListener
btn.addMouseListener(new MouseListener() {
@Override
public void mousePressed(MouseEvent e) {
//do some stuff
}
/*Override other methods*/
});
Or better use a MouseAdapter
btn.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
//do some stuff
}
/*No need to override other methods, `MouseAdapter` already does it*/
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With