繁体   English   中英

如何检查用户是否单击了JPanel中的任何按钮

[英]How to check if any button in JPanel is clicked by a user

我一直在做巴士预订项目,并且已经在预订页面。

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--;
                }
            });
           }         

ActionListener添加到JButton ,请在此处查看示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM