- Saved searches
- Use saved searches to filter your results more quickly
- StaceyWhitmore/simple-web-browser-in-java
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- How To Create A Web Browser In Java using Netbeans
- A comprehensive step by step tutorial on how to create a web simple web browser in Java using Apache Netbeans IDE
- This tutorial is divided into several steps:
- Step #1: Create a New Java Application
- Step #2: Add Required Swing Components
- Step #3: Make a Simple Web Browser Working
- Step #4: Run and Test the Java Web Browser
- Java Tip 66: Control browsers from your Java application
- Follow-up tips
- The BrowserControl code
- Conclusion
- Submit your favorite tip
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
A Simple Web Browser Written in Java
StaceyWhitmore/simple-web-browser-in-java
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
A Simple Web Browser Written in Java
I wanted to code up a simple web browser perhaps to better understand how a browser makes http requests and renders pages to the browser. Naturally, Most would say C++ would be the best choice for creating a browser; however, since I am more familiar with Java, I decided to start with Java. I will add more comments and features down the road.
About
A Simple Web Browser Written in Java
How To Create A Web Browser In Java using Netbeans
by Didin J. on Okt. 24, 2021
A comprehensive step by step tutorial on how to create a web simple web browser in Java using Apache Netbeans IDE
In this tutorial, we will show you how to create a web simple web browser in Java using Apache Netbeans IDE. This time, we will use Java Desktop using Swing Framework. This desktop application is a cross-platform application that can run on Microsoft Windows, Mac OS, Linux, etc.
This tutorial is divided into several steps:
The flow of this simple web browser is very simple. There’s a JFrame that contains JTextField, JEditorPane, JButton, and JPanel. The JTextField is used to enter the web address. JButton is used to refresh the web browser. JEditorPane is used to display the web page found after entering the web address. JPanel uses to align other components’ positions or layouts.
We assume that you have downloaded and installed Apache Netbeans 12.4 and JDK 11. So, we can start this tutorial as per the steps above.
You can watch the video tutorial on our YouTube channel here.
Step #1: Create a New Java Application
To create a new Java application (Desktop Application), just start the Apache Netbeans 12.4.
Click File -> New Project in the menu or click the box with the plus icon in the toolbar.
Expand the Java with Ant in the categories then choose Java Application in the Projects then click the next button.
Fill the project name (ours: «MySimpleWebBrowser»), leave Project Location and Project Folder as defaults, uncheck the «User Dedicated Folder for Storing Libraries» checkbox, check «Create Main Class checkbox, and change the package name (ours: «com.djamware.MySimpleWebBrowser») then click the Finish button.
Now, we have a Java application created with a single main Java file inside the package.
Step #2: Add Required Swing Components
All required Swing components will be put in the JFrame. For that, create a new JFrame by right-clicking the Project name -> New -> JFrameForm.
The new Frame Form dialog will look like this.
Fill the name (ours: BrowserFrame), leave Project and Location as defaults, choose the package (ours: com.djamware), leave other fields as defaults then click the Finish button.
Resize the JFrame by drag the bottom right of Frame to fit the window. Drag and drop a Panel from the Palette pane to the top left corner of the JFrame.
Expand the JPanel to fill the JFrame vertically.
In the Properties pane -> Properties, find border properties then click the ellipsis button.
In the JPanel — border dialog, choose the Etched Border then click the OK button. Find the vertical size then set the value to 60. Make sure the Horizontal Resizable is checked. Switch to the Properties pane -> Code then change Variable Name to «topPanel».
Next, drag and drop again the Panel then resize to fit the rest of the Frame area and make the border as the previous Panel. Change the Variable Name to «bottomPanel». So the whole JPanel in the JFrame looks like this.
Next, drag and drop the Button component in the palette pane to the left side inside the topPanel. Change the Variable Name to «refreshButton» and change the text to «Refresh».
Next, drag and drop the Text Field from the palette pane to the topPanel right after the refresh button. Change the Variable Name to «addressField» and change the text to «Enter website address».
Next, drag and drop the Editor Pane from the palette pane to the bottomPanel. Resize the editor pane to fit the bottomPanel. Change the Variable Name to «browserPane». So, the whole JFrame look like this.
Step #3: Make a Simple Web Browser Working
To make the simple web browser work, we need to write some codes inside the JFrame class. For that, switch the Design to Source mode in the BrowserForm pane.
Add a method to set the web page to browserPane and the web address text to addressField that is wrapped by the try-catch block.
private void enterWebsite(String text) < try < browserPane.setPage(text); addressField.setText(text); >catch (IOException e) < JOptionPane.showMessageDialog(null, "Invalid URL!"); >>
The IOException that is caught will throw the message dialog if the URL from addressField is invalid.
Next, inside the BrowserForm method, add this event handler or action for addressField, browserPane, and refreshButton.
public BrowserForm() < initComponents(); addressField.addActionListener((ActionEvent event) ->< enterWebsite(event.getActionCommand()); >); browserPane.addHyperlinkListener((HyperlinkEvent event) -> < if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) < enterWebsite(event.getURL().toString()); >>); refreshButton.addActionListener((ActionEvent event) -> < enterWebsite(addressField.getText()); >); >
We are using HyperlinkEvent to catch the typed URL from the addressField then transform it as a page to the browserPane. HyperlinkEvent is used to notify interested parties that something has happened with respect to a hypertext link.
Step #4: Run and Test the Java Web Browser
Before running this Java application, right-click the project name in the Project pane then choose properties.
From the Categories choose Run and change the Main Class to «com.djamware.BrowserForm» by clicking the browse button then choosing that class. Click the OK button.
Next, run this Java application by clicking the play button in the toolbar. Here is what a simple web browser looks like.
Replace the Enter website address text with the valid URL then click Enter key. As you can see above, the website that you enter might not seem as expected because this is just a basic web browser which not compatible with modern web technologies.
That it’s, How To Create A Web Browser In Java using Netbeans. You can get the full source codes from our GitHub.
That just the basic. If you need more deep learning about Java and Spring Framework you can take the following cheap course:
Java Tip 66: Control browsers from your Java application
It’s great that Java applets and browsers are so tightly integrated, but what if you want to have your Java application display a URL? There’s no API call in any Java package that can help you with that.
However, using the exec() command, you can fork a process and issue a command to the underlying OS. The only problem is figuring out just which command needs to be issued to control the browsers on each platform.
On Unix, for Netscape, it was easy to figure this out as you only need to type «netscape -help». If Netscape is already running, the command is this:
netscape -remote openURL(http://www.javaworld.com)
And, if the browser is not already running, you type:
Under Windows, it took much exploration and a bit of luck to find something equivalent that wouldn’t open a new browser windows for each request. This command, in fact, works better then the Unix command, as you don’t have to know whether or not the browser is already running, and the command invokes the default browser — it is not hard-coded to run a Netscape browser. If Microsoft’s Internet Explorer is your default browser, then this will dislay the page in Internet Explorer. To display a page, issue the following command (you can try this in a DOS Shell): rundll32 url.dll,FileProtocolHandler http://www.javaworld.com
Follow-up tips
From Ryan Stevens: For Mac users, here’s an easy way to open a Web page in the default browser, usi ng MRJ 2.2:
import com.apple.mrj.MRJFileUtils; import java.io.*; class Open < String url = "http://www.yourpage.com/"; public static void main(String[] args) < new Open(); >Open() < try < MRJFileUtils.openURL(url); >catch (IOException ex) <> > >
You can launch the command line stuff on Mac similar to Unix (MacOS 8 and 9), except you must place the command-line tokens into a java.lang.String array. The array gets passed to the process exec() method. For example:
String[] commandLine = < "netscape", "http://www.javaworld.com/" >; Process process = Runtime.getRuntime().exec(commandLine);
The BrowserControl code
The class I have written, called BrowserControl takes the above into account and will work for both Windows and Unix platforms. For the Unix platform, you must have Netscape installed and in your path in order for this to work unmodified. If you’re a Mac user and know how to invoke a browser from within a Java application, let me know.
To display a page in your default browser, just call the following method from your application:
BrowserControl.displayURL("http://www.javaworld.com")
Note: You must include the URL protocol («http://» or «file://»).
Here is the code for BrowserControl.java :
import java.io.IOException; /** * A simple, static class to display a URL in the system browser.
* * Under Unix, the system browser is hard-coded to be 'netscape'. * Netscape must be in your PATH for this to work. This has been * tested with the following platforms: AIX, HP-UX and Solaris.
* * Under Windows, this will bring up the default browser under windows, * usually either Netscape or Microsoft IE. The default browser is * determined by the OS. This has been tested under Windows 95/98/NT.
* * Examples:
- *
- BrowserControl.displayURL(«http://www.javaworld.com») *
- BrowserControl.displayURL(«file://c:\\docs\\index.html») *
- BrowserContorl.displayURL(«file:///user/joe/index.html»); *
* Note - you must include the url type -- either "http://" or * "file://". */ public class BrowserControl < /** * Display a file in the system browser. If you want to display a * file, you must include the absolute path name. * * @param url the file's url (the url must start with either "http://" or * "file://"). */ public static void displayURL(String url) < boolean windows = isWindowsPlatform(); String cmd = null; try < if (windows) < // cmd = 'rundll32 url.dll,FileProtocolHandler http://. ' cmd = WIN_PATH + " " + WIN_FLAG + " " + url; Process p = Runtime.getRuntime().exec(cmd); >else < // Under Unix, Netscape has to be running for the "-remote" // command to work. So, we try sending the command and // check for an exit value. If the exit command is 0, // it worked, otherwise we need to start the browser. // cmd = 'netscape -remote openURL(http://www.javaworld.com)' cmd = UNIX_PATH + " " + UNIX_FLAG + "(" + url + ")"; Process p = Runtime.getRuntime().exec(cmd); try < // wait for exit code -- if it's 0, command worked, // otherwise we need to start the browser up. int exitCode = p.waitFor(); if (exitCode != 0) < // Command failed, start up the browser // cmd = 'netscape http://www.javaworld.com' cmd = UNIX_PATH + " " + url; p = Runtime.getRuntime().exec(cmd); >> catch(InterruptedException x) < System.err.println("Error bringing up browser, cmd='" + cmd + "'"); System.err.println("Caught: " + x); >> > catch(IOException x) < // couldn't exec browser System.err.println("Could not invoke browser, command=" + cmd); System.err.println("Caught: " + x); >> /** * Try to determine whether this application is running under Windows * or some other platform by examing the "os.name" property. * * @return true if this application is running under a Windows OS */ public static boolean isWindowsPlatform() < String os = System.getProperty("os.name"); if ( os != null && os.startsWith(WIN_ID)) return true; else return false; >/** * Simple example. */ public static void main(String[] args) < displayURL("http://www.javaworld.com"); >// Used to identify the windows platform. private static final String WIN_ID = "Windows"; // The default system browser under windows. private static final String WIN_PATH = "rundll32"; // The flag to display a url. private static final String WIN_FLAG = "url.dll,FileProtocolHandler"; // The default browser under unix. private static final String UNIX_PATH = "netscape"; // The flag to display a url. private static final String UNIX_FLAG = "-remote openURL"; >
Conclusion
is a class that allows you to control your system’s native browser from any Java application. By using a native browser to display HTML, you get more complete support and faster rendering of HTML, while reducing the amount of code you have to write. And, your users have less to learn, as they are likely already familiar with their system’s browser.
Submit your favorite tip
We would like to pass on your Java tips to the rest of the Java world. For detailed guidelines on what we’re looking for in a Java Tip and how to ensure that your tip has all the necessary elements, see the Java Tips Index page—and be sure to read the Java Tips Author Guidelines carefully.
Once you’ve read the guidelines, go ahead and write up your coolest tips and tricks, and send them to tips at javaworld.com. You may find yourself an author in JavaWorld with your helpful hints chosen as the next Java Tip!
Steven Spencer is a senior software engineer at Lumos Technologies, where he focuses on user interfaces and Java components. When not training his computer, he trains his yellow Labrador, Ally.
This story, «Java Tip 66: Control browsers from your Java application» was originally published by JavaWorld .
Next read this: