基本上,你可以使用ButtonModel
来跟踪按钮状态的更精细的改变,然后ActionListener
给你。
本示例监视模型的armed
和pressed
状态,并根据一定条件采取措施。
这是一个小窍门,因为您正在寻找的状态不仅会在释放按钮时发生,还会在按钮被第一次按下时发生。我们做的是等待,直到先前的状态了按钮按下,按钮pressed
状态false
,那么我们就知道我们有一个按钮释放
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() && !model.isPressed() && 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);
}
});
}
}
请张贴SSCEE(http://sscce.org)帮助你的帮手,因为那时帮助你简单得多。 – 2013-04-09 22:52:22