Useful Java Code Snippets 5 - A Simple Web Browser in Java



Looking for useful code examples to build your Java applications? 



A web browser (commonly referred to as a browser) is a software application for retrieving, presenting, and traversing information resources on the World Wide Web. 
In this example we built a simple web browser by using the Java programming language.


/**
* Author : Berk Soysal
* ReadFile.java
*/

package Browser;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;

public class ReadFile extends JFrame{
  
  
  private JTextField addressBar;
  private JEditorPane display = new JEditorPane();
  
  //The constructor
  public ReadFile(){
    //Title of the browser
    super("Berk Browser");
    
    addressBar = new JTextField("https://");
    addressBar.addActionListener(
                                 new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        
        Action(e.getActionCommand());
        
      }
    }
    );
    
    //Add addressBar object to the JFrame
    add(addressBar,BorderLayout.NORTH);
    
    
    display.setEditable(false);
    display.addHyperlinkListener(
                                 new HyperlinkListener() {
      @Override
      public void hyperlinkUpdate(HyperlinkEvent h) {
        if(h.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
          Action(h.getURL().toString());
        
      }
    }
                                 
    );
    //Add display object to the JFrame
    add(new JScrollPane(display),BorderLayout.CENTER);
    setSize(1024,768);
    setVisible(true);
    
    
  }
  
  // Load to display on the screen
  private void Action(String userText){
    try {
      // Displays the WebPage using setPage method !**
      display.setPage(userText);
      addressBar.setText(userText); 
    } catch (Exception e) {
      System.out.println("Error!");
    }
  }
}





/**
* Author : Berk Soysal
* Main.java
*/

package Browser;

import javax.swing.JFrame;

public class Main{ 
  public static void main(String[] args){
    ReadFile rf = new ReadFile();
    rf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
  
}



If you do everything right the result should be like the figure below;



Please comment below if you have any questions. Thanks. 



Continue Reading Useful Java Code Snippets 6 - A Screen Capture Program in Java

Author:

Software Developer, Codemio Admin

Disqus Comments Loading..