【发布时间】:2012-09-04 01:40:27
【问题描述】:
我有使用 Swing 的示例代码。
package playerlist;
import java.awt.FlowLayout;
import javax.swing.*;
import java.awt.event.*;
public class Sample extends JFrame{
private JButton button1;
private JButton button2;
public Sample(){
super();
setTitle("Sample JFrame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button1 = new JButton("Button 1");
button2 = new JButton("Button 2");
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
button1ActionPerformed(e);
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
button2ActionPerformed(e);
}
});
setLayout(new FlowLayout());
add(button1);
add(button2);
pack();
}
private void button1ActionPerformed(ActionEvent ae){
button1.setEnabled(false);
button2.setEnabled(false);
try{
Thread.sleep(5000);
}catch(Exception e){
}
System.out.println("*** Button 1 Clicked ***");
button1.setEnabled(true);
button2.setEnabled(true);
}
private void button2ActionPerformed(ActionEvent ae){
button1.setEnabled(false);
button2.setEnabled(false);
try{
Thread.sleep(5000);
}catch(Exception e){
}
// I have disabled this button from button 1's action, but still when I click this button within
// 5 seconds, actions of this button is performed
System.out.println("*** Button 2 Clicked ***");
button1.setEnabled(true);
button2.setEnabled(true);
}
public static void main(String [] args){
new Sample().setVisible(true);
}
}
我想要喜欢 - 当我单击 button1 时(当 button1 的动作开始时), button1 和 button2 应该被禁用(如果我单击禁用的按钮,则不应执行任何操作)。我使用 setEnabled(false) 禁用了这两个按钮。当 button1 的动作完成时,两个按钮都应该被启用。 但是在我的代码中,这不起作用,即使在禁用按钮之后,也会对禁用的按钮执行操作。 在 button1 的操作中,我禁用了两个按钮并使用 sleep 方法暂停执行(用于模拟繁重的工作)5 秒,但在 5 秒内如果我单击任何按钮,它们的操作将在 button1 的操作完成后触发。 请帮我。我提供了示例代码,当您运行它时,在单击按钮 1 后,立即单击按钮 2,两个按钮的操作都会执行。 我希望当我按下任何按钮时,按钮的点击动作都会做繁重的工作,同时我会禁用所有按钮,所以不能执行其他动作。当第一个动作完成时,我将启用所有按钮。 请帮我。 提前致谢。
【问题讨论】:
标签: java swing concurrency jbutton event-dispatch-thread