日期:2014-05-20  浏览次数:20589 次

一个莫名其妙的问题,望高手帮忙解决
先贴代码:

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TestVisible extends JFrame {

private JButton btn;

/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TestVisible thisClass = new TestVisible();
thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thisClass.setVisible(true);
}
});
}

/**
 * This is the default constructor
 */
public TestVisible() {
super();
this.setSize(300,200);
JPanel panel = new JPanel();
panel.setLayout(null);
btn = new JButton("haha");
btn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
btn.setVisible(false);
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btn.setBounds(30, 30, 80, 30);
panel.add(btn);
this.setContentPane(panel);
}

}


我希望一点击按钮 按钮就立即不可见 但是貌似只要下面有try语句 “btn.setVisible(false);”这句话就不能立即执行 

------解决方案--------------------
方法一:
把 btn.setVisible(false); 这句话放到
SwingUtilities.invokeAndWait 中去

方法二:
把 btn.setVisible(false); 之后那些耗时代码放到
SwingWorker 中去处理
------解决方案--------------------
		btn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
btn.setVisible(false);
try {
SwingUtilities.invokeAndWait(new Thread() {
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
});
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});

------解决方案--------------------
换成invokeLater试试