我真的想不出来为什么这个程序在Java 7中不能正常运行。使用Java 6时,我已经毫无问题地运行了它,但是一旦在Java 7上运行,它就不能工作。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class HelloWorld implements ActionListener {
JButton button;
boolean state;
public HelloWorld(){
init();
state = false;
System.out.println("state - "+state);
while (true){
if (state == true){
System.out.println("Success");
}
}
}
private void init(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button = new JButton("Button");
button.addActionListener(this);
frame.add(button);
frame.pack();
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
JButton source = (JButton)e.getSource();
if (source == button){
state = !state;
System.out.println("state - "+state);
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new HelloWorld();
}
}
使用Java 6,如果我按下按钮,它将打印出短语“Success”,直到我再次按下按钮。使用Java 7注册按钮被按下并且状态值已更改为true,但短语“Success”从未被打印。发生了什么?