UNIT 5 GUI
UNIT 5 GUI
UNIT 5 GUI
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.
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)`
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.*;
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.
import javax.swing.*;
// Create a panel
JPanel panel = new JPanel();
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.
1.FlowLayout:
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:
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:
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:
Here's a simple example using the FlowLayout and GridLayout layout managers:
import javax.swing.*;
import java.awt.*;
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:_
The following three steps are essential in making use of a GUI control
component.
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;
// 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);
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;
// 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);
// 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);
}
}
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.
1. init()
2. start()
3. paint()
1. stop()
2. destroy()
Flow of Applet Life Cycle:
Syntax of applet:-