Java SwingUtilities.invokeLater
大家好,在我设计的这个应用程序的最后一个阶段有点痛苦 基本上,当用户单击按钮时,我希望光标变成“等待”版本,然后一旦后台进程(task.execute)完成,光标就会恢复正常 task.execute不在同一个类中,因此我不能直接调用“gui.setCursor”,因为它不能将gui识别为变量 不知道该怎么做,有什么建议就好了Java SwingUtilities.invokeLater,java,swing,cursor,swingutilities,invokelater,Java,Swing,Cursor,Swingutilities,Invokelater,大家好,在我设计的这个应用程序的最后一个阶段有点痛苦 基本上,当用户单击按钮时,我希望光标变成“等待”版本,然后一旦后台进程(task.execute)完成,光标就会恢复正常 task.execute不在同一个类中,因此我不能直接调用“gui.setCursor”,因为它不能将gui识别为变量 不知道该怎么做,有什么建议就好了 谢谢:D当您创建任务时,请向其传递一个具有某种“已完成”方法的界面。完成任务后,让任务调用该方法,然后让gui类实现该接口并更改该方法调用上的光标。修改任务的类,使其将g
谢谢:D当您创建任务时,请向其传递一个具有某种“已完成”方法的界面。完成任务后,让任务调用该方法,然后让gui类实现该接口并更改该方法调用上的光标。修改任务的类,使其将gui作为构造函数参数。这样,当任务完成时,它可以调用
setCursor
方法
这类事情你应该找一个SwingWorker
编辑:
以下是任务的代码:
.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent e){
try{
ta.append("Searching Initiated at: "+datetime()+"\n");
gui.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
task.execute();
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
gui.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
});
//Enable the next stage in the YD process and disable the previously executed functions
clusAn.setEnabled(true);
open.setEnabled(false);
statCl.setEnabled(false);
}catch (Exception IOE){
}
}
});
公共类MyWingWorker扩展SwingWorker{
/**
*必须设置默认光标的帧
*在后台任务结束时
*/
私有jframegui;
公共MySwingWorker(JFrame gui){
this.gui=gui;
}
// ...
@凌驾
受保护的void done(){
//在EDT中调用done方法。
//这里不需要SwingUtilities.invokeLater
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_Cursor));
}
}
也许您可以尝试将gui设置为最终版本
public class MySwingWorker extends SwingWorker<Void, Void> {
/**
* The frame which must have the default cursor set
* at the end of the background task
*/
private JFrame gui;
public MySwingWorker(JFrame gui) {
this.gui = gui;
}
// ...
@Override
protected void done() {
// the done method is called in the EDT.
// No need for SwingUtilities.invokeLater here
gui.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
哦,确实如此,任务类已经扩展了SwingWorker。我想我理解这是如何工作的,所以在公共类YouDetectTaskStatCl extensed SwingWorker{这是否需要成为公共类YouDetectTaskStatCl(JFrame GUI)extensed SwingWorker{??您不需要
invokeLater()
在actionPerformed()
中,因为它总是从GUI事件调度线程调用的。
final JComponent guiFinal = gui;
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
guiFinal .setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
});