请帮我看看我错过了什么。我正在把头发拉出来,对这个问题感到沮丧。
我有30个JToggle和2个按钮。按下确认按钮后,我想打印出单击了哪个toggleButton。
即使我点击了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");
}
}
}
});
}
答案 0 :(得分:4)
您的程序当前根据您的实现为每个按钮提供输出,因此当您单击confirm
时,它将打印切换按钮的数量,而对于所有其他按钮,它将打印“没有按钮被单击”。如果您只想打印切换按钮的数量或“没有按钮被单击”,如果没有切换按钮,则需要将实现更改为:
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");
}
}
});
希望这有帮助。