我试着运行下面的代码,但是当单选按钮trueButton或falseButton被选中时,它不会跳出for循环。跳出for循环
for(;;){
if (trueButton.isSelected() || falseButton.isSelected()){
System.out.print("Selected");
break;
}
}
但是,如果我添加System.out.println(“”);在if语句之前,当选择trueButton或falseButton时,我可以跳出for循环。
for(;;){
System.out.println("");
if (trueButton.isSelected() || falseButton.isSelected()){
System.out.print("Selected");
break;
}
}
反正我有可以打破循环,而不if语句之前加入的System.out.println(“”)?
如果有人能解释第一个代码为什么不起作用,那将会很棒。
由于我是编程新手,如果我对任何事情一无所知,请原谅我。
编辑:我已经创建了一个类似的场景,以供大家测试。
public static void main(String[] args){
JFrame window = new JFrame("Hello");
JRadioButton trueButton = new JRadioButton("True ");
JRadioButton falseButton = new JRadioButton("False ");
window.setSize(400, 325);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(new FlowLayout());
window.add(trueButton);
window.add(falseButton);
trueButton.setVisible(true);
falseButton.setVisible(true);
window.setVisible(true);
for(;;){
if (trueButton.isSelected() || falseButton.isSelected()){
System.out.println("Selected");
break;
}
}
System.out.println("Done");
}
如果我们设法打破循环,应该打印“完成”。
为什么不使用while循环? 'while(!trueButton.isSelected()&&!falseButton.isSelected()){} System.out.print(“Selected”);'另外,如果你使用Swing,这基本上会破坏你的GUI。 – Compass
你确定没有其他区别吗?因为这没有意义 –
这种情况应该在按钮上使用监听器,并按照按键操作。 – jr593