【发布时间】:2017-04-18 10:24:56
【问题描述】:
点击一个按钮,我正在运行一个很长的任务。我想显示任务已开始的消息。使用 swingworker,JOptionPane 创建消息框,但其内容在任务完成之前留空。我猜我的 EDT 被阻塞了,因此除非任务完成,否则 GUI 不会更新。有什么方法可以显示这个(swingutils.invokelater 不能使用,因为我需要在任务开始时显示) 示例代码:-
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 是空白的 -
display1 是实现 SwingWorker 的类的名称。我知道它不起作用的原因。我所要求的只是一种显示任务已启动并同时执行任务的对话的方法(该任务包含操作某些 GUI 组件)
-
考虑提供一个runnable example 来证明您的问题。这不是代码转储,而是您正在做的事情的一个例子,它突出了您遇到的问题。这将导致更少的混乱和更好的响应
-
上面的程序非常清晰易懂。我发布了完整的代码以获得更好的可见性/理解,并且代码本身非常简单和简短。如果您没有任何积极的贡献,请停止不必要的评论
-
对不起,我试图了解您的问题以帮助您找到解决方案,但
for(int i=0;i<10000;i++)将阻止可能阻止 UI 更新的 EDT,但我想这无关紧要不帮忙,那我很抱歉
标签: java multithreading swing joptionpane swingworker