我正在運行一個長按任務按鈕。我想顯示任務已經開始的消息。使用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