This is a Java Program to go to a Link using Applet
We have to write a program in Java such that it creates an applet where the user has got choices of two links. When the user clicks on either of the buttons, the link is opened in the default web browser.
For opening a link using applet, we can have the following 3 different sets of input and output.
1. To view the applet :
When the program is executed, it is expected that the applet contains two button - google and yahoo.
2. When the user selects Google :
If the user selects the button labeled "google", then it is expected that the default google page is opened in the browser.
3. When the user selects Yahoo :
If the user selects the button labeled "yahoo", then it is expected that the default yahoo page is opened in the browser.
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.
Here is source code of the Java Program to open a link using an applet. The program is successfully compiled and tested using javac compiler on Fedora 30. The program output is also shown below.
/* Java Program to Go To a Link using Applet */
import java.awt.*;
import java.applet.*;
import java.net.*;
import java.awt.event.*;
import java.awt.Desktop.*;
public class Goto_Link extends Applet implements ActionListener
{
//Function to initialize the applet
public void init()
{
setBackground(Color.white);
Button button1 = new Button("google");
Button button2 = new Button("yahoo");
this.add(button1);
this.add(button2);
button1.addActionListener(this);
button2.addActionListener(this);
}
//Function to go to the link
public void actionPerformed(ActionEvent e)
{
String button = e.getActionCommand();
String link = "http://www."+button+".com";
try
{
Desktop.getDesktop().browse(new URI(link));
}
catch (Exception E)
{
}
}
}
/*
<applet code=Goto_Link.class width=500 height=500>
</applet>
*/
To compile and execute the program use the following commands :
>>> javac Goto_Link.java >>> appletviewer Goto_Link.java
1. To form a complete link prefix “http://www.” before the domain and suffix “.com” after it.
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.
Here’s the run time test cases for opening a link using an applet.
Test case 1 – To View the Applet
Test case 2 – Go To Google (When the user selects Google)
Test case 3 – Go To Yahoo (When the user selects Yahoo)
Sanfoundry Global Education & Learning Series – Java Programs.
- Check Programming Books
- Apply for Java Internship
- Practice Information Technology MCQs
- Check Java Books
- Practice Programming MCQs