Open In App

Java Program to Goto a Link Using Applet

Last Updated : 29 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

  1. Create an applet with the two buttons.
  2. Add ActionListener to the buttons.
  3. Form the complete URL of the page.
  4. 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

Applet Vieweer Output

Test Case 2 : When user click on google button

Redirecting to Google.com

Test Case 2 : When user click on facebook button

Redirecting to facebook.com

Explaination of the Above Program

  1. For Example: https://www.geeksforgeeks.org/ or https://www.google.com/
  2. Use Desktop class to handle the URI (Uniform Resource Identifier) file.
  3. Use method browse(URI) to open the link in the default browser of the system eg. Google Chrome.
  4. public void init() function is used to initialize the applet.
  5. 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
  6. Action Listener is used to check which button is selected.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads