John Joe John Joe - 6 months ago 8
Java Question

Detect which toggleButotn was clicked

please help me to check what I have missed here. I am pulling my hair out of this and getting frustrated on this problems.

I have 30 JToggle and 2 buttons. When confirm button is pressed, I want to print out which toggleButton is clicked.

The output I get is always No button clicked even though I have clicked toggleButton.

enter image description here

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

Answer

Your program currently gives output for each button as per your implementation hence when you click confirm it will print the number of toggled button and for all others it will print "No button is Clicked". If you just want to print the number of toggled button or "No button is clicked" if no button was toggled then you need to change your implementation to:

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

        });

Hope this helps.

Comments