【问题标题】:Display an external HTML file in a JPanel在 JPanel 中显示外部 HTML 文件
【发布时间】:2013-07-21 14:37:50
【问题描述】:

我正在编写一个应用程序启动器,我目前有一个显示应用程序更改的 HTML 文件,这就像一个魅力,每次发布新更新时,我都会在 HTML 文件中列出更改它会在用户的 .exe/.jar 文件中自动更新。

但是我当前使用的方法需要用户下载 .exe/.jar 文件才能显示更新,所以我怎么会从我的网络服务器获取 HTML 文件并相应地显示它。

这是我当前的代码;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;

public class Launcher extends JFrame {

private static final long serialVersionUID = -6224390548062243879L;

public static void createFrame() {

    JEditorPane editorPane = new JEditorPane();
    editorPane.setEditable(false);

    java.net.URL helpURL = Launcher.class.getResource("/changelog.html");

    if (helpURL != null) {
        try {
            editorPane.setPage(helpURL);
        } catch (IOException e) {
            System.err.println("Attempted to read a bad URL: " + helpURL);
        }
    } else {
        System.err.println("Couldn't find file: changelog.html");
    }

    JScrollPane editorScrollPane = new JScrollPane(editorPane);

    editorScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    editorScrollPane.setPreferredSize(new Dimension(350, 300));
    editorScrollPane.setMinimumSize(new Dimension(10, 10));

    JLabel emptyLabel = new JLabel("");

    emptyLabel.setPreferredSize(new Dimension(300, 300));

    JButton launch = new JButton("Launch!");

    launch.setPreferredSize(new Dimension(350, 50));

    JFrame f = new JFrame();

    f.setTitle("Stonelore Launcher");
    f.setSize(350, 400);
    f.setLocationRelativeTo(null);
    f.getContentPane().add(emptyLabel, BorderLayout.CENTER);
    f.getContentPane().add(editorScrollPane, BorderLayout.NORTH);
    f.getContentPane().add(launch, BorderLayout.SOUTH);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setResizable(false);
    f.setVisible(true);
}

public static void main(String[] args) {
    createFrame();
}
}

【问题讨论】:

    标签: java html swing webserver


    【解决方案1】:

    您只需更改以下行:

    java.net.URL helpURL = Launcher.class.getResource("/changelog.html");
    

    到以下:

    java.net.URL helpURL = new URL("http://www.server.com/changelog.html");
    

    当然,您必须在 URL 构造器中替换实际的 URL。

    【讨论】:

    • 虽然这是解决方案,但我要补充一点,您应该考虑在新线程中运行try { editorPane.setPage(helpURL); } catch (IOException e) { System.err.println("Attempted to read a bad URL: " + helpURL); }。 UI 线程上的网络操作是个坏主意。
    • 我事先在try catch中添加了!
    猜你喜欢
    • 2015-08-24
    • 2014-09-09
    • 2018-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-01
    • 1970-01-01
    相关资源
    最近更新 更多