Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Basically, you can use the <code>ButtonModel</code> to track finer changes to the button state then <code>ActionListener</code> gives you.</p> <p>This example monitors the <code>armed</code> and <code>pressed</code> states of the model and takes action based on a certain condition.</p> <p>This is a small trick, as the state you are looking for will occur not only when the button is released, but also when the button is first pressed. What we do is wait until the previous state had the button pressed and the buttons <code>pressed</code> state is <code>false</code>, then we know we have a button release</p> <pre><code>import java.awt.EventQueue; import java.awt.GridBagLayout; import javax.swing.ButtonModel; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class TestButton05 { public static void main(String[] args) { new TestButton05(); } public TestButton05() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { } final JButton btn = new JButton("Clicked"); btn.getModel().addChangeListener(new ChangeListener() { private boolean wasPressed = false; @Override public void stateChanged(ChangeEvent e) { ButtonModel model = (ButtonModel) e.getSource(); if (model.isArmed() &amp;&amp; !model.isPressed() &amp;&amp; wasPressed) { System.out.println("Released"); } else { wasPressed = model.isPressed(); } } }); JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new GridBagLayout()); frame.add(btn); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload