
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Display Webpage in JEditorPane Using Java
In this article, we will learn how to display a webpage in JEditorPane using Java. The program will load a specified webpage, and display it within a GUI window. If the connection to the webpage fails, a message will appear indicating the connection issue. This setup can be useful for embedding simple web content within Java applications.
Steps to display a webpage in JEditorPane
Following are the steps to display a webpage in JEditorPane ?
- We will import the necessary classes from the java.io package and javax.swing package.
- Create a JEditorPane object to serve as the component that will display the webpage.
- Use the setPage() method of JEditorPane to load the specified webpage URL.
- Add exception handling to catch any IOException in case the webpage fails to load, displaying an error message as HTML in that case.
- Add the JEditorPane to a JScrollPane to enable scrolling if the webpage content exceeds the view area.
- Create a JFrame to serve as the main application window, and add the JScrollPane containing the JEditorPane.
- Set the frame size and make it visible to display the webpage.
Java program to display a webpage in JEditorPane
The following is an example of displaying a webpage in JEditorPane ?
import java.io.IOException; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JScrollPane; public class SwingDemo { public static void main(String[] args) { JEditorPane editorPane = new JEditorPane(); try { editorPane.setPage("https://www.tutorialspoint.com"); } catch (IOException e) { editorPane.setContentType("text/html"); editorPane.setText("<html>Connection issues!</html>"); } JScrollPane pane = new JScrollPane(editorPane); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(pane); frame.setSize(500, 300); frame.setVisible(true); } }
Output
Code explanation
The program begins by creating a JEditorPane object to hold the webpage. It attempts to set the page using editorPane.setPage() with the URL. If there's an IOException (like a connection issue), the catch block handles it by setting the content type to HTML and displaying a simple "Connection issues!" message.
The JEditorPane is then wrapped in a JScrollPane (pane), which provides a scrollable view for the webpage content. A JFrame (frame) is created to host the JScrollPane. The frame's default close operation is set to exit the application when the window is closed, and its size is set to 500x300 pixels. Finally, the frame is made visible, displaying the webpage or the error message if loading fails.