gpt4 book ai didi

java - Swing invokeLater 永远不会出现,invokeAndWait 会抛出错误。我能做些什么?

转载 作者:行者123 更新时间:2023-12-02 09:03:14 24 4
gpt4 key购买 nike

我有这个代码:

try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
try {
dialog.handleDownload();
} catch (IOException io) {
io.printStackTrace();
}
}
});
} catch(Exception io) { io.printStackTrace(); }

handleDownload中,我正在读取输入流,计算进度条的值,并将其设置为该值。因此,当我单击按钮时,会打开一个新的 JFrame 并执行我上面编写的所有操作。

如果我有 dialog.handleDownload 本身(在没有 SwingUtilities 方法中),它会卡住,直到操作完成。如果我将它添加到 invokeLater 中,它会很快关闭(我看不到任何东西,并且操作尚未完成)。如果我将其添加到 invokeAndWait 中,我会收到 invokeAndWait 无法从事件调度程序线程调用的错误。我该怎么办?

最佳答案

看起来你可以利用SwingWorker 。这允许您将昂贵的操作推迟到后台线程(保持 GUI 响应),并且当操作完成时,对 GUI 执行一些操作。

编辑:示例

这里有一个更复杂的示例,展示了如何使用 SwingWorker 的基础知识以及如何发布/处理中间结果。

public static void main(String[] args) {
final int SIZE = 1024*1024; //1 MiB

//simulates downloading a 1 MiB file
final InputStream in = new InputStream() {
int read = 0;
public int read() throws IOException {
if ( read == SIZE ) {
return -1;
} else {
if ( read % 200 == 0 ) {
try { Thread.sleep(1); } catch ( InterruptedException e ) {}
}
read++;
return 5;
}
}
};

final JProgressBar progress = new JProgressBar(0, SIZE);

final JButton button = new JButton("Start");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
button.setText("Working...");
SwingWorker<byte[], Integer> worker = new SwingWorker<byte[], Integer>() {
@Override
protected byte[] doInBackground() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
for ( int read = -1; (read = in.read(buff)) != -1; ) {
baos.write(buff, 0, read);
publish(read);
}
return baos.toByteArray();
}

@Override
protected void process(List<Integer> chunks) {
int total = 0;
for ( Integer amtRead : chunks ) {
total += amtRead;
}
progress.setValue(progress.getValue() + total);
}

@Override
protected void done() {
try {
byte[] data = get();
button.setText("Read " + data.length + " bytes");
} catch (Exception e) {
e.printStackTrace();
}
}
};
worker.execute();
}
});

JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.add(button, BorderLayout.NORTH);
frame.add(progress, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack(); frame.setVisible(true);
}

编辑:更改示例以驱动进度条,就像正在进行下载一样。

关于java - Swing invokeLater 永远不会出现,invokeAndWait 会抛出错误。我能做些什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3039657/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com