Skip to main content

Simple Web Browser in Java


In this tutorial we will see how to create a simple web browser. It contains an address bar where a user can type the address and a go button which when clicked loads the web page. For displaying the web pages we require JEditor Pane and HyperlinkListener is required to respond when the user clicks on a link in the document. Following are the steps for creating the web browser.

Step 1: Defining the constructor of the class

The main class extends the JPanel. First we will set it's background color and layout as a Border Layout ans set border for it as follows.

  1. setBackground(Color.BLACK);
  2. setLayout(new BorderLayout(1,1));
  3. setBorder(BorderFactory.createLineBorder(Color.BLACK,1));

Scroll Pane is added to the edit pane and hyperlink listener is registered with this class. Edit Pane is placed in the center of the panel.

  1.  
  2. editPane = new JEditorPane();
  3. editPane.setEditable(false);
  4. editPane.addHyperlinkListener(new LinkListener());
  5. add(new JScrollPane(editPane),BorderLayout.CENTER);

Next a toolbar is created and added to the north of the panel. A label, text field for location input and go button are added to this tool bar. Action Listener is added to the go button and location input field to load the url.

  1. JToolBar toolbar = new JToolBar();
  2. toolbar.setFloatable(false);
  3. add(toolbar,BorderLayout.NORTH);
  4. ActionListener goListener = new GoListener();
  5. locationInput = new JTextField("www.sourcecodester.com", 40); //home page
  6. locationInput.addActionListener(goListener);
  7. JButton goButton = new JButton(" Go ");
  8. goButton.addActionListener(goListener);
  9. toolbar.add( new JLabel(" Location: "));
  10. toolbar.add(locationInput);
  11. toolbar.addSeparator(new Dimension(5,0)); //after 5 pixel of space the go button is added
  12. toolbar.add(goButton);


Step 2: Implementing Hyperlink Listener

Hyperlink Listener contains a single function as hyperlinkUpdate() which is defined as follows. If hyperlink is clicked then URL of that hyperlink is loaded in the edit pane by calling loadURL() method.

  1. public void hyperlinkUpdate(HyperlinkEvent evt) {
  2. if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
  3. loadURL(evt.getURL());
  4. }

Step 3: Defining loadURL() method

It loads the document at the specified URL into the edit pane. try catch block is used to handle errors if occurred any while changing the contents of the edit pane. JEditPane's setPage() method is used to set the edit pane's content.

  1. private void loadURL(URL url) {
  2. try {
  3. editPane.setPage(url);
  4. }
  5. catch (Exception e) {
  6. editPane.setContentType("text/plain");
  7. editPane.setText( "Sorry, the requested document was not found\n"
  8. +"or cannot be displayed.\n\nError:" + e);
  9. }
  10. }


Step 4: ActionListener for Go button and Location input field

Here the location input field's data is stored in a string variable and checked whether its format is wrong or right. If the format is correct then URL is created and loadURL() method is called to load that URL else suitable message is displayed.

  1. public void actionPerformed(ActionEvent evt) {
  2. URL url;
  3. try {
  4. String location = locationInput.getText().trim(); //gets the text and removes the spaces
  5. if (location.length() == 0) //empty URL
  6. throw new Exception();
  7. if (! location.contains("://")) // "://" if it not present in the string
  8. location = "http://" + location;
  9. url = new URL(location); //create url from string
  10. }
  11. catch (Exception e) {
  12. JOptionPane.showMessageDialog(SimpleWebBrowser.this,
  13. "The Location input box does not\nccontain a legal URL.");
  14. return;
  15. }
  16. loadURL(url);
  17. locationInput.selectAll();
  18. locationInput.requestFocus();
  19. }


Step 5: main() for defining different properties of frame

A frame is created and object of the main class(SimpleWebBrowser) is set as content of the frame as it is a panel. Location of the frame is centered using Toolkit as follows.

  1. public static void main(String[] args) {
  2. JFrame window = new JFrame("SimpleWebBrowser"); // Title of web browser
  3. SimpleWebBrowser content = new SimpleWebBrowser();
  4. window.setContentPane(content);
  5. window.setSize(600,500);
  6. Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
  7. window.setLocation( (screenSize.width - window.getWidth())/2, (screenSize.height - window.getHeight())/2 );//center the frame
  8. window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
  9. window.setVisible(true);
  10. }

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Submitted bykelilon Thu, 06/12/2014 - 22:06

i like your web site very much. It is helpful for me.

Submitted byalji abu (not verified)on Tue, 12/09/2014 - 14:28

waaaw gud great work thanks

Submitted bytzelepis (not verified)on Fri, 01/09/2015 - 02:07

Congrats!!! very nice job,and very educational

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.