How should HTML for Java components reference resources?

后端 未结 1 1751
耶瑟儿~
耶瑟儿~ 2020-12-19 09:16

Resources for HTML (style sheets, images etc.) might not be loaded correctly when:

  • A Swing app. is distributed, or when it is put into a Jar file.
  • T
1条回答
  •  再見小時候
    2020-12-19 10:04

    HTML from a Jar file that links resources (e.g. CSS or images) by relative references will work just fine.

    E.G.

    This example loads HTML (that has a relative reference to an image) from a Jar.

    import javax.swing.*;
    import java.net.URL;
    
    class ShowHtml {
    
        public static void main(String[] args) {
            final String address =
                "jar:http://pscode.org/jh/hs/object.jar!/popup_contents.html";
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    try {
                        URL url = new URL(address);
                        JEditorPane jep = new JEditorPane(url);
                        JFrame f = new JFrame("Show HTML in Jar");
                        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        f.add(new JScrollPane(jep));
                        f.pack();
                        f.setSize(400,300);
                        f.setLocationByPlatform(true);
                        f.setVisible(true);
                    } catch(Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    

    Screenshot

    JEditorPane displaying Jar'd HTML

    HTML

    The HTML that is being loaded.

    
    
    
    
    
    Editing Project Attributes
    
    
    
     Popup Window
    

    Popup windows appear near the location from which they are activated. They are not contained in frames and thus cannot be resized or moved by the user. Popups are dismissed by clicking anywhere in the help viewer.

    Popup windows can be activated by clicking on a text object, graphic object, or JComponent button. All three examples are included in this demo.

    More...

    E.G. 2

    For dynamically created HTML, the JRE will probably use the class file's location as the presumed location of the HTML. But to remove all doubt, we can specify the base element in the head.

    import javax.swing.*;
    
    class HtmlUsingBase {
    
        public static void main(String[] args) {
            final String htmlContent =
                "" +
                "" +
                "" +
                "" +
                "" +
                "

    Image path from BASE

    " + "" + "" + ""; SwingUtilities.invokeLater(new Runnable() { public void run() { JLabel label = new JLabel(htmlContent); JOptionPane.showMessageDialog(null, label); } }); } }

    Screenshot

    enter image description here

    0 讨论(0)
提交回复
热议问题