JInternalFrame不会出现

时间:2012-09-17 19:07:59

标签: java swing concurrency event-dispatch-thread jinternalframe

我有一个名为GameUpdater的java类,它扩展了JInternalFrame。 当我把这个类作为一个程序单独运行时,它用于扩展JFrame,但我把它改为JInternalFrame,成为一个更大的应用程序的一部分 - 现在可以从菜单按钮访问。

按下此菜单按钮时调用的功能如下:

private void update(){

    GameUpdater gu = new GameUpdater();
    desktop.add(gu); //add to JDesktopPane
    gu.setSize(400, 300);
    gu.setVisible(true);

    gu.readMatches();//this function takes ages

    gu.setMatch("Updating database...");//this is some output to the user, displays info in the internal frame
    //try and insert into database
    for(Match m : gu.getMatches()){
        db.insertMatch(m);
    }
    gu.setMatch("DONE"); //now it shows the frame, way too late
}

方法gu.readMatches()需要很长时间才能执行,因此它会定期更新JInternalFrame中的内容以显示其进度。但是,在此更新功能完成之前,框架不会显示!

就像setVisible(true)一直等到函数结束......

当它是JFrame时,它工作得非常好。是否有任何奇怪的JInternalFrame属性会导致这种情况?

干杯

2 个答案:

答案 0 :(得分:2)

听起来你在Event Dispatching Thread(EDT)内执行一个耗时的过程,这将阻止事件队列处理(除其他事项外)重绘请求。

这将使您的程序看起来好像已经“挂起”。

您需要将此任务卸载到后台线程。

仔细阅读Concurrency in Swing,尤其是Worker Threads and SwingWorker

部分

答案 1 :(得分:2)

问题在于您阻止了EDT这可以通过简单地创建一个新的Thread / Runnable thar调用gu.readMatches();方法来解决这个问题:

SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
gu.readMatches(); //gu will have to be declared `final`

gu.setMatch("Updating database...");//this is some output to the user, displays info in the internal frame
//try and insert into database
for(Match m : gu.getMatches()){
    db.insertMatch(m);
}
}
});

当然,您可能希望实现JProgressBar,以便用户可以跟踪阅读的距离。