import javax.swing.JEditorPane; import javax.swing.JScrollPane; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.HTMLDocument; import java.net.URL; import javax.swing.JOptionPane; import java.io.IOException; import javax.swing.event.HyperlinkListener; import javax.swing.event.HyperlinkEvent; import javax.swing.text.html.HTMLFrameHyperlinkEvent; /** * This class is a simple html viewer. It is able to render html files and display them. * * @author Brad Rippe (brippe@fullcoll.edu) * @version 1.0 */ public class HTMLViewer extends JScrollPane { /** * Constructs a HTMLViewer * To construct this in a JFrame simply call "HTMLViewer htmlViewer = new HTMLViewer(this);" * @param the main JFrame application component */ public HTMLViewer(URLSetable browser) { super(new JEditorPane()); this.browser = browser; editor = (JEditorPane) getViewport().getView(); editor.setContentType("text/html"); editor.setEditable(false); editor.setEditorKit(new javax.swing.text.html.HTMLEditorKit()); editor.addHyperlinkListener(new HyperlinkListener() { public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { JEditorPane pane = (JEditorPane) e.getSource(); setWebPage(e.getURL()); } } }); setWebPage("http://cis226.fullcoll.edu/index.cfm"); } /** * This method set the web page to be displayed. * @param url - this uniform resource locator of the new page, this must start with "http://" */ public void setWebPage(String url) { try { editor.setPage(new URL(url)); currentURL = url; browser.setURLTextField(currentURL); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Error retrieving specified URL", "Bad URL", JOptionPane.ERROR_MESSAGE); } } /** * This method set the web page to be displayed, this method is for internal use only. * @param url - this uniform resource locator of the new page, this must start with "http://" */ public void setWebPage(URL url) { try { editor.setPage(url); currentURL = "http://" + url.getHost() + url.getPath(); browser.setURLTextField(currentURL); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Error retrieving specified URL", "Bad URL", JOptionPane.ERROR_MESSAGE); } } /** * Returns the current url. */ public String getCurrentURL() { return currentURL; } private JEditorPane editor; private String currentURL = null; private String backURL = null; private String forwardURL = null; private HTMLDocument htmlDoc; private URLSetable browser; }