0% found this document useful (0 votes)
19 views

Java Unit 1

Uploaded by

jrabhi300
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Java Unit 1

Uploaded by

jrabhi300
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 107

Unit 1

GUI programming
What is GUI?
● A GUI, or Graphical User Interface, is a type of user interface that allows people to
interact with a computer or device through visual elements like windows, icons, buttons,
and menus, rather than through text commands.
● For example, when you use a computer, clicking on icons, opening files by
double-clicking them, or navigating through a software application using menus and
buttons are all parts of a GUI.
● It makes it easier for users to operate software by providing a visual and intuitive way to
interact with the device.
Abstract Window Toolkit (AWT)
● AWT, or Abstract Window Toolkit, is a set of tools in the Java programming language
used to create graphical user interfaces (GUIs).
● It provides a way to build windows, buttons, text fields, and other components for Java
applications.
Problems with AWT
1. Heavyweight
2. Platform Dependency:
3. Limited Components
4. Less Flexibility (Look and Feel)
Introduction
● Swing is a part of Java's standard library for building graphical user interfaces (GUIs).
● It is built on top of AWT but offers more advanced and flexible components.
● Swing provides a richer set of GUI components, such as buttons, text fields, tables, trees,
and more, which are designed to look consistent across different operating systems.

History and Origin

● 1990s: In the mid-1990s, Sun Microsystems recognized the need for a modern,
platform-independent GUI toolkit for Java. They aimed to create a more sophisticated
GUI toolkit than the earlier AWT (Abstract Window Toolkit).
● 1997: Swing was introduced as part of the Java Foundation Classes (JFC) in
JDK 1.2 (Java 2). It provided a more flexible and customizable set of
components compared to AWT. Swing aimed to provide a consistent look and
feel across different platforms.
● Early 2000s: Swing became widely adopted by Java developers for building
desktop applications, as it offered a rich set of components and features.
Two Key Features of Swing
1. Pluggable Look and Feel

Swing's pluggable look and feel feature allows developers to change the appearance and
behavior of their application's GUI components without altering the application's code. This
means you can switch between different "skins" or styles for your application, making it
adaptable to various user preferences or system themes.

2. Lightweight Components

Swing components are lightweight, meaning they are written entirely in Java and do not rely
on native operating system components. This makes Swing components more flexible and
easier to manage, as they are not tied to the underlying platform's GUI system.
Advantages of Swing

1. Platform Independence: Swing components are implemented entirely in Java, making


Swing applications truly platform-independent.
2. Rich Set of Components: Swing provides a wide range of components like buttons,
labels, text fields, tables, trees, etc., allowing developers to create sophisticated GUIs.
3. Customizable Look and Feel: Swing supports pluggable look and feel, allowing
developers to customize the appearance of their applications to match the native look
and feel of the underlying operating system or create custom looks.
4. Event-Driven Programming Model: Swing follows an event-driven programming model,
making it easy to handle user interactions and create responsive applications.
5. Support for MVC Architecture: Swing components are designed to follow the
Model-View-Controller (MVC) design pattern, which promotes separation of concerns
and modular design.
Disadvantages of Swing
1. Performance: Swing applications can sometimes suffer from performance issues,
especially when dealing with large amounts of data or complex UIs.
2. Complexity: Swing has a steep learning curve, especially for beginners. Creating
complex GUIs with Swing requires understanding of various layout managers, event
handling, and threading issues.
3. Look and Feel Consistency: While Swing aims to provide a consistent look and feel
across platforms, achieving pixel-perfect consistency can be challenging, especially
when customizing the look and feel or when running on different operating systems.
Swing Components
Java Swing provides a rich set of GUI components that allow developers to create complex
and interactive user interfaces. Here is a list of commonly used Swing components:

Top-Level Containers

1. JFrame: A top-level window with a title and a border.


2. JDialog: A top-level window used for creating dialogs.
3. JApplet: A top-level container for applets (not commonly used today).
4. JWindow: A top-level window without borders or a title bar.
Basic Controls
1. JLabel: Displays a short string or an image icon.
2. JButton: A button that can trigger an action when clicked.
3. JCheckBox: A check box that can be selected or deselected.
4. JRadioButton: A radio button, typically used in a group to allow a single selection.
5. JToggleButton: A button that can be toggled on or off.
6. JTextField: A single-line text input field.
7. JPasswordField: A single-line text input field for password entry.
8. JTextArea: A multi-line text area for editing text.
9. JComboBox: A drop-down list that allows users to select one item from a list.
10. JList: A list of items from which the user can select one or more items.
Menus and Toolbars

1. JMenuBar: A menu bar to hold menus.


2. JMenu: A menu that can contain menu items.
3. JMenuItem: An item in a menu.
4. JCheckBoxMenuItem: A menu item that can be checked or unchecked.
5. JRadioButtonMenuItem: A menu item that can be selected as part of a group.
6. JToolBar: A component that groups several components, usually buttons with icons, into
a row or column.
Containers and Panels
1. JPanel: A generic container for grouping other components.
2. JScrollPane: Provides a scrollable view of another component.
3. JSplitPane: Divides two components and allows the user to resize the components
dynamically.
4. JTabbedPane: A container that allows multiple components to be displayed in tabbed
pages.
5. JLayeredPane: Provides a container that can be used to place components in layers,
stacking them.
6. JDesktopPane: Provides a container for JInternalFrame objects (used for creating
Multiple Document Interface (MDI) applications).
7. JInternalFrame: A frame that can be contained within a JDesktopPane.
Tables, Trees, and Lists

1. JTable: Displays data in a two-dimensional table format.


2. JTree: Displays a hierarchical tree of data.
3. JList: Displays a list of items.

Dialogs

1. JOptionPane: Provides standard dialog boxes such as message, confirm, and input
dialogs.
2. JFileChooser: A dialog that allows users to choose files or directories.
3. JColorChooser: A dialog that allows users to choose a color.
First Program
import javax.swing.JFrame;
public class Example1 {
public Example1() {
JFrame f=new JFrame("GUI");
f.setSize(300, 330);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(3);
f.setVisible(true);
}
public static void main(String[] args) {
new Example1();
}
}
Second Program
import javax.swing.JFrame;
public class Example2 extends JFrame {
public Example2() {
setTitle("Example 2");
setSize(300, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(3);
setVisible(true);
}

public static void main(String[] args) {


new Example2();

}
}
JLabel and ImageIcon

● JLabel can be used to display text and/or an icon. It is a passive component in that it
does not respond to user input.
● JLabel defines several constructors. Here are three of them:
○ JLabel(Icon icon)
○ JLabel(String str)
○ JLabel(String str, Icon icon, int align)
● The align argument specifies the horizontal alignment of the text and/or icon within
the dimensions of the label.
● It must be one of the following values:
○ LEFT, RIGHT, CENTER, LEADING, or TRAILING.
● The easiest way to obtain an icon is to use the ImageIcon class.
● ImageIcon implements Icon and encapsulates an image.
● Thus, an object of type ImageIcon can be passed as an argument to the Icon
parameter of JLabel’s constructor.
● There are several ways to provide the image, including reading it from a file or
downloading it from a URL.
● Here is the ImageIcon constructor used by the example in this section:
● ImageIcon(String filename)
● It obtains the image in the file named filename.
● The icon and text associated with the label can be obtained by the following methods:
● Icon getIcon( )
● String getText( )
● The icon and text associated with a label can be set by these methods:
● void setIcon(Icon icon)
● void setText(String str)
● Here, icon and str are the icon and text, respectively. Therefore, using setText( ) it is
possible to change the text inside a label during program execution.
import javax.swing.*;
class SwingDemo{
public SwingDemo(){
JFrame f=new JFrame("Swing Demo");
f.setSize(400,400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JLabel l=new JLabel("Swing is more powerful than AWT");


f.add(l);
f.setVisible(true);
}
public static void main(String []args){
new SwingDemo();
}
}
import javax.swing.*;
class JImageIconDemo{
public JImageIconDemo(){
JFrame f=new JFrame("Swing Demo");
f.setSize(400,400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon image1=new ImageIcon("images.jpg");
JLabel l=new JLabel(image1);
f.add(l);
f.setVisible(true);
}
public static void main(String []args){
new JImageIconDemo();
}
}
JTextField
● JTextField allows you to edit one line of text.

● It is derived from JTextComponent, which provides the basic functionality common to


Swing text components.

● Three of JTextField’s constructors are shown here:

○ JTextField(int cols)

○ JTextField(String str, int cols)

○ JTextField(String str)

● Here, str is the string to be initially presented, and cols is the number of columns in the
text field. If no string is specified, the text field is initially empty. If the number of columns
is not specified, the text field is sized to fit the specified string.

● To obtain the text currently in the text field, call getText( ).


JButton
● The JButton class provides the functionality of a push button.
● JButton allows an icon, a string, or both to be associated with the push button. Three
of its constructors are shown here:

○ JButton(Icon icon)

○ JButton(String str)

○ JButton(String str, Icon icon)

● Here, str and icon are the string and icon used for the button.

● When the button is pressed, an ActionEvent is generated.


JToggleButton
● A useful variation on the push button is called a toggle button.

● A toggle button looks just like a push button, but it acts differently because it has two
states: pushed and released.

● JToggleButton(String str)
● Like JButton, JToggleButton generates an action event each time it is pressed. Unlike
JButton, however, JToggleButton also generates an item event.
● The easiest way to determine a toggle button’s state is by calling the isSelected( )
method on the button that generated the event. It is shown here:
● boolean isSelected( )
● It returns true if the button is selected and false otherwise.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JToggleButtonDemo {
public JToggleButtonDemo(){
JFrame frame = new JFrame(“JToggleButton Demo");
frame.setSize(200, 200);

frame.setLayout(new FlowLayout());
JLabel l1=new JLabel("Button is off");
JToggleButton jtbtn=new JToggleButton("on/off");
jtbtn.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if( jtbtn.isSelected()){
l1.setText("button is on");
}else{
l1.setText("button is off");
}
}
});
frame.add( jtbtn);
frame.add(l1);
frame.setVisible(true);
}
public static void main(String[] args) {
new JToggleButtonDemo();
}
}
Check Boxes
● The JCheckBox class provides the functionality of a check box.
● JCheckBox defines several constructors. The one used here is

● JCheckBox(String str)

● It creates a check box that has the text specified by str as a label.

● When the user selects or deselects a check box, an ItemEvent is generated. You can
obtain a reference to the JCheckBox that generated the event by calling getItem( ) on
the ItemEvent passed to the itemStateChanged( ) method defined by ItemListener.

● The easiest way to determine the selected state of a check box is to call isSelected( ) on
the JCheckBox instance.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JCheckBoxDemo2 implements ItemListener {

JCheckBox c1, c2;


JLabel status;

public JCheckBoxDemo2() {
JFrame frame = new JFrame("Checkbox Demo");
frame.setLayout(new GridLayout(2, 1));
frame.setSize(600, 400);
JPanel p = new JPanel(new FlowLayout());
JPanel p1 = new JPanel(new FlowLayout());
c1 = new JCheckBox("singing");
c2 = new JCheckBox("dancing");

JLabel hobbies = new JLabel("Hobbies");


status = new JLabel();
c1.addItemListener(this);
c2.addItemListener(this);
p.add(hobbies);
p.add(c1);
p.add(c2);
p1.add(status);
frame.add(p);
frame.add(p1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void itemStateChanged(ItemEvent ie) {
String singing = "", dancing = "";
if (c1.isSelected()) {
singing = c1.getText();
}
if (c2.isSelected()) {
dancing = c2.getText();
status.setText("Your Hobbies :::" + singing + " " + dancing);
}
public static void main(String[] args) {
new JCheckBoxDemo2();
}
}
Radio Buttons
● Radio buttons are a group of mutually exclusive buttons, in which only one button can be
selected at any one time. They are supported by the JRadioButton class, which extends
JToggleButton. JRadioButton provides several constructors.
● JRadioButton(String str)
● Here, str is the label for the button. Other constructors let you specify the initial selection
state of the button and specify an icon.
● In order for their mutually exclusive nature to be activated, radio buttons must be
configured into a group.
● Only one of the buttons in the group can be selected at any time. For example, if a user
presses a radio button that is in a group, any previously selected button in that group is
automatically deselected.
● A button group is created by the ButtonGroup class. Its default constructor is invoked for
this purpose. Elements are then added to the button group via the following method:
● void add(AbstractButton ab)
● A JRadioButton generates action events, item events, and change events each time
the button selection changes.

● Most often, it is the action event that is handled, which means that you will normally
implement the ActionListener interface.
JComboBox
● Swing provides a combo box (a combination of a text field and a drop-down list)
through the JComboBox class.
● A combo box normally displays one entry, but it will also display a drop-down list that
allows a user to select a different entry.
● You can also create a combo box that lets the user enter a selection into the text field.
● In the past, the items in a JComboBox were represented as Object references.
However, beginning with JDK 7, JComboBox was made generic and is now declared
like this: class JComboBox<E>
● Here, E represents the type of the items in the combo box. The JComboBox
constructor used by the example is shown here:
● JComboBox(E[ ] items)
● Here, items is an array that initializes the combo box.
● In addition to passing an array of items to be displayed in the drop-down list, items can be
dynamically added to the list of choices via the addItem( ) method, shown here:

● void addItem(E obj)

● JComboBox generates an action event when the user selects an item from the list.

● JComboBox also generates an item event when the state of selection changes, which
occurs when an item is selected or deselected.

● Thus, changing a selection means that two item events will occur: one for the deselected
item and another for the selected item.

● One way to obtain the item selected in the list is to call getSelectedItem( ) on the combo
box. It is shown here:

● Object getSelectedItem( )

● You will need to cast the returned value into the type of object stored in the list
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JComboBoxDemo extends JFrame{


JLabel jlab;
JComboBox<String> jcb;
String timepiece[]={"morning","Afternoon","evening","night"};
public JComboBoxDemo(){
setLayout(new FlowLayout());
jcb=new JComboBox<String>(timepiece);
add( jcb);
JLabel jlab=new JLabel("Choose time");
add( jlab);
jcb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String s=(String)jcb.getSelectedItem();
jlab.setText("Your selection: "+s);
}
});
setSize(200,200);
setVisible(true);
}
public static void main(String[] args) {
new JComboBoxDemo();
}
JList
● In Swing, the basic list class is called JList.
● It supports the selection of one or more items from a list.
● However, beginning with JDK 7, JList was made generic and is now declared like this:
○ class JList<E>
● JList provides several constructors. The one used here is
○ JList(E[ ] items)
● Although a JList will work properly by itself, most of the time you will wrap a JList inside a
JScrollPane.
● This way, long lists will automatically be scrollable, which simplifies GUI design.
● A JList generates a ListSelectionEvent when the user makes or changes a selection.
● This event is also generated when the user deselects an item. It is handled by
implementing ListSelectionListener.
● This listener specifies only one method, called valueChanged( ), which is shown here:
● void valueChanged(ListSelectionEvent le)
● Both ListSelectionEvent and ListSelectionListener are packaged in javax.swing.event.
● By default, a JList allows the user to select multiple ranges of items within the list, but
you can change this behavior by calling setSelectionMode( ), which is defined by JList.
It is shown here:
● void setSelectionMode(int mode)
● Here, mode specifies the selection mode. It must be one of these values defined by
ListSelectionModel: SINGLE_SELECTION SINGLE_INTERVAL_SELECTION
MULTIPLE_INTERVAL_SELECTION
● Of course, a single item can be selected in the other two modes, too. It’s just that they
also allow a range to be selected.
● You can obtain the index of the first item selected, which will also be the index of the
only selected item when using single-selection mode, by calling getSelectedIndex( ),
shown here:
● int getSelectedIndex( )
● Indexing begins at zero. So, if the first item is selected, this method will return 0.
● If no item is selected, –1 is returned. Instead of obtaining the index of a selection, you
can obtain the value associated with the selection by calling getSelectedValue( ):
● E getSelectedValue( )
● It returns a reference to the first selected value. If no value has been selected, it returns
null.
import java.awt.event.*;
Import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;

public class JListDemo {


JList<String> jlist;
JLabel city;
JScrollPane jspane;
public JListDemo() {
JFrame frame = new JFrame();
frame.setSize(200, 200);
frame.setLayout(new FlowLayout());
String cities[] = {"New York", "Chicago", "Houston", "Paris", "LA", "kathmandu", "New Delhi"};
jlist=new JList<>(cities);
jlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jspane=new JScrollPane( jlist);
jspane.setPreferredSize(new Dimension(120,90));
city=new JLabel("Choose a city");
jlist.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
int idx=jlist.getSelectedIndex();
if(idx!=-1){
city.setText("Current Selection:"+cities[idx]);
}else{
city.setText("Choose a city");
}
}
});
frame.add( jspane);
frame.add(city);
frame.setVisible(true);
}
public static void main(String[] args) {
Using paint() in Swing
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JFrame;
public class Demo extends JFrame{
public Demo() {
setSize(300, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(3);
setVisible(true);
getContentPane().setBackground(Color.CYAN);
}
public void paint(Graphics g) {
super.paint(g);
g.drawString("Universal", 80, 80);
g.setColor(Color.red);
g.setFont(new Font("Arial", Font.ITALIC, 18));
g.drawString("Hello World",50,50);
}
public static void main(String[] args) {
new Demo();

}
Layout Managers
● Layout managers in Java are used to control the size and position of components within
a container.
● They provide a level of abstraction over the manual positioning and sizing of
components, allowing developers to create complex and dynamic user interfaces
without having to deal with pixel-level details.
● Types
○ FlowLayout Manager
○ GridLayout Manager
○ BorderLayout Manager
○ CardLayout Manager
○ GridBagLayout Manager
FlowLayout

● Arranges components in a left-to-right flow, much like lines of text in a paragraph. When
one line is full, it moves to the next line.
● It is used for simple dialogs and panels where components should be laid out in a row.

JPanel panel = new JPanel();

panel.setLayout(new FlowLayout());
BorderLayout
● Divides the container into five regions: North, South, East, West, and Center. Each
region can contain only one component.

JFrame frame = new JFrame();

frame.setLayout(new BorderLayout());

frame.add(new JButton("North"), BorderLayout.NORTH);

frame.add(new JButton("South"), BorderLayout.SOUTH);

frame.add(new JButton("East"), BorderLayout.EAST);

frame.add(new JButton("West"), BorderLayout.WEST);

frame.add(new JButton("Center"), BorderLayout.CENTER);


GridLayout
● Description: Arranges components in a grid of cells, with each cell having the same
size.

JPanel panel = new JPanel(); panel.setLayout(new GridLayout(2, 3));


// 2 rows, 3 columns
GridBagLayout

● A flexible and complex layout manager that aligns components vertically and
horizontally, without requiring that the components be of the same size.
● It is used in complex forms and applications where components need to span multiple
rows or columns.

JPanel panel = new JPanel();

panel.setLayout(new GridBagLayout());

GridBagConstraints gbc = new GridBagConstraints();

// Add components to the panel using gbc to specify constraints


package basic;
import javax.swing.*;
import java.awt.*;
public class GridBagDemo {
public GridBagDemo() {
JFrame f = new JFrame("GridBagLayout Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400, 300);
// Create a panel with GridBagLayout
JPanel p1 = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
// First button
JButton button1 = new JButton("Button 1");
gbc.gridx = 0; // Column 0
gbc.gridy = 0; // Row 0
p1.add(button1, gbc);
// Second button
JButton button2 = new JButton("Button 2");
gbc.gridx = 1; // Column 1
gbc.gridy = 1; // Row 1
p1.add(button2, gbc);
// Third button
JButton button3 = new JButton("Button 3");
gbc.gridx = 2; // Column 2
gbc.gridy = 2; // Row 2
p1.add(button3, gbc);
// Fourth button
JButton button4 = new JButton("Button 4");
gbc.gridx = 3; // Column 3
gbc.gridy = 3; // Row 3
p1.add(button4, gbc);
// Add the panel to the frame
f.add(p1);
// Display the window
f.setVisible(true);
}
public static void main(String[] args) {
new GridBagDemo();
}
}
CardLayout
● Description: Manages components in a stack, where only one component is visible at
a time.
● Use Case: Wizards, tabbed panes, or any UI where different views are needed in the
same space.

JPanel panel = new JPanel();

panel.setLayout(new CardLayout());
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class CardLayoutDemo {

public CardLayoutDemo() {
JFrame f = new JFrame("CardLayout Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400, 300);

// Create the panel that uses CardLayout


JPanel p1 = new JPanel(new CardLayout());

// Create two cards


JPanel card1 = new JPanel();
card1.add(new JLabel("This is the first card"));
card1.setBackground(Color.CYAN);

JPanel card2 = new JPanel();


card2.add(new JLabel("This is the second card"));
card2.setBackground(Color.PINK);

// Add the cards to the card panel


p1.add(card1, "Card1");
p1.add(card2, "Card2");

// Create buttons to switch between cards


JButton showCard1Button = new JButton("Show Card 1");
showCard1Button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout) (p1.getLayout());
cl.show(p1, "Card1");
}
});
JButton showCard2Button = new JButton("Show Card 2");
showCard2Button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout) (p1.getLayout());
cl.show(p1, "Card2");
}
});

// Create a panel for the buttons


JPanel buttonPanel = new JPanel();
buttonPanel.add(showCard1Button);
buttonPanel.add(showCard2Button);
// Add the card panel and button panel to the frame
f.setLayout(new BorderLayout());
f.add(p1, BorderLayout.CENTER);
f.add(buttonPanel, BorderLayout.SOUTH);

// Display the window


f.setVisible(true);
}

public static void main(String[] args) {


new CardLayoutDemo();
}
}
Menu and MenuBar
package basic;
import java.awt.event.*;
import javax.swing.*;
public class MenuDemo {
public MenuDemo() {
JFrame f=new JFrame("Menu Demo");

JMenuBar mb=new JMenuBar();


JMenu m1=new JMenu("Menu 1");
JMenu m2=new JMenu("Menu 2");

JMenuItem item1=new JMenuItem("Item1");


JMenuItem item2=new JMenuItem("Item2");
JMenuItem item3=new JMenuItem("Item3");
JMenuItem item4=new JMenuItem("Item4");
m1.add(item1);
m1.add(item2);

m2.add(item3);
m2.add(item4);

mb.add(m1);
mb.add(m2);

f.setJMenuBar(mb);

item1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Hello");

}
});
f.setSize(300, 330);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(3);
f.setVisible(true);
}
public static void main(String[] args) {
new MenuDemo();
}
}
Two Event Handling Mechanisms
● The way in which events are handled changed significantly between the original version
of Java (1.0) and all subsequent versions of Java, beginning with version 1.1.
● Although the 1.0 method of event handling is still supported, it is not recommended for
new programs.
● Also, many of the methods that support the old 1.0 event model have been deprecated.
● The modern approach is the way that events should be handled by all new programs
The Delegation Event Model
● The modern approach to handling events is based on the delegation event model, which
defines standard and consistent mechanisms to generate and process events.
● Its concept is quite simple: a source generates an event and sends it to one or more
listeners.
● In this scheme, the listener simply waits until it receives an event. Once an event is
received, the listener processes the event and then returns.
● The advantage of this design is that the application logic that processes events is cleanly
separated from the user interface logic that generates those events.
● In the delegation event model, listeners must register with a source in order to receive
an event notification.
● This provides an important benefit: notifications are sent only to listeners that want to
receive them.
Events
● An event is an object that describes a state change in a source.
● An event can be generated as a consequence of a person interacting with
the elements in a graphical user interface.
● Some of the activities that cause events to be generated are pressing a
button, entering a character via the keyboard, selecting an item in a list, and
clicking the mouse.
● Events may also occur that are not directly caused by interactions with a
user interface.
● For example, an event may be generated when a timer expires, a counter
exceeds a value, software or hardware failure occurs, or an operation is
completed.
Event Sources
● A source is an object that generates an event. This occurs when the internal state of that object
changes in some way.
● Sources may generate more than one type of event.
● A source must register listeners in order for the listeners to receive notifications about a specific
type of event.
● Each type of event has its own registration method.
● Here is the general form:
● public void addTypeListener (TypeListener el )
● For example, the method that registers a keyboard event listener is called addKeyListener( ).
The method that registers a mouse motion listener is called addMouseMotionListener( ).
● When an event occurs, all registered listeners are notified and receive a copy of the
event object.
● A source must also provide a method that allows a listener to unregister an interest in a
specific type of event. The general form of such a method is this:
● public void removeTypeListener(TypeListener el )
● Here, Type is the name of the event, and el is a reference to the event listener.
● For example, to remove a keyboard listener, you would call removeKeyListener( ).
Event Listeners
•A listener is an object that is notified when an event occurs. It has two major requirements.
•First, it must have been registered with one or more sources to receive notifications about specific
types of events.
•Second, it must implement methods to receive and process these notifications.
•The methods that receive and process events are defined in a set of interfaces, such as those
found in java.awt.event.
•For example, the MouseMotionListener interface defines two methods to receive notifications when
the mouse is dragged or moved.
•Any object may receive and process one or both of these events if it provides an implementation of
this interface.
Event Classes
● The classes that represent events are at the core of Java’s event handling
mechanism.
● Thus, a discussion of event handling must begin with the event classes.
● The most widely used events at the time of this writing are those defined by
the AWT and those defined by Swing.
The KeyEvent Class
● A KeyEvent is generated when keyboard input occurs.
● There are three types of key events, which are identified by these integer constants:
○ KEY_PRESSED, KEY_RELEASED, and KEY_TYPED.
● The first two events are generated when any key is pressed or released.
● The last event occurs only when a character is generated.
● Remember, not all keypresses result in characters. For example, pressing shift does not
generate a character.
● There are many other integer constants that are defined by KeyEvent.
● For example, VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents of the
numbers and letters.
● The KeyEvent class defines several methods, but probably the most commonly used
ones are getKeyChar( ), which returns the character that was entered, and getKeyCode(
), which returns the key code. Their general forms are shown here:
○ char getKeyChar( )
○ int getKeyCode( )
● If no valid character is available, then getKeyChar( ) returns CHAR_UNDEFINED. When a
KEY_TYPED event occurs, getKeyCode( ) returns VK_UNDEFINED.
Example
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class Keyboard {

public Keyboard() {
Frame f = new Frame("Key Event");

TextField t1 = new TextField(10);


Label l1 = new Label(" ");
f.setLayout(new FlowLayout());
t1.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {

}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent ke) {
if (ke.getKeyCode()==KeyEvent.VK_ENTER) {
l1.setText(t1.getText());
}
}
});
f.add(t1);
f.add(l1);
f.setSize(300, 300);
f.setLocationRelativeTo(null);
f.setVisible(true);
}

public static void main(String[] args) {


new Keyboard();
}

}
The MouseEvent Class
•There are eight types of mouse events. The MouseEvent class defines the following integer
constants that can be used to identify them:
MOUSE_CLICKED The user clicked the mouse.
MOUSE_DRAGGED The user dragged the mouse.
MOUSE_ENTERED The mouse entered a component.
MOUSE_EXITED The mouse exited from a component.
MOUSE_MOVED The mouse moved.
MOUSE_PRESSED The mouse was pressed.
MOUSE_RELEASED The mouse was released.
MOUSE_WHEEL The mouse wheel was moved.
● Two commonly used methods in this class are getX( ) and getY( ).
● These return the X and Y coordinates of the mouse within the component when the
event occurred.
● Their forms are shown here:
● int getX( )
● int getY( )
● Alternatively, you can use the getPoint( ) method to obtain the coordinates of the mouse.
It is shown here:
● Point getPoint( )
● It returns a Point object that contains the X,Y coordinates in its integer members: x and y.
● The translatePoint( ) method changes the location of the event. Its form is shown here:
● void translatePoint(int x, int y)
● Here, the arguments x and y are added to the coordinates of the event.
● The getClickCount( ) method obtains the number of mouse clicks for this event. Its
signature is shown here:
● int getClickCount( )
● The isPopupTrigger( ) method tests if this event causes a pop-up menu to appear on this
platform. Its form is shown here:
● –boolean isPopupTrigger( )
● Also available is the getButton( ) method, shown here:
● int getButton( )
● It returns a value that represents the button that caused the event. For most cases, the
return value will be one of these constants defined by MouseEvent:
● NOBUTTON BUTTON1 BUTTON2 BUTTON3
Event Listener Interfaces
● As explained, the delegation event model has two parts: sources and listeners.
● Listeners are created by implementing one or more of the interfaces defined by the
java.awt.event package.
● When an event occurs, the event source invokes the appropriate method defined by the
listener and provides an event object as its argument.
● Table below lists several commonly used listener interfaces and provides a brief
description of the methods that they define.
● The following sections examine the specific methods that are contained in each
interface.
The ActionListener Interface
● The listener interface for receiving action events.
● The class that is interested in processing an action event implements this interface, and
the object created with that class is registered with a component, using the component's
addActionListener method.
● When the action event occurs, that object's actionPerformed method is invoked.
● This interface defines the actionPerformed( ) method that is invoked when an action
event occurs. Its general form is shown here:
● void actionPerformed(ActionEvent ae)
The KeyListener Interface
● The listener interface for receiving keyboard events (keystrokes).
● The class that is interested in processing a keyboard event either implements this
interface (and all the methods it contains) or extends the abstract KeyAdapter class
(overriding only the methods of interest).
● This interface defines three methods. The keyPressed( ) and keyReleased( ) methods
are invoked when a key is pressed and released, respectively. The keyTyped( ) method
is invoked when a character has been entered.
● For example, if a user presses and releases the a key, three events are generated in
sequence: key pressed, typed, and released.
•If a user presses and releases the home key, two key events are
generated in sequence: key pressed and released. The general
forms of these methods are shown here:
–void keyPressed(KeyEvent ke)
–void keyReleased(KeyEvent ke)
–void keyTyped(KeyEvent ke)

The MouseListener Interface

● The listener interface for receiving "interesting" mouse events (press, release, click, enter,
and exit) on a component. (To track mouse moves and mouse drags, use the
MouseMotionListener.)
● The class that is interested in processing a mouse event either implements this interface
(and all the methods it contains) or extends the abstract MouseAdapter class (overriding
only the methods of interest).
● This interface defines five methods.
● If the mouse is pressed and released at the same point, mouseClicked( ) is invoked.
● When the mouse enters a component, the mouseEntered( ) method is called.
● When it leaves, mouseExited( ) is called.
● The mousePressed( ) and mouseReleased( ) methods are invoked when the mouse is
pressed and released, respectively. The general forms of these methods are shown
here:
● void mouseClicked(MouseEvent me)
● void mouseEntered(MouseEvent me)
● void mouseExited(MouseEvent me)
● void mousePressed(MouseEvent me)
● void mouseReleased(MouseEvent me)
The MouseMotionListener Interface
● The Java MouseMotionListener is notified whenever you move or drag mouse. It is
notified against MouseEvent.
● The MouseMotionListener interface is found in java.awt.event package. It has two
methods.
● void mouseDragged(MouseEvent e);
● void mouseMoved(MouseEvent e);
The MouseWheelListener
● The listener interface for receiving mouse wheel events on a component.
● The class that is interested in processing a mouse wheel event implements this interface
● It has only one method
● void mouseWheelMoved(MouseWheelEvent e)
The WindowListener Interface
● The listener interface for receiving window events.
● The class that is interested in processing a window event either implements this
interface (and all the methods it contains) or extends the abstract WindowAdapter class
(overriding only the methods of interest).
● This interface defines seven methods. The windowActivated( ) and
windowDeactivated( ) methods are invoked when a window is activated or deactivated,
respectively.
● If a window is iconified, the windowIconified( ) method is called.
● When a window is deiconified, the windowDeiconified( ) method is called. When a
window is opened or closed, the windowOpened( ) or windowClosed( ) methods are
called, respectively. The windowClosing( ) method is called when a window is being
closed.
•The general forms of these methods are
–void windowActivated(WindowEvent we)
–void windowClosed(WindowEvent we)
–void windowClosing(WindowEvent we)
–void windowDeactivated(WindowEvent we)
–void windowDeiconified(WindowEvent we)
–void windowIconified(WindowEvent we)
–void windowOpened(WindowEvent we)
The ItemListener Interface

● The listener interface for receiving item events. The class that is interested in processing
an item event implements this interface.
● void itemStateChanged(ItemEvent e)Invoked when an item has been selected or
deselected by the user.

The AdjustmentListener Interface

● The listener interface for receiving adjustment events.


● void adjustmentValueChanged(AdjustmentEvent e)Invoked when the value of the
adjustable has changed
Adapter Classes
● An adapter class provides an empty implementation of all methods in an event listener
interface.
● Adapter classes are useful when you want to receive and process only some of the
events that are handled by a particular event listener interface.
● You can define a new class to act as an event listener by extending one of the adapter
classes and implementing only those events in which you are interested.
● For example, the MouseMotionAdapter class has two methods, mouseDragged( ) and
mouseMoved( ), which are the methods defined by the MouseMotionListener interface. If
you were interested in only mouse drag events, then you could simply extend
MouseMotionAdapter and override mouseDragged( ). The empty implementation of
mouseMoved( ) would handle the mouse motion events for you.
import javax.swing;
import java.awt.event.*;

public class AdapterDemo {


public AdapterDemo(){
JFrame f=new JFrame("Adapter demo");
f.setSize(200,200);

JTextField tf=new JTextField();


tf.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e){
System.out.println("hello");
}
});
f.add(tf);
f.setVisible(true);
}
public static void main(String[] args) {
new AdapterDemo();
}
}
Swing and the MVC Design Pattern

Java Swing is a part of Java Foundation Classes (JFC) used to create


window-based applications. Swing provides a set of 'lightweight' (all-Java language)
components that, to the maximum degree possible, work the same on all platforms.

The Model-View-Controller (MVC) design pattern is a way to separate concerns in


application development, which makes the code more modular and easier to
maintain. The MVC pattern divides an application into three interconnected
components:

● Model: Manages the data and business logic.


● View: Displays the data (the UI).
● Controller: Handles the input and updates the Model and View accordingly.
How Swing Implements MVC
Swing components, like JButton, JTextField, JTable, etc., are designed using
the MVC pattern. Each Swing component has:

● A Model: Represents the state of the component.


● A View: Responsible for rendering the component on the screen.
● A Controller: Manages the user interactions.

For example, a JButton:

● Model: ButtonModel (holds the state of the button, like whether it is pressed,
enabled, etc.).
● View: The actual button that is drawn on the screen.
● Controller: ActionListener (handles the action events when the button is
pressed).
Example: MVC in a Swing Application
1. The Model
public class CounterModel {
private int count;
public int getCount() {
return count;
}
public void incrementCount() {
count++;
}
}
2. The View
import javax.swing.*;
import java.awt.*;
public class CounterView extends JFrame {
private JButton incrementButton;
private JLabel countLabel;

public CounterView() {
incrementButton = new JButton("Increment");
countLabel = new JLabel("Count: 0");
this.setLayout(new FlowLayout());
this.add(countLabel);
this.add(incrementButton);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(200, 100);
}
public void setCount(int count) {
countLabel.setText("Count: " + count);
}

public JButton getIncrementButton() {


return incrementButton;
}
}
3. The Controller
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CounterController {


private CounterModel model;
private CounterView view;
public CounterController(CounterModel model, CounterView view) {
this.model = model;
this.view = view;
this.view.getIncrementButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
model.incrementCount();
view.setCount(model.getCount());
}
});
}
}
4. Putting It All Together

public class MVCDemo {

public static void main(String[] args) {

CounterModel model = new CounterModel();

CounterView view = new CounterView();

CounterController controller = new CounterController(model, view);

view.setVisible(true);

}
Explanation

1. Model (CounterModel):
○ Manages the state of the counter.
○ Provides methods to get the current count and increment the count.
2. View (CounterView):
○ Manages the UI components (JButton and JLabel).
○ Provides methods to update the count label and access the increment button.
3. Controller (CounterController):
○ Connects the Model and the View.
○ Updates the Model when the button is clicked and refreshes the View to reflect the new
state.
4. Main (MVCDemo):
○ Creates instances of the Model, View, and Controller.
○ Makes the View visible.

You might also like