Applets in Java
1. Passing Parameters to Applets
Applets can receive values from the HTML file through <param> tag. The applet retrieves
them using getParameter() method.
Example (Java):
import [Link];
import [Link];
public class ParamApplet extends Applet {
String message;
public void init() {
// Getting parameter from HTML
message = getParameter("msg");
if (message == null) {
message = "Default Message";
}
}
public void paint(Graphics g) {
[Link](message, 20, 20);
}
}
Example (HTML):
<applet code="[Link]" width="300" height="200">
<param name="msg" value="Hello Ankita!">
</applet>
2. Aligning the Display
We use drawString() with (x,y) coordinates. Proper alignment can be done by adjusting
coordinates.
Example:
public void paint(Graphics g) {
[Link]("Top Left", 10, 20);
[Link]("Center", getWidth()/2, getHeight()/2);
[Link]("Bottom Right", getWidth()-100, getHeight()-10);
}
3. Displaying Numerical Values
You can display numbers directly using drawString(). Convert numeric values to string
using [Link]() or concatenation.
Example:
public void paint(Graphics g) {
int a = 5, b = 10;
int sum = a + b;
[Link]("Sum of " + a + " and " + b + " = " + sum, 20, 50);
}
4. Getting Input from the User
Unlike standalone Java, applets don’t use Scanner. You can take input using TextField,
Button, etc. (AWT components).
Example:
import [Link];
import [Link].*;
import [Link].*;
public class InputApplet extends Applet implements ActionListener {
TextField t1, t2;
Button b;
int sum = 0;
public void init() {
t1 = new TextField(5);
t2 = new TextField(5);
b = new Button("Add");
add(t1);
add(t2);
add(b);
[Link](this);
}
public void actionPerformed(ActionEvent e) {
int a = [Link]([Link]());
int b = [Link]([Link]());
sum = a + b;
repaint();
}
public void paint(Graphics g) {
[Link]("Sum: " + sum, 20, 100);
}
}
How AWT is Used in Code
AWT provides classes in the package:
import [Link].*;
Java's Abstract Window Toolkit (AWT), "Windows Fundamentals" refers to
the core classes and concepts for creating and managing graphical user
interface (GUI) windows, which are represented by the hierarchy
of Component (abstract), Container, Window, Frame, and Panel classes.
Key fundamentals include the top-level Frame for main application
windows with borders and title bars, and the Panel for grouping other
components within a window or frame. Understanding how these
components are arranged, how to display and hide them, and how to handle
events is crucial for building AWT applications.