我一直在做一个巴士预订项目,并且制作了一个预订页面。
JPanel
名为 PanelSeat
,里面包含按钮(大约 36 个按钮)。
我想检查 JPanel
中的任何按钮是否被单击,然后禁用该按钮,最后如果用户单击 util 3 按钮,它将被停止或用户无法再单击它。
这是我到目前为止编写的代码:
private void CountTicket() {
try {
int count = 3;
Component[] components = PanelSeat.getComponents();
for (int i = 0; i < components.length; i++) {
if (components[i] instanceof JButton) {
if (((JButton) components[i]).isSelected()) { // I wanna check if any button is clicked by a user
if (JOptionPane.showConfirmDialog(this, "Seat Confirmation") == JOptionPane.YES_OPTION) { // confirm message
((JButton) components[i]).setEnabled(false); // disable the button
count--;
System.out.println("Your ramaining seat : " + count);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
如何检查按钮是否被点击?
最佳答案
由于您想要计算按钮被按下的次数,然后在涉及计数的情况下禁用它,我建议您包装 Jbutton 类以便更轻松地执行这些任务,此解决方案通常更好
class JbuttonWrapper extends JButton {
int count=0;
public void increment()
{
count++;
if (count==numberOfclicksToDisable)
{
this.setEnabled(false);
}
}
}
//then you can simply do the following.
JbuttonWrapper [] buttons= new JbuttonWrapper [NumbersOfButtonsYouHave];
for (int i=0; i<=NumbersOfButtonsYouHave;i++)
{
buttons[i].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { buttons[i].increment(); } });
}
此解决方案基于您的代码
static int count=3;
Component[] components = PanelSeat.getComponents();
for (int i = 0; i < components.length; i++) {
if (components[i] instanceof JButton) {
{
components[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
count--;
}
});
}
关于java - 如何检查用户是否单击了 JPanel 中的任何按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32689823/