2016-07-26 137 views
-2

我试着运行下面的代码,但是当单选按钮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"); 
} 

如果我们设法打破循环,应该打印“完成”。

+3

为什么不使用while循环? 'while(!trueButton.isSelected()&&!falseButton.isSelected()){} System.out.print(“Selected”);'另外,如果你使用Swing,这基本上会破坏你的GUI。 – Compass

+2

你确定没有其他区别吗?因为这没有意义 –

+0

这种情况应该在按钮上使用监听器,并按照按键操作。 – jr593

回答

1

试试这个:

for(;;){    
      if (trueButton.isSelected() || falseButton.isSelected()){ 
      System.out.print("Selected"); 
      return; 
     } 
    } 

或本:

outerloop: 
    for(;;){    
      if (trueButton.isSelected() || falseButton.isSelected()){ 
      System.out.print("Selected"); 
      break outerloop; 
     } 
    } 

否则看起来一切都设置正确的... 希望这有助于

+0

我在尝试代码时遇到了同样的问题。这是行不通的。但是,如果我在循环之前添加System.out.println(“”)语句,我设法摆脱了循环。谢谢你的帮助。 – togglebreak

+0

让我试着复制你的代码,看看 –

+0

好不好。非常感谢你的帮助。 – togglebreak

3

当编写一个GUI,你应该避免不惜任何代价阻止循环,因为它会导致您的应用程序无响应。

您应该添加一个ActionListener来“点击”按钮被点击。否则,您只需使用isSelected方法检查单击哪个按钮而不需要循环;例如,在提交表单或执行一些计算时。

如果您绝对需要不断阅读按钮的状态,请使用Thread

+0

谢谢。我会尝试使用ActionListener。你知道我的代码不工作的原因吗? – togglebreak

+0

很可能是因为您有一个看起来无限循环,它与GUI线程有竞争条件。添加打印语句将代码暂停足够长的时间以使条件通过 –

+0

该解释有很大帮助。谢谢。 – togglebreak