import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import javax.swing.JButton; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingUtilities; public class DisplayHTML { private JEditorPane editorPane; private JTextField field; private JButton button; private JPanel buttPanel; private String str; private URL url; public DisplayHTML() { init(); } private void init() { JFrame frame = new JFrame("HTML-Seite darstellen"); field = new JTextField("file://"); frame.add(field, BorderLayout.NORTH); button = new JButton("laden"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setURL(); loadPage(); } }); buttPanel = new JPanel(new FlowLayout()); buttPanel.add(button); frame.add(buttPanel, BorderLayout.SOUTH); editorPane = new JEditorPane(); editorPane.setEditable(false); frame.add(editorPane, BorderLayout.CENTER); setURL(); loadPage(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); } /** * loads the asked page to the JEditorPane and displays its source in the * console */ public void loadPage() { // stop the program if there is no URL-Object if (url == null) { return; } try { // load the page editorPane.setPage(url); // get the source InputStream in = url.openStream(); BufferedReader buff = new BufferedReader(new InputStreamReader(in)); String s; // display source while ((s = buff.readLine()) != null) { System.out.println(s); } } catch (IOException e) { e.printStackTrace(); } } public void setURL() { // check the URL-String if (!verifyStr()) return; if (str.startsWith("file://") || str.startsWith("http://") || str.startsWith("https://")) { // create an URL-Object try { url = new URL(str); } catch (MalformedURLException e) { url = null; System.err.println("Falsches URL-Format!"); e.printStackTrace(); } } } private boolean verifyStr() { str = field.getText(); if (str.equals("") || str.length() < 8) { return false; } if (str.startsWith("http://") || str.startsWith("https://")) { return true; } if (!str.startsWith("http://") && !str.startsWith("file://")) { str = "file://" + str; } if (str.startsWith("file://")) { // check if file is valid and can be read String s = str.substring(7); File file = new File(s); if (file.isFile() && file.canRead()) { return true; } } return false; } public static void main(String[] args) { SwingUtilities.invokeLater(() -> new DisplayHTML()); } }