-2

我有一个加载新闻的课程。

package swing;
import java.awt.Color;
import java.net.URL;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import net.Logger;
import net.Util;

public class WebPanel extends JScrollPane implements Runnable {
    private JTextPane editorPane;
    private String link;

    public WebPanel(final String link) {
        this.link = link;
        editorPane = new JTextPane();
        editorPane.setContentType("text/html");
        editorPane.setBackground(Color.DARK_GRAY);
        editorPane.setEditable(false);
        editorPane.setMargin(null);
        editorPane.setBorder(null);
        setBorder(null);
        editorPane.setBackground(Color.DARK_GRAY);
        editorPane.setText("<html><body><font color=\"#808080\"><br><center>Getting data</center></font></body></html>");
    }

    @Override
    public void run() {
        try {
            editorPane.setPage(new URL(link));
        } catch (Exception e) {
            Logger.logError("setting web page failed ", e);
            editorPane.setContentType("text/html");
            editorPane.setText("<html><body><font color=\"#808080\"><br><center>Failed to get data<br>" + e.toString() + "</center></font></body></html>");
        }

        editorPane.addHyperlinkListener(new HyperlinkListener() {
            @Override
            public void hyperlinkUpdate(HyperlinkEvent he) {
                if (he.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                    try {
                        Util.openLink(he.getURL().toURI());
                    } catch (Exception e) {
                        Logger.logError("hyperlinkUpdate failed", e);
                    }
                }
            }
        }); 

        setViewportView(editorPane);
   }

   public String GetLink() {
       return editorPane.getPage().toString();
   }
   public final void setLink(final String link) {
       this.link = link;
   }}

它是可运行的,但是当我更新页面时(我有 GUI 类我这样做)Lo

public static WebPanel scrollPane = new WebPanel(Util.newslink);
...
LoginForm.scrollPane.setLink(Util.newslink);
new Thread(LoginForm.scrollPane).start();

我的程序在加载页面之前无法运行(无法按下任何按钮)。我尝试使用创建线程invokeLater(),但没有任何帮助。

4

2 回答 2

1

最可能的原因是您在 GUI 线程中等待 Web 下载。这样做会在您等待时阻止 GUI。

如果您不希望发生这种情况,请使用另一个线程进行下载并使用 invokeLater 获取结果并在完成时更新 GUI。

于 2013-03-09T20:32:45.227 回答
1

现在,您正在对负责更新 GUI 的事件调度线程 (EDT) 进行阻塞调用。这将显示该应用程序没有执行任何操作,因为在您的阻止呼叫之前它无法更新。你真的应该利用 aSwingWorker在后台线程上做“繁重”的工作。

查看教程Concurrency in Swing,了解有关如何在后台线程上执行长时间运行的任务的详细信息。

于 2013-03-09T20:33:49.997 回答