Share this page 

Display HTML in a JScrollPaneTag(s): Swing


The JTextPane can display simple HTML page.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;

public class TestShowPage {
 public static void main(String args[]) {  
  JTextPane tp = new JTextPane();
  JScrollPane js = new JScrollPane();
  js.getViewport().add(tp);
  JFrame jf = new JFrame();
  jf.getContentPane().add(js);
  jf.pack();
  jf.setSize(400,500);
  jf.setVisible(true); 
  
  try {
    URL url = new URL("http://www.tactika.com/realhome/contents.html");
    tp.setPage(url);
    } 
  catch (Exception e) {
    e.printStackTrace();
    }
  }
 }

If the HTML is a located into a jar,

...
URL url = getClass().getResource("contents.html");
tp.setPage(url);
...
to set an anchor, you get the URL then add the "#anchor".
...
URL url = getClass().getResource("contents.html");
tp.setPage(new URL(url.toExternalForm() + "#section42")); 
...