【发布时间】:2014-10-13 05:58:53
【问题描述】:
当我启动我的应用程序时,它会打开一个 JFrame(主窗口)和一个 JFilechooser 以选择一个输入目录,然后对其进行扫描。
scan 方法本身会创建一个新的JFrame,其中包含一个JButton 和一个JProgressBar,并启动一个新的线程来扫描选定的目录。到目前为止,一切正常。
现在我在我的主窗口中更改目录路径,它再次调用扫描方法。这次它创建了另一个JFrame,其中应该包含JProgressBar 和JButton,但它显示为空(JFrame 标题仍然设置)。
更新: 最小的例子
public class MainWindow
{
private JFrame _frame;
private JTextArea _textArea;
private ProgressBar _progress;
public MainWindow() throws InterruptedException, ExecutionException
{
_frame = new JFrame("Main Window");
_textArea = new JTextArea();
_frame.add(_textArea);
_frame.setSize(200, 200);
_frame.setVisible(true);
_textArea.setText(doStuffinBackground());
_progress.dispose();
}
private String doStuffinBackground() throws InterruptedException,
ExecutionException
{
setUpProgressBar();
ScanWorker scanWorker = new ScanWorker();
scanWorker.execute();
return scanWorker.get();
}
private void setUpProgressBar()
{
// Display progress bar
_progress = new ProgressBar();
}
class ProgressBar extends JFrame
{
public ProgressBar()
{
super();
JProgressBar progressBar = new JProgressBar();
progressBar.setIndeterminate(true);
progressBar.setStringPainted(false);
add(progressBar);
setTitle("Progress Window");
setSize(200, 200);
toFront();
setVisible(true);
}
}
class ScanWorker extends SwingWorker<String, Void>
{
@Override
public String doInBackground() throws InterruptedException
{
int j = 0;
for (int i = 0; i < 10; i++)
{
Thread.sleep(1000);
j += 1;
}
return String.valueOf(j);
}
}
public static void main(String[] args) throws InvocationTargetException,
InterruptedException
{
SwingUtilities.invokeAndWait(new Runnable()
{
public void run()
{
// Start the main controller
try
{
new MainWindow();
}
catch (InterruptedException | ExecutionException e) {}
}
});
}
}
【问题讨论】:
-
1) 见The Use of Multiple JFrames, Good/Bad Practice? 2) 为了尽快获得更好的帮助,请发布MCVE(最小、完整、可验证的示例)。 3) 你的问题是什么?
-
@andrew-thompson 实际上我想使用 JDialog 因为它会更简洁,因为它会更简洁,而不是禁用 Main JFrame 并在之后重新启用它,但从我在网上发现的情况来看,它会使处理复杂化取消按钮,因为侦听器代码需要完全在 JDialog 类本身中(我的老师不太喜欢这样做,因为它违反了 MVC 模式(至少在他看来)
标签: java multithreading swing components swingworker