检测点击了哪个 toggleButotn

Detect which toggleButotn was clicked

请帮我检查一下我在这里遗漏了什么。我正在努力解决这个问题并对这个问题感到沮丧。

我有 30 个 JToggle 和 2 个按钮。按下确认按钮时,我想打印出单击了哪个切换按钮。

我得到的输出总是没有点击按钮,即使我已经点击了 toggleButton。

public selectSeat(String title, String day, String time)
    {
        JPanel topPanel= new JPanel(new GridLayout(1, 215));
        RectDraw rect= new RectDraw();
        rect.setPreferredSize(new Dimension(3,25)); 
        topPanel.add(rect);

          JToggleButton[] ButtonList = new JToggleButton[30];

            JPanel ButtonPanel= new JPanel(new GridLayout(5,25,45,25)); // row,col,hgap,vgap
            for(int i = 0; i < 30; i++) {   
                int a=i+1;
                ButtonList[i]= new JToggleButton(""+a);
                ButtonPanel.add(ButtonList[i]);

            }

            JPanel bottomPanel = new JPanel(new GridLayout(1,5,40,20));
            JButton cancel= new JButton("Cancel");
            JButton confirm= new JButton("Confirm");
            bottomPanel.add(cancel);
            bottomPanel.add(confirm);

           setLayout(new BorderLayout(0, 45));
           add(topPanel, BorderLayout.PAGE_START);
           add(ButtonPanel, BorderLayout.CENTER);
           add(bottomPanel, BorderLayout.PAGE_END);
           ButtonPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
           bottomPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 20, 20)); //top,left,bottom,right

           confirm.addActionListener(new ActionListener()
                   {
               public void actionPerformed(ActionEvent e)
               {
                   for(int i=0;i<30;i++)
                 {
                    if(ButtonList[i].isSelected())
                        {
                         System.out.println(i);
                        }                   
                   else  {
                       System.out.println("No button is clicked");
                   }
                    }    
        }
      });
               }

您的程序当前根据您的实现为每个按钮提供输出,因此当您单击 confirm 时,它将打印切换按钮的数量,对于所有其他按钮,它将打印 "No button is Clicked"。如果您只想打印切换按钮的数量或 "No button is clicked" 如果没有按钮被切换,那么您需要将您的实现更改为:

confirm.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                boolean buttonClicked = false;
                for (int i = 0; i < 30; i++) {
                    if (ButtonList[i].isSelected()) {
                        buttonClicked = true;
                        System.out.println(i);
                    }
                }
                if (!buttonClicked) {
                    System.out.println("No button is clicked");
                }
            }

        });

希望对您有所帮助。