我正在运行一个长按任务按钮。我想显示任务已经开始的消息。使用swingworker,JOptionPane创建消息框,但其内容保留为空,直到任务完成。我想我的EDT正在被阻塞,因此除非任务完成,否则GUI不会更新。有什么办法来证明这个(swingutils.invokelater,因为我需要在任务开始时显示无法使用) 示例代码: -从SwingWorker显示消息(Joptionpane)thread-doInBackground()
public class myClass {
private JFrame frame;
private display1 dis;
class display1 extends SwingWorker<Void,Void>
{
public Void doInBackground() throws InterruptedException
{
JOptionPane.showMessageDialog(null,
"Task Started");
return null;
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
myClass window = new myClass();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public myClass() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dis=new display1();
dis.execute();
System.out.println("starting");
for(int i=0;i<10000;i++)
System.out.println("this is " +i);// Long task
System.out.println("Finished");
}
});
btnNewButton.setBounds(166, 228, 89, 23);
frame.getContentPane().add(btnNewButton);
}
}
什么是'display1'?您在EDT的上下文中运行了一项长期任务,这解释了您的UI为空的原因 – MadProgrammer
display1是实现SwingWorker的类的名称。我知道它不工作的原因。我所要求的所有方法都是显示任务已启动并同时执行任务的对话方式(该任务包含操作某些GUI组件) – sam
考虑提供[可运行示例](https://stackoverflow.com/help/mcve )这表明你的问题。这不是代码转储,而是您正在做的事情的一个例子,它突出了您遇到的问题。这会减少混淆和更好的反应 – MadProgrammer