在swing中如果需要点击按钮执行一个死循环或者长期任务时会发现程序出现假死现象,如下图:
按钮并不能弹起,程序也不能关掉,整个界面无响应。
解决办法:把循环代码写到一个新线程里
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Thread() {
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
int i=0;
while (true) {
System.out.println(i++);
}
}
}.start();
}
});
这样程序界面就不会失去响应了
完整代码如下
package test;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class TestXunhan{
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestXunhan window = new TestXunhan();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TestXunhan() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 399, 165);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Thread() {
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
int i=0;
while (true) {
System.out.println(i++);
}
}
}.start();
}
});
frame.getContentPane().add(btnNewButton, BorderLayout.NORTH);
}
}