What is JApplet in Swing?

JApplet:
JApplet is a class in javax.swing that represents swing applet.
An applet is a small program which runs in the web browser.
To create a Swing applet developers often extend the JApplet class.
Life Cycle methods:
There are 4 methods to represent the life cycle of the JApplet and they are:
intit(): it is called only once when the applet is created.
start(): it is called whenever the applet becomes not visible or starts after being paused.
stop(): it is called whenever the applet becomes not visible or when the applet is paused.
destroy(): it is called when the applet is about to be unloaded.
Swing components in applets:
Like JFrame, JApplet can include various Swing components like buttons, labels and panels.
To add swing components to JApplet we can follow the same principles which we followed to use JFrame.
Displaying in a web browser:
- To display JApplet in a web browser we can use <applet> tag embedded with the .class file in HTML
Layout managers:
Layout managers like flow layout, border layout and others can be used to arrange components within the applet.
Event Handling:
Event handling in swing applets is done using Listeners to capture user interactions.
Program:
// Java program to demonstrate using JApplet. import javax.swing.JApplet; import javax.swing.JButton; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; class MyApplet extends JApplet { public void init() { JButton button = new JButton("Click me"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("Button Clicked"); } }); add(button); } public void start(){} public void stop(){} public void destroy(){} }
Subscribe to my newsletter
Read articles from Sai Sahith Polimera directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
