UNIT 5 GUI

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

Unit 5:- Event and GUI programming

Event handling in java:-


Event handling in Java involves managing and responding to events generated by
various user interactions or system activities, such as button clicks, mouse movements,
keyboard inputs, and more. Java provides a comprehensive event handling mechanism
through the AWT (Abstract Window Toolkit) and Swing libraries. Event handling is
an essential aspect of graphical user interface (GUI) programming, enabling
applications to respond to user actions effectively.

Here's an overview of event handling in Java:

 Event Source:
An event source is an object that generates events. Common event sources include
GUI components like buttons, text fields, and mouse-related actions.

 Event Listener:
An event listener is an object that waits for and responds to events generated by an
event source. Event listeners are registered with event sources to receive notifications
about specific types of events.

 Event Object:
An event object encapsulates information about the event that occurred. It contains
details such as the event type, the source of the event, and any additional data related
to the event.

Event Handling Steps:

1. Register Event Listeners: You associate an event listener (implementing a


specific listener interface) with an event source using methods like
addActionListener() for buttons.
2. Implement Listener Methods: Implement the required methods of the listener
interface to specify what should happen when the event occurs.
3. Receive and Respond to Events: When an event is triggered by the event source,
the appropriate listener method is invoked to handle the event.

For registering the component with the Listener, many classes provide the
registration methods. For example:

 Button:
public void addActionListener(ActionListener a){}

 MenuItem:
public void addActionListener(ActionListener a){}

 TextField:
public void addActionListener(ActionListener a){}
public void addTextListener(TextListener a){}
 TextArea:
public void addTextListener(TextListener a){}

 Checkbox:
public void addItemListener(ItemListener a){}

 Choice:
public void addItemListener(ItemListener a){}

 List:
public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){}

Types of event:-

In Java's event handling mechanism, various types of events can be generated by user
interactions and system activities. Each type of event corresponds to a specific listener
interface that defines the methods to be implemented for handling that type of event.
Here are some common event types in Java and their corresponding listener interfaces:

1. Action Events:
- Action events are generated by components like buttons, menu items, and text
fields when the user performs an action like clicking a button or pressing "Enter" in a
text field.
- Corresponding Listener Interface: `ActionListener`
- Listener Methods: `actionPerformed(ActionEvent e)`

2. Mouse Events:
- Mouse events are generated when the user interacts with the mouse, including
clicking, moving, dragging, and releasing the mouse button.
- Corresponding Listener Interfaces: `MouseListener`, `MouseMotionListener`
- Listener Methods: `mouseClicked(MouseEvent e)`, `mousePressed(MouseEvent
e)`, `mouseReleased(MouseEvent e)`, `mouseEntered(MouseEvent e)`,
`mouseExited(MouseEvent e)`, `mouseMoved(MouseEvent e)`,
`mouseDragged(MouseEvent e)`

3. Key Events:
- Key events are generated when the user interacts with the keyboard, including
pressing and releasing keys.
- Corresponding Listener Interface: `KeyListener`
- Listener Methods: `keyPressed(KeyEvent e)`, `keyReleased(KeyEvent e)`,
`keyTyped(KeyEvent e)`

4. Window Events:
- Window events are generated when a window's state changes, such as when it is
opened, closed, activated, deactivated, or resized.
- Corresponding Listener Interface: `WindowListener`
- Listener Methods: `windowOpened(WindowEvent e)`,
`windowClosing(WindowEvent e)`, `windowClosed(WindowEvent e)`,
`windowIconified(WindowEvent e)`, `windowDeiconified(WindowEvent e)`,
`windowActivated(WindowEvent e)`, `windowDeactivated(WindowEvent e)`

5.Focus Events:
-Focus events are generated when a component gains or loses focus, indicating
that it is currently accepting input.
- Corresponding Listener Interface: `FocusListener`
- Listener Methods: `focusGained(FocusEvent e)`, `focusLost(FocusEvent e)`

6. Item Events:
- Item events are generated by components like checkboxes, radio buttons, and
combo boxes when their selection state changes.
- Corresponding Listener Interface: `ItemListener`
- Listener Method: `itemStateChanged(ItemEvent e)`

7. List Selection Events:


- List selection events are generated by components like lists and tables when the
selection of items changes.
- Corresponding Listener Interface: `ListSelectionListener`
- Listener Method: `valueChanged(ListSelectionEvent e)`

These are just a few examples of the many event types available in Java's event
handling mechanism. Depending on the components and user interactions in your
graphical user interface, you may need to implement multiple listener interfaces to
handle different event types effectively.

Java frames:-
n Java, frames are the top-level windows that serve as containers for building
graphical user interfaces (GUIs) using components like buttons, labels, text fields, and
more. Frames provide the main window in which you can place and organize various
GUI elements. Java's GUI libraries, such as AWT (Abstract Window Toolkit) and
Swing, offer classes for creating and working with frames.

import javax.swing.*;

public class SimpleFrameExample {


public static void main(String[] args) {
JFrame frame = new JFrame("My Simple Frame"); // Create a frame with a title
frame.setSize(400, 300); // Set the dimensions of the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Close operation
frame.setVisible(true); // Make the frame visible
}
}
In this example, we use the JFrame class from the Swing library to create a simple
frame. Key steps include:

 Creating an instance of JFrame.


 Setting the title of the frame using setTitle().
 Specifying the dimensions of the frame using setSize().
 Setting the close operation when the frame is closed using
setDefaultCloseOperation().
 Making the frame visible using setVisible().

The JFrame class provides various methods and properties to customize the
appearance and behavior of the frame. You can add components like buttons, labels,
and panels to the frame to build complex GUIs.

Java panels:

n Java GUI programming, a panel is a container component that is used to group and
organize other components within a frame or another container. Panels are often used
to create visually organized sections of a user interface. Both AWT (Abstract Window
Toolkit) and Swing provide classes for creating and working with panels.

Here's an example of creating a panel using the Swing library:

import javax.swing.*;

public class PanelExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Panel Example");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create a panel
JPanel panel = new JPanel();

// Add components to the panel


JLabel label = new JLabel("This is a label");
JButton button = new JButton("Click Me");
panel.add(label);
panel.add(button);

// Add the panel to the frame


frame.add(panel);

frame.setVisible(true);
}
}
In this example, we create a JPanel and add components like a label and a button to it.
The JPanel acts as a container for these components. We then add the panel to the
JFrame, which displays the panel along with its contents.
Here's a brief overview of using panels in Java GUI programming:

1.Creating a Panel:
Create an instance of the panel class, such as JPanel in Swing or Panel in AWT.

2.Adding Components:
Use the add() method of the panel to add components like buttons, labels, text fields,
etc.

3.Layout Management:
Panels support layout managers that determine how components are arranged within
the panel. Common layout managers include FlowLayout, BorderLayout, GridLayout,
and BoxLayout.

4.Nesting Panels:
You can nest panels within other panels to create more complex layouts.

5.Customization:
Panels can have their own properties and behaviors that can be customized using
appropriate methods.

Both Swing and AWT provide panel classes (JPanel in Swing and Panel in AWT), but
Swing's JPanel offers additional features and greater flexibility. When developing
modern GUI applications, it's recommended to use Swing components due to their
enhanced capabilities and better look-and-feel.

Layout manager:-

Layout managers in Java GUI programming are classes that help you arrange and
organize components within a container, such as a frame or panel. They handle the
positioning and sizing of components based on certain rules and policies. Java
provides several layout managers through the AWT (Abstract Window Toolkit) and
Swing libraries to assist you in creating visually appealing and responsive user
interfaces.

Here are some common layout managers available in Java:

1.FlowLayout:

FlowLayout arranges components in a left-to-right or top-to-bottom flow, respecting


the preferred sizes of components.
Components are placed next to each other or below one another in the order they are
added.
Suitable for simple layouts where components don't need complex positioning.

2.BorderLayout:

BorderLayout divides the container into five regions: NORTH, SOUTH, EAST,
WEST, and CENTER.
Each region can hold one component, and the CENTER region takes up any
remaining space.
Useful for creating a basic structure with a main component in the center and optional
components along the borders.

3.GridLayout:

GridLayout arranges components in a grid, with a specified number of rows and


columns.
All components have the same size and occupy equal space within their cells.
Useful for creating uniform layouts of components.

4.GridBagLayout:

GridBagLayout is a more flexible grid layout manager that allows components to span
multiple rows and columns.
Components can have different sizes and can be aligned both horizontally and
vertically.
Suitable for complex and customized layouts.

5.BoxLayout:

BoxLayout arranges components either in a vertical or horizontal line.


Components can be evenly distributed or have variable sizes.
Useful for creating simple stacked or sequential layouts.

6.CardLayout:

CardLayout is used to manage multiple components as "cards" where only one card is
visible at a time.
Useful for creating panels that display different content based on user actions.

7.GroupLayout:

GroupLayout is a more sophisticated layout manager that allows you to define


complex relationships between components.
Supports hierarchical grouping and alignment.
Using layout managers ensures that your GUI components are positioned correctly
across different platforms and screen resolutions. Layout managers adapt to changes
in component sizes and available space, providing a consistent user experience.

Here's a simple example using the FlowLayout and GridLayout layout managers:

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

public class LayoutManagerExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Layout Manager Example");
frame.setLayout(new FlowLayout()); // Use FlowLayout for the frame
JPanel panel = new JPanel(new GridLayout(2, 2)); // Use GridLayout for the
panel

for (int i = 1; i <= 4; i++) {


JButton button = new JButton("Button " + i);
panel.add(button);
}

frame.add(panel);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

In this example, we use the FlowLayout layout manager for the frame and the
GridLayout layout manager for the panel. This results in a layout where buttons are
arranged in a grid within the panel, and the panel itself is placed within the frame
using a flow layout.

GUI COMPONENTS:_

GUI Control Components

GUI control components are the primary elements of a graphical user


interface that enable interaction with the user. They are subclasses of
the Component class. The GUI control components for constructing menus
are derived from the abstract class MenuComponent.

The following three steps are essential in making use of a GUI control
component.

1. A GUI control component is created by calling the appropriate


constructor.
JButton guiComponent = new JButton ( "ON" );
2. The GUI control component is added to a container using a layout
manager. This involves invoking the overloaded method add() on a
container with the GUI control component as the argument.
guiFrame.add ( guiComponent );
3. Listeners are registered with the GUI component, so that they can
receive events when these occur. GUI components generate particular
events in response to user actions.
4. Button - has a textual label and is designed to invoke an action when
pushed.
5. Checkbox - has textual label that can be toggled on and off.
6. ComboBox - is a component that provides a pop-up menu of choices.
7. Label - is a component that displays a single line of read-only, non-
selectable text.
8. List - is a component that defines a scrollable list of text items.
9. Scrollbar - is a slider to denote a position or a value.
10. TextField - is a component that implements a single line of text.
11. TextArea - is a component that implements multiple lines of text.

Example:-Java program that includes various GUI components like buttons, text
fields, text areas, check boxes, radio buttons, and labels all within one graphical user
interface using Java Swing

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class GUIComponentsExample {


public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGUI());
}

private static void createAndShowGUI() {


JFrame frame = new JFrame("GUI Components Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());

// Labels
JLabel label = new JLabel("Label:");
frame.add(label);

// Text Field
JTextField textField = new JTextField(20);
frame.add(textField);

// Text Area
JTextArea textArea = new JTextArea(5, 20);
JScrollPane textAreaScrollPane = new JScrollPane(textArea);
frame.add(textAreaScrollPane);

// Buttons
JButton button = new JButton("Button");
frame.add(button);

// Check Box
JCheckBox checkBox = new JCheckBox("Check Box");
frame.add(checkBox);
// Radio Buttons
JRadioButton radioButton1 = new JRadioButton("Radio Button 1");
JRadioButton radioButton2 = new JRadioButton("Radio Button 2");
ButtonGroup radioGroup = new ButtonGroup();
radioGroup.add(radioButton1);
radioGroup.add(radioButton2);
frame.add(radioButton1);
frame.add(radioButton2);

// Action Listener for the Button


button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String inputText = textField.getText();
String areaText = textArea.getText();
String checkBoxStatus = checkBox.isSelected() ? "Checked" : "Unchecked";
String radioButtonStatus = radioButton1.isSelected() ? "Radio Button 1" :
"Radio Button 2";

JOptionPane.showMessageDialog(frame,
"Text Field: " + inputText + "\n" +
"Text Area: " + areaText + "\n" +
"Check Box: " + checkBoxStatus + "\n" +
"Radio Button: " + radioButtonStatus,
"Component Values",
JOptionPane.INFORMATION_MESSAGE);
}
});

frame.pack();
frame.setVisible(true);
}
}

Lists:
Lists are used to display a list of items from which users can select one or more items.
In Java Swing, the JList component is used to create lists. It allows you to display a
vertical list of items.

Scroll Bars:
Scroll bars are used to navigate through content that is larger than the visible area of a
component.
In Java Swing, the JScrollBar component provides vertical or horizontal scrolling for
other components like text areas or panels.

Sliders:
Sliders are used to select a value from a range by sliding a handle along a track.
In Java Swing, the JSlider component is used to create sliders. It's often used for
settings like volume control or numerical input.
Windows:
Windows in GUI applications represent individual application windows or dialog
boxes.
In Java Swing, the JFrame class is used to create windows. It provides the main
window container for GUI components.

Menus:
Menus provide a way to organize and present various commands and options to users.
In Java Swing, the JMenu class represents a menu, and JMenuItem represents items
within the menu. Menus are typically organized in a menu bar (JMenuBar).

Dialog Box:
A dialog box is a temporary window that appears to prompt the user for input or to
display information.
In Java Swing, the JOptionPane class is commonly used to create dialog boxes. It
provides static methods for creating standard dialog boxes like message, input,
confirmation, and more.

Example:-
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ExtendedGUIComponentsExample {


public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGUI());
}

private static void createAndShowGUI() {


JFrame frame = new JFrame("Extended GUI Components Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());

// Lists
String[] listItems = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"};
JList<String> list = new JList<>(listItems);
JScrollPane listScrollPane = new JScrollPane(list);
frame.add(listScrollPane, BorderLayout.WEST);

// Scroll Bar
JScrollBar scrollBar = new JScrollBar(JScrollBar.VERTICAL);
frame.add(scrollBar, BorderLayout.EAST);

// Sliders
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 50);
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(5);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
frame.add(slider, BorderLayout.SOUTH);

// Menus and Menu Bar


JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem openMenuItem = new JMenuItem("Open");
JMenuItem saveMenuItem = new JMenuItem("Save");
fileMenu.add(openMenuItem);
fileMenu.add(saveMenuItem);
menuBar.add(fileMenu);
frame.setJMenuBar(menuBar);

// Dialog Box
JButton showDialogButton = new JButton("Show Dialog");
frame.add(showDialogButton, BorderLayout.NORTH);

showDialogButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "This is a dialog box!",
"Dialog Box", JOptionPane.INFORMATION_MESSAGE);
}
});

frame.pack();
frame.setVisible(true);
}
}

Applet and its life cycle:-


There are five methods of an applet life cycle, and they are:

o init(): The init() method is the first method to run that initializes the applet. It
can be invoked only once at the time of initialization. The web browser creates
the initialized objects, i.e., the web browser (after checking the security
settings) runs the init() method within the applet.
o start(): The start() method contains the actual code of the applet and starts the
applet. It is invoked immediately after the init() method is invoked. Every time
the browser is loaded or refreshed, the start() method is invoked. It is also
invoked whenever the applet is maximized, restored, or moving from one tab
to another in the browser. It is in an inactive state until the init() method is
invoked.
o stop(): The stop() method stops the execution of the applet. The stop ()
method is invoked whenever the applet is stopped, minimized, or moving from
one tab to another in the browser, the stop() method is invoked. When we go
back to that page, the start() method is invoked again.
o destroy(): The destroy() method destroys the applet after its work is done. It is
invoked when the applet window is closed or when the tab containing the
webpage is closed. It removes the applet object from memory and is executed
only once. We cannot start the applet once it is destroyed.
o paint(): The paint() method belongs to the Graphics class in Java. It is used to
draw shapes like circle, square, trapezium, etc., in the applet. It is executed
after the start() method and when the browser or applet windows are resized.

Sequence of method execution when an applet is executed:

1. init()
2. start()
3. paint()

Sequence of method execution when an applet is executed:

1. stop()
2. destroy()
Flow of Applet Life Cycle:

Syntax of applet:-

class TestAppletLifeCycle extends Applet {


public void init() {
// initialized objects
}
public void start() {
// code to start the applet
}
public void paint(Graphics graphics) {
// draw the shapes
}
public void stop() {
// code to stop the applet
}
public void destroy() {
// code to destroy the applet
}
}

Here's a summarized sequence of the applet's life cycle:

 Init() method - Initialization tasks.


 Start() method - Starting animations and dynamic processes.
 Running and interacting with users.
 Stop() method - Pausing or halting ongoing processes.
 Destroy() method - Cleaning up resources and performing cleanup tasks.
 Termination() - Applet execution ends.

You might also like