Java examples for Swing:JEditorPane
Create An HTML Browser Using the JEditorPane Component
import java.awt.BorderLayout; import java.awt.Container; import java.beans.PropertyChangeEvent; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.event.HyperlinkEvent; public class Main extends JFrame { JLabel urlLabel = new JLabel("URL:"); JTextField urlTextField = new JTextField(40); JButton urlGoButton = new JButton("Go"); JEditorPane editorPane = new JEditorPane(); JLabel statusLabel = new JLabel("Ready"); public Main(String title) { super(title); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container contentPane = this.getContentPane(); Box urlBox = this.getURLBox(); Box editorPaneBox = this.getEditPaneBox(); contentPane.add(urlBox, BorderLayout.NORTH); contentPane.add(editorPaneBox, BorderLayout.CENTER); contentPane.add(statusLabel, BorderLayout.SOUTH); }//from w w w . ja v a2s .co m private Box getURLBox() { Box urlBox = Box.createHorizontalBox(); urlBox.add(urlLabel); urlBox.add(urlTextField); urlBox.add(urlGoButton); urlTextField.addActionListener(e -> { String urlString = urlTextField.getText(); go(urlString); }); urlGoButton.addActionListener(e -> go()); return urlBox; } private Box getEditPaneBox() { editorPane.setEditable(false); Box editorBox = Box.createHorizontalBox(); editorBox.add(new JScrollPane(editorPane)); editorPane.addHyperlinkListener((HyperlinkEvent event) -> { if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { go(event.getURL()); } else if (event.getEventType() == HyperlinkEvent.EventType.ENTERED) { statusLabel.setText("Please click this link to visit the page"); } else if (event.getEventType() == HyperlinkEvent.EventType.EXITED) { statusLabel.setText("Ready"); } }); editorPane.addPropertyChangeListener((PropertyChangeEvent e) -> { String propertyName = e.getPropertyName(); if (propertyName.equalsIgnoreCase("page")) { URL url = editorPane.getPage(); urlTextField.setText(url.toExternalForm()); } }); return editorBox; } public void go() { try { URL url = new URL(urlTextField.getText()); this.go(url); } catch (MalformedURLException e) { setStatus(e.getMessage()); } } public void go(URL url) { try { editorPane.setPage(url); urlTextField.setText(url.toExternalForm()); setStatus("Ready"); } catch (IOException e) { setStatus(e.getMessage()); } } public void go(String urlString) { try { URL url = new URL(urlString); go(url); } catch (IOException e) { setStatus(e.getMessage()); } } private void setStatus(String status) { statusLabel.setText(status); } public static void main(String[] args) { Main browser = new Main("HTML Browser"); browser.setSize(700, 500); browser.setVisible(true); browser.go("https://www.java2s.com"); } }