Core_java_Unit_V

unit3

Applet, AWT, Event and Swing Programming Applet

5.1 Introduction

Applets were a significant part of early Java development, offering a way to create interactive web-based applications. They were primarily used for creating small programs embedded within web pages to provide dynamic and interactive content. Applets were executed within the web browser's Java Virtual Machine (JVM) plugin, providing a platform-independent way to deliver rich client-side functionality.

Characteristics of Applets:

1. Embedded in Web Pages: Applets were designed to be embedded within HTML pages using the >applet< tag.
2. Platform Independence: Like all Java programs, applets were platform-independent, meaning they could run on any system with a Java Virtual Machine (JVM).
3. GUI Components: Applets could contain graphical user interface (GUI) components like buttons, text fields, and graphics.
4. Networking Support: They could make network connections to fetch data from servers or interact with other applets.
5. Limited Access to System Resources: For security reasons, applets were restricted in their access to system resources like file system and local devices.

5.2 Types of applet

In Java, there are primarily two types of applets based on their life cycle and how they are embedded within web pages:
1. Standalone Applets:
o Standalone applets are run outside of a web browser, typically within an applet viewer or an integrated development environment (IDE).
o They are executed independently of any web page.
o These applets are useful for testing and debugging applet functionality before embedding them into web pages.

2. Embedded Applets:
o Embedded applets are designed to be included within web pages and run within a web browser.
o They are embedded using the <applet> HTML tag or, more commonly nowadays, the <object> or <embed> tag (for HTML5).

5.3 Applet Lifecycle

• Initialization (init): This method is called when the applet is first loaded into memory. It is used for one-time initialization tasks.
• Start (start): This method is called after the initialization and whenever the applet is restarted or brought back into focus. It is used to start any animations or other ongoing activities.
• Stop (stop): This method is called when the applet is suspended or sent to the background. It is used to stop ongoing activities like animations.
• Destroy (destroy): This method is called when the applet is about to be destroyed. It is used to release any resources held by the applet.

5.3.1 Creating applet

An applet class in Java typically extends the java.applet.Applet class or implements the java.applet.Applet interface. Here's a basic structure of an applet class:

import java.applet.Applet;
import java.awt.Graphics;

public class MyApplet extends Applet {
// Applet initialization method
public void init() {
// Initialization code here
}

// Method to paint the applet
public void paint(Graphics g) {
// Drawing code here
}
}

5.3.2 Applet tag

The <applet> tag was used in HTML to embed Java applets within web pages. It provided a way to integrate interactive Java content into web pages, allowing developers to create rich client-side applications.

Here's a basic structure of the <applet> tag:


<applet code="AppletClassName.class" width="width" height="height">
<!-- Optional parameters -->
<param name="parameterName1" value="parameterValue1">
<param name="parameterName2" value="parameterValue2">
<!-- More parameters if needed -->
Your browser does not support Java applets.
</applet>

Attributes of the <applet> tag:


• code: Specifies the name of the Java class file (with the .class extension) that contains the applet's code.
• width: Specifies the width of the applet in pixels.
• height: Specifies the height of the applet in pixels.

Optional Parameters (specified using <param> tags):


• Parameters can be used to pass data to the applet.
• These parameters can be accessed by the applet using the getParameter() method.

Example:


<applet code="MyApplet.class" width="300" height="200">
<param name="param1" value="value1">
<param name="param2" value="value2">
Your browser does not support Java applets.
</applet>

5.4 Applet Classes

5.4.1 Color Class

The Color class in Java is used to encapsulate colors in the RGB (Red, Green, Blue) color model. It provides constructors and methods to create and manipulate colors for use in graphical applications.

Example:

import java.awt.Color;
import java.applet.Applet;
import java.awt.Graphics;

public class MyColorApplet extends Applet {
public void paint(Graphics g) {
// Set color using predefined constants
g.setColor(Color.RED);

// Draw a rectangle filled with the specified color
g.fillRect(10, 10, 100, 100);

// Create a custom color
Color customColor = new Color(100, 200, 50); // RGB values
g.setColor(customColor);

// Draw another rectangle filled with the custom color
g.fillRect(150, 10, 100, 100);
}
}

5.4.2 Graphics Class

The Graphics class in Java provides methods for drawing graphics, text, and images on a component. It serves as the primary interface for rendering graphics in Java applets.

Example:

import java.awt.Graphics;
import java.applet.Applet;

public class MyGraphicsApplet extends Applet {
public void paint(Graphics g) {
// Draw a line
g.drawLine(10, 10, 100, 100);

// Draw a rectangle
g.drawRect(120, 10, 100, 50);

// Draw a filled rectangle
g.fillRect(230, 10, 100, 50);

// Draw an oval
g.drawOval(10, 120, 100, 50);

// Draw a filled oval
g.fillOval(120, 120, 100, 50);
}
}

5.4.3 Font Class

The Font class in Java represents fonts. It provides constructors and methods to create and manipulate font objects, including specifying the font family, style, and size.

Example:

import java.awt.Font;
import java.applet.Applet;
import java.awt.Graphics;

public class MyFontApplet extends Applet {
public void paint(Graphics g) {
// Create a font object
Font font = new Font("Arial", Font.BOLD, 24);

// Set the font for drawing text
g.setFont(font);

// Draw text using the specified font
g.drawString("Hello, World!", 50, 50);
}
}

AWT

AWT (Abstract Window Toolkit) is a set of Java APIs used to create graphical user interfaces (GUIs) and handle input/output operations. It provides a platform-independent way to create windows, dialogs, buttons, text fields, and other GUI components for Java applications.

Key Features of AWT:

1. Platform Independence: AWT provides a platform-independent way to create GUIs, allowing Java applications to run on different operating systems without modification.
2. GUI Components: AWT includes a wide range of GUI components, such as buttons, text fields, labels, checkboxes, lists, and menus, to build interactive user interfaces.
3. Event Handling: AWT provides event handling mechanisms to respond to user actions, such as mouse clicks, keyboard input, and window events.
4. Layout Management: AWT includes layout managers to arrange GUI components within containers, ensuring proper alignment and resizing of components across different window sizes.
5. Graphics and Drawing: AWT provides classes and methods for drawing shapes, images, and text onto graphical surfaces, enabling custom graphics and visualizations.
6. Integration with Native System: AWT components are lightweight and integrate seamlessly with the native system's windowing toolkit, providing a native look and feel across different platforms.

5.5 Components and container used in AWT

In AWT (Abstract Window Toolkit), GUI components are divided into two main categories: Components and Containers.

Components:

1. Button: A push-button component that can be clicked by the user to trigger an action.
2. Label: A non-editable text component used to display a single line of text or an image.
2. Label: A non-editable text component used to display a single line of text or an image.
3. TextField: An editable text component that allows the user to input text.
4. Checkbox: A component that represents a toggleable option or state.
5. CheckboxGroup: A group of checkboxes that are mutually exclusive within the same group.
6. Choice: A drop-down list of selectable items.
7. List: A list component that allows the user to select one or more items from a list of options.
8. Scrollbar: A component that provides a way to scroll through content, such as text or images.
9. Canvas: A blank rectangular area where custom graphics can be drawn.

Containers:

1. Frame: A top-level window with a title bar and border.
2. Dialog: A modal or modeless dialog box that displays a message or prompts the user for input.
3. Panel: A generic container used to group and organize other components.
4. Window: An abstract base class for top-level windows, including frames and dialogs.
5. Applet: A container used to embed Java applets within web pages.
6. ScrollPane: A container used to add scrolling capabilities to other components.

5.6 Layout managers

In AWT, layout managers are used to arrange and manage the placement of components within containers. Some commonly used layout managers include:
1. FlowLayout: Arranges components in a row or column, wrapping to the next row or column as needed.
2. BorderLayout: Divides the container into five regions: North, South, East, West, and Center, each of which can contain a single component.
3. GridLayout: Arranges components in a grid of rows and columns, with each cell containing one component.

5.7 Listeners and Adapter classes

In AWT (Abstract Window Toolkit) and Swing, event handling is accomplished using listeners and adapter classes. These classes provide a way to respond to user actions, such as mouse clicks, keyboard input, and window events.

Listeners:

Listeners are interfaces that define methods to handle specific types of events. To respond to an event, you implement the corresponding listener interface and provide implementations for its methods.

Example:

1. ActionListener: Handles action events, such as button clicks.
2. MouseListener: Handles mouse events, such as mouse clicks, movements, and entering/exiting components.
3. KeyListener: Handles keyboard events, such as key presses and releases.
4. WindowListener: Handles window events, such as window opening, closing, and activation.

Adapter Classes:

Adapter classes are abstract classes that provide default implementations for listener interfaces. They are useful when you want to implement only a subset of the methods in a listener interface.

Example:

1. MouseAdapter: Provides default implementations for all methods in the MouseListener interface. You can override only the methods you need.
2. KeyAdapter: Provides default implementations for all methods in the KeyListener interface.
3. WindowAdapter: Provides default implementations for all methods in the WindowListener interface.

Usage:

import java.awt.*;
import java.awt.event.*;

public class MyButtonApplet extends java.applet.Applet {
private Button button;

public void init() {
button = new Button("Click Me");
add(button);

// Register ActionListener using a lambda expression
button.addActionListener((ActionEvent e) -> {
System.out.println("Button clicked");
});

// Register MouseListener using an anonymous inner class
button.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked");
}
});

// Register KeyListener using an adapter class
button.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
System.out.println("Key typed: " + e.getKeyChar());
}
});

// Register WindowListener using an adapter class
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}

In this example, we register event listeners using various approaches:
• ActionListener: Using a lambda expression.
• MouseListener: Using an anonymous inner class.
• KeyListener: Using an adapter class (KeyAdapter).
• WindowListener: Using an adapter class (WindowAdapter).

5.8 Event Delegation model

The Event Delegation Model is a design pattern used in GUI programming to handle events in a hierarchical manner. It is commonly employed in frameworks like AWT (Abstract Window Toolkit) and Swing in Java.

Key Concepts:

1. Event Source: The component that generates an event, such as a button or a text field.
2. Event Listener: An object that listens for events generated by an event source and responds to them by invoking appropriate methods.
3. Event Object: An object that encapsulates information about an event, such as its type and the source that generated it.
4. Event Dispatching: The process of dispatching events from event sources to registered event listeners.

How It Works:

1. Registration: Event listeners are registered with event sources to receive notifications when events occur.
2. Event Generation: When an event occurs (e.g., a button is clicked), the event source creates an event object and dispatches it to registered listeners.
3. Event Dispatching: The event object is passed to the appropriate event listener, which invokes the appropriate event handling method.
4. Propagation: If an event is not handled by the listener associated with the event source, it may be propagated up the component hierarchy to be handled by higher-level containers or the application itself.

Advantages:

1. Decoupling: Event sources and event listeners are decoupled, allowing for better separation of concerns and modularity in the code.
2. Flexibility: Multiple listeners can be registered with a single event source, enabling different components of the application to respond to the same events independently.
3. Efficiency: Events are dispatched directly to registered listeners, minimizing unnecessary processing and improving performance.

Example:

import java.awt.*;
import java.awt.event.*;

public class EventDelegationExample extends Frame implements ActionListener {
private Button button;

public EventDelegationExample() {
super("Event Delegation Example");

// Create a button
button = new Button("Click Me");

button.addActionListener(this); // Register this frame as the ActionListener

// Add the button to the frame
add(button);

// Set frame size and visibility
setSize(200, 100);
setVisible(true);

// Handle window closing event
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

// ActionListener method
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked");
}

public static void main(String[] args) {
new EventDelegationExample();
}
}

In this example:

• The EventDelegationExample class extends Frame and implements ActionListener.
• The Button component is the event source, and it registers the EventDelegationExample instance as its action listener using the addActionListener() method.
• When the button is clicked, the actionPerformed() method of the EventDelegationExample class is invoked to handle the event.

Swing

5.9 Introduction to Swing Component and Container Classes

Swing is a GUI (Graphical User Interface) toolkit for Java that provides a set of lightweight components for building rich desktop applications. It is part of the Java Foundation Classes (JFC) and is built on top of the AWT (Abstract Window Toolkit).

Key Features of Swing:

1. Platform Independence: Swing components are implemented entirely in Java, making them platform-independent and capable of running on any system with a Java Virtual Machine (JVM).
2. Lightweight Components: Unlike AWT components, Swing components are lightweight and do not rely on native peers, resulting in improved performance and consistency across different platforms.
3. Rich Set of Components: Swing provides a wide range of components, including buttons, labels, text fields, text areas, tables, trees, and more, enabling developers to create sophisticated GUIs.
4. Customizable Look and Feel: Swing supports pluggable look and feel (PLAF), allowing developers to customize the appearance of their applications to match the native look and feel of different operating systems or create custom designs.
5. Enhanced Layout Managers: Swing offers advanced layout managers, such as BorderLayout, GridLayout, and GridBagLayout, for flexible and precise arrangement of components within containers.
6. Event Handling: Swing provides comprehensive support for event handling, including listeners and adapters, to respond to user actions, such as mouse clicks, keyboard input, and window events.

5.10 Exploring Swing Controls-

In Swing, GUI components are divided into two main categories: Components and Containers. Components are the basic building blocks of the user interface, while containers are components that can contain other components.

Swing Components:

1. JButton: A button that can be clicked by the user to trigger an action.
2. JLabel: A non-editable text component used to display a single line of text or an image.
3. JTextField: An editable text component that allows the user to input text.
4. JTextArea: A multi-line text component that allows the user to input and display multiple lines of text.
5. JCheckBox: A component that represents a toggleable option or state.
6. JRadioButton: A component that represents a choice among a group of mutu=lly exclusive options.
7. JComboBox: A drop-down list of selectable items.
8. JList: A list component that allows the user to select one or more items from a list of options.
9. JScrollPane: A container used to add scrolling capabilities to other components.
10. JTable: A table component that displays data in tabular form.
11. JPanel: A generic container used to group and organize other components.
12. JScrollPane: A container used to add scrolling capabilities to other components.
13. JMenuBar: A menu bar component that contains menus.

Swing Containers:

1. JFrame: A top-level window with a title bar, border, and optional menu bar.
2. JDialog: A modal or modeless dialog box that displays a message or prompts the user for input.
3. JApplet: A container used to embed Java applets within web pages.
4. JWindow: A top-level window without a title bar or border.
5. JPanel: A generic container used to group and organize other components.
6. JScrollPane: A container used to add scrolling capabilities to other components.

Example:

import javax.swing.*;

public class SwingComponentsExample {
public static void main(String[] args) {
// Create a JFrame (window)
JFrame frame = new JFrame("Swing Components Example");

// Create components
JButton button = new JButton("Click Me");
JLabel label = new JLabel("Enter your name:");
JTextField textField = new JTextField(20);
JTextArea textArea = new JTextArea(5, 20);
JCheckBox checkBox = new JCheckBox("Check me");
JRadioButton radioButton1 = new JRadioButton("Option 1");
JRadioButton radioButton2 = new JRadioButton("Option 2");
JComboBox comboBox = new JComboBox<>(new String[] { "Option 1", "Option 2", "Option 3" });
JList list = new JList<>(new String[] { "Item 1", "Item 2", "Item 3" });
JScrollPane scrollPane = new JScrollPane(textArea);

// Add components to a panel
JPanel panel = new JPanel();
panel.add(label);
panel.add(textField);
panel.add(button);
panel.add(textArea);
panel.add(checkBox);
panel.add(radioButton1);
panel.add(radioButton2);
panel.add(comboBox);
panel.add(list);
panel.add(scrollPane);

// Add panel to the content pane of the frame
frame.getContentPane().add(panel);

// Set frame size, default close operation, and visibility
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

In this example, we create a JFrame and add various Swing components and containers to it, such as JButton, JLabel, JTextField, JTextArea, JCheckBox, JRadioButton, JComboBox, JList, JScrollPane, and JPanel. These components and containers can be customized and arranged to create rich and interactive user interfaces in Java Swing applications.

No comments:

Post a Comment