Java Program to Goto a Link Using Applet
In this article, we shall be animating the applet window to show the goto link in Java Applet. A Goto link is basically, any particular link that redirects us from one page to another.
Approach to Implement Goto a Link using Applet
- Create an applet with the two buttons.
- Add ActionListener to the buttons.
- Form the complete URL of the page.
- Use the Desktop class of java.awt package to open the link.
Note: Java Version : 1.8 and above required
Goto a Link using Java Applet
Below is the implementation of the above method:
Java
// Java Program to implement // Java Applet for goto a link import java.applet.*; import java.awt.*; import java.awt.Desktop.*; import java.awt.event.*; import java.net.*; // Driver Class public class GotoLink extends Applet implements ActionListener { // Function to initialize the applet public void init() { setBackground(Color.white); // Button Created Button b1 = new Button( "google" ); Button b2 = new Button( "facebook" ); this .add(b1); this .add(b2); // Action Listener to check which option choose b1.addActionListener( this ); b2.addActionListener( this ); } // Function to go to the link public void actionPerformed(ActionEvent e) { String button = e.getActionCommand(); String link = "https://www." + button + ".com" ; try { Desktop.getDesktop().browse( new URI(link)); } catch (Exception ex) { ex.printStackTrace(); } } } /* <applet code=GotoLink.class width=400 height=400> </applet> */ |
Executing the Applet Program
Save the file with the name GotoLink.java
javac GotoLink.java
Applet Viewer GotoLink.java
Output
Test case 1: Applet Output
Test Case 2 : When user click on google button
Test Case 2 : When user click on facebook button
Explaination of the Above Program
- For Example: https://www.w3wiki.net/ or https://www.google.com/
- Use Desktop class to handle the URI (Uniform Resource Identifier) file.
- Use method browse(URI) to open the link in the default browser of the system eg. Google Chrome.
- public void init() function is used to initialize the applet.
- public void actionPerformed(ActionEvent e) fucntion is used to check on button click what logic we have to perform in our case it will take us to external url like google.com or facebook.com
- Action Listener is used to check which button is selected.