我有使用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的操作完成后触发.
请帮我.我提供了示例代码,当您运行它时,在单击button1,然后立即单击button2之后,将执行两个按钮的操作.
我想要按下任何按钮时,都会在按钮的单击操作中完成繁重的工作,同时我将禁用所有按钮,因此无法执行其他任何操作.当第一个动作完成时,我将启用所有按钮.
请帮我.
提前致谢.