你好,我现在正在制作一个简单的游戏,当你在游戏屏幕上时,你可以按 esc 打开菜单。有一个主菜单按钮,可将您从游戏屏幕带到主菜单屏幕,问题是它会将它们带到主菜单屏幕,但随后单击主屏幕上与游戏内相同位置的按钮菜单,因此它会在您释放按钮之前单击主菜单上的按钮。这是我的一些类(class)
这是我的菜单类(主屏幕)http://pastebin.com/kc5Dx2bp
这是我的游戏类(class)(游戏屏幕)http://pastebin.com/Gr3y9Amj
有没有办法让你在释放鼠标按钮之前无法单击另一个按钮?
最佳答案
基本上,您可以使用 ButtonModel
来跟踪按钮状态的更精细更改,然后 ActionListener
为您提供。
此示例监视模型的武装
和按下
状态,并根据特定条件采取行动。
这是一个小技巧,因为您正在寻找的状态不仅会在释放按钮时发生,而且还会在第一次按下按钮时发生。我们要做的就是等到上一个状态按下按钮并且按钮 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);
}
});
}
}
关于java - 在释放按钮之前不要单击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15913893/