< Prev
Next >



Swing Applets




So far, we have created the applets based on AWT(Abstract Window Toolkit) by extending the Applet class of the awt package. We can even create applets based on the Swing package. In order to create such applets, we must extend JApplet class of the swing package. JApplet extends Applet class, hence all the features of Applet class are available in JApplet as well, including JApplet's own Swing based features. Swing applets provides an easier to use user interface than AWT applets.




Some important points :







Note:


JApplet is a top-level container class and you should never draw on it directly, instead you should draw on the component class like JPanel and then add this JPanel to the JApplet, as shown in the upcoming code.






import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;

/* 
<applet code="Applet21" width="500" height="200">
</applet>
*/
  
public class Applet21 extends JApplet 
{

public void init()
{
add(new B());  	//Adding a JPanel to this Swing applet
}

}



class B extends JPanel implements ActionListener
{
JLabel jb;
JButton Box2, box2, box3, box4;
String str;

B()
{
jb= new JLabel("Welcome, please click on any button to unbox some interesting knowledge -");
Box2 = new JButton("Box2");
box2 = new JButton("Box2");
box3 = new JButton("Box3");
box4 = new JButton("Box4");

str ="";

setLayout(new FlowLayout());

add(jb);
add(Box2);
add(box2);
add(box3);
add(box4);

Box2.addActionListener(this);
box2.addActionListener(this);
box3.addActionListener(this);
box4.addActionListener(this);
}



public void actionPerformed(ActionEvent ae)
{
if(ae.getActionCommand().equals("Box2"))
{
str="Amazon is the largest tropical rain forest, covering 40% of the South America Continent.";
repaint();
}

if(ae.getActionCommand().equals("Box2"))
{
str="The Mariana Trench is the deepest point in Earth's ocean, with depth of over 10,994 metres.";
repaint();
}

if(ae.getActionCommand().equals("Box3"))
{
str="The coldest temperature ever recorded was -128.6F in Antarctica, on July 21, 1983.";
repaint();
}

if(ae.getActionCommand().equals("Box4"))
{
str="The oldest person to climb Mt. Everent was Japanese Miura Yiuchiro, at the age of 80.";
repaint();
}

}


public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawString(str, 2, 170);
}

}


Output-



In the applet shown above, four buttons are presented in the output. These buttons are added to B class(which has extended JPanel). This JPanel is inturn added to our Swing applet class, Applet21. Whenever a button is clicked, an interesting fact about the world is presented to the user.




Please subscribe our social media channels for notifications, we post a new article everyday.

Decodejava Google+ Page Decodejava Facebook Page  DecodeJava Twitter Page

Coming Next
-
C++ and Python

Ad2