我正在尝试在按下按钮时启用/禁用标签,我想在事件期间而不是之后执行此操作。如下所示,我尝试启用/禁用两个标签:lblKeyboard和lblGamepad。
他们最终在“RemoteControl.run();”之后运行被执行但我希望它发生在那之前。我能以任何方式做到这一点吗?
谢谢!
JButton btnGamepad = new JButton("Gamepad");
btnGamepad.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(cont_state == 0){
if(RemoteControl.findGamePad() == true){
cont_state = 1;
game_status = "on";
}
else{
game_status = "off";
key_status = "on";
JOptionPane.showMessageDialog(null, "Controller not found!");
cont_state = 0;
}
}
if(cont_state == 1){
System.out.println("CONNECTED GAMEPAD!");
lblKeyboard.disable();
lblGamepad.enable();
frame.repaint();
RemoteControl.run();
cont_state = 0;
}
}
});
答案 0 :(得分:1)
Code in an event listener executes on the Event Dispatch Thread (EDT) and the GUI can't repaint itself until all the code has finished executing. Read the section from the Swing tutorial on Concurrency for more information on the EDT.
Try wrapping your RemoteControl.run() code in a SwingUtilities.invokeLater(...).
This will place the code at the end of the EDT, which might give Swing a changes to repaint the state of the two labels.
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
RemoteControl.run()
}
});
This assumes your code updates the GUI. If not, then just use a separate Thread.
答案 1 :(得分:1)
ActionEvents
are run on the EDT which is also responsible for painting. Once you change the labels state, Swing issues a request for repaiting the Label
. The thing is that this request is posted on a queue and will be executed once the EDT is free and, as you can see, the EDT is busy running your code so no repainting for you! Depending on the nature of your code, you should consider using a SwingWorker or simply moving RemoteControl.run()
to another Thread as in
new Thread(new Runnable() {
@override
public void run() {
RemoteControl.run();
}
}).start();