Unit 3 - GUI Components II - Swing - Components
Unit 3 - GUI Components II - Swing - Components
Unit III
GUI Components – II
Swing Components
Graphical User Interfaces
• Designing graphical application is an excellent example of the use of inheritance,
abstract classes, and interfaces.
• Every program that presents a Swing GUI contains at least one top-level Swing
CONTAINER. For most programs, the top-level Swing containers are instances
of JFrame, JDialog, or (for applets) JApplet. Each JFrame object implements a single main
window, and each JDialog implements a secondary window, usually a temporary
window to receive an additional information from the user (JOptionPane is an
example of JDialog).
Continued…
• Each JApplet object implements an applet's display area within a browser
window. A top-level Swing container provides the support for painting and event
handling.
• In addition to this there are the HELPER classes, like Font, Color, Graphics and
more.
JButton
• The JButton class is used to create a labelled button that has platform
independent implementation.
• A button is a component the user clicks to trigger a specific action.
• A Java application can use several types of buttons, including command buttons,
check boxes, toggle buttons and radio buttons.
• Following Figure shows the inheritance hierarchy of the Swing buttons we cover
in this chapter. As you can see, all the button types are subclasses of
AbstractButton (package javax.swing), which declares the common features of
Swing buttons. In this section, we concentrate on buttons that are typically used
to initiate a command.
Constructor Description
JFrame(String title, It creates a JFrame with the specified title and the
GraphicsConfiguration gc) specified GraphicsConfiguration of a screen device.
Useful Methods
Modifier and Type Method Description
Constructor Description
• The application may use multiple-selection lists to copy items from one JList to
another. One list is a MULTIPLE_INTERVAL_SELECTION list and the other is a
SINGLE_INTERVAL_SELECTION list. When you execute the application, try using
the selection techniques described previously to select items in both lists.
Events
• Events are objects that encapsulate changes in state that are initiated by
the user. Generally, the user triggers events by pressing and releasing keys
on the keyboards…………
• The AWT API includes the package java.awt.event in which you will find
the classes from this API that encapsulate the events that relate to the GUI
components in your application or applet. All classes in this package that
define events are the subclasses of the class java.awt.event.AWTEvent
which is a subclass of java.util.EventObject. EventObject is the superclass
of all Java platform classes that define events, whether they are GUI events
or not.
• The Swing API separates its event related classes into a package called
javax.swing.event. It is worth noting that most Swing event classes are
direct subclasses of EventObject, not AWTEvent.
Java Event classes and Listener interfaces
• The java.awt.event package provides many event classes and Listener
interfaces for event handling.
Event Classes Listener Interfaces
ActionEvent ActionListener
MouseEvent MouseListener and MouseMotionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
• Following steps are required to perform event handling:
1. Register the component with the Listener:
Registration Methods: 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){}
Java Event Handling Code
• We can put the event handling code into one of the following places:
• Within class
• Other class
• Anonymous class
1) Java event handling by implementing ActionListener
• Program: AEvent.java
2) Java event handling by outer class
• Program AEvent2.java
3) Java event handling by anonymous class
• Program AEvent3.java
ItemListener and ActionListener
• Different GUI components have different events associated with it (
more or less and/or same or different , than/compared with other
GUI components). ItemListener and ActionListener are interfaces, and
when you invoke “add____Listener“ , it require you to pass along
appropriate interface (based on event applicable to GUI component).
• ItemListener is for drop downs or lists , and ActionListener is for
Actions (like clicking , although there is MouseListenter interface for
mouse events like mouse press/release/click/etc).
• An ItemEvent is fired even when the user deselects a check box by
selecting another JCheckBox (when in a ButtonGroup), however
ActionEvent is not generated like that instead ActionEvent only listens
whether an action is performed on the JCheckBox (to which the
ActionListener is registered only) or not. It does not know about
ButtonGroup and all other selection/deselection stuff.
• ItemListeners are notified whenever the state of the button is changed,
whether through a user interacting with the button or programmatically
(via the setSelected method). ActionListeners on the other hand will be
called when a user interacts with the button (but can be simulated
programmatically via the onClick method).
• Note that a user interacting with the button such as clicking or hitting the
space bar will also change the state of the button and raise an item event
as well as an action event. Generally, you will want to define either one or
the other, don't listen for both action events and item events on the
button.
Event-listener interface and an event-adapter class
• What is the relationship between an event-listener interface and an event-
adapter class?
An event-listener interface allows describing the methods which must be
implemented by one of the event handler for a specific event.
An event-adapter allows default implementations of an event-listener interface of a
specific event.
• What is the relationship between an event-listener interface and an event-
adapter class?
If an event listener is implemented directly by a class, all the methods within that
interface need to be implemented making the code unnecessarily large.
This issue can be solved using the adapter class.
To use an adapter, you create a subclass of it and override only the methods of
interest, rather than directly implementing all methods of the listener interface.
Agenda
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
java.awt.dnd Adapter classes
DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener
MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener
Java WindowAdapter Example
import java.awt.*;
import java.awt.event.*;
public class AdapterExample
{ Frame f;
AdapterExample()
{ f=new Frame("Window Adapter");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) { f.dispose(); }
});
f.setSize(400,400); f.setLayout(null); f.setVisible(true);
}
public static void main(String[] args)
{ new AdapterExample();
}
}
java MouseAdapter Example
import java.awt.*;
import java.awt.event.*;
public class MouseAdapterExample extends MouseAdapter
{ Frame f;
MouseAdapterExample()
{ f=new Frame("Mouse Adapter"); f.addMouseListener(this);
f.setSize(300,300); f.setLayout(null); f.setVisible(true);
}
public void mouseClicked(MouseEvent e)
{ Graphics g=f.getGraphics(); //The getGraphics() method of Component class returns the object of Graphics.
g.setColor(Color.BLUE); g.fillOval(e.getX(), e.getY(),30,30);
}
public static void main(String[] args)
{ new MouseAdapterExample();
}
}
Java MouseMotionAdapter Example
import java.awt.*;
import java.awt.event.*;
public class MouseMotionAdapterExample extends MouseMotionAdapter
{ Frame f;
MouseMotionAdapterExample()
{ f=new Frame("Mouse Motion Adapter"); f.addMouseMotionListener(this);
f.setSize(400,300); f.setLayout(null); f.setVisible(true);
}
public void mouseDragged(MouseEvent e)
{ Graphics g=f.getGraphics(); g.setColor(Color.ORANGE);
g.fillOval(e.getX(),e.getY(),20,20);
}
public static void main(String[] args)
{ new MouseMotionAdapterExample();
}
}
Agenda
• WindowAdapter
• MouseAdapter
• MouseMotionAdapter
• Java KeyAdapter Example
• Key Event Handling
• Java KeyListener interface
• Java KeyListener interface - Example1 (key pressed/released/typed)
• Java KeyListener interface – Example2 (Count words and characters)
• Layout managers
Java KeyAdapter Example
import java.awt.*;
import java.awt.event.*;
public class KeyAdapterExample extends KeyAdapter
{ Label l; TextArea area; Frame f;
KeyAdapterExample()
{ f=new Frame("Key Adapter"); l=new Label(); l.setBounds(20,50,200,20); area=new TextArea();
area.setBounds(20,80,300, 300); area.addKeyListener(this); f.add(l);f.add(area); f.setSize(400,400);
f.setLayout(null); f.setVisible(true);
}
public void keyReleased(KeyEvent e)
{ String text=area.getText(); String words[]=text.split("\\s");
l.setText("Words: "+words.length+" Characters:"+text.length());
}
public static void main(String[] args) //Program
{ new KeyAdapterExample();
}
}
Key Event Handling
• This section presents the KeyListener interface for handling key
events. Key events are generated when keys on the keyboard are
pressed and released. A class that implements KeyListener must
provide declarations for methods keyPressed, keyReleased and
keyTyped, each of which receives a KeyEvent as its argument. Class
KeyEvent is a subclass of InputEvent. Method keyPressed is called in
response to pressing any key. Method keyTyped is called in response
to pressing any key that is not an action key. (The action keys are any
arrow key, Home, End, Page Up, Page Down, any function key, Num
Lock, Print Screen, Scroll Lock, Caps Lock and Pause.) Method
keyReleased is called when the key is released after any keyPressed or
keyTyped event.
Java KeyListener Interface
• The Java KeyListener is notified whenever you change the state of key.
It is notified against KeyEvent. The KeyListener interface is found in
java.awt.event package. It has three methods.
• Methods of KeyListener interface
• The signature of 3 methods found in KeyListener interface are given
below:
• public abstract void keyPressed(KeyEvent e);
• public abstract void keyReleased(KeyEvent e);
• public abstract void keyTyped(KeyEvent e);
Java KeyListener Example
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements KeyListener
{ Label l; TextArea area;
KeyListenerExample()
{ l=new Label(); l.setBounds(20,50,100,20); area=new TextArea(); area.setBounds(20,80,300, 300);
area.addKeyListener(this); add(l);add(area); setSize(400,400); setLayout(null); setVisible(true);
}
public void keyPressed(KeyEvent e) { l.setText("Key Pressed"); }
public void keyReleased(KeyEvent e) { l.setText("Key Released"); }
public void keyTyped(KeyEvent e) { l.setText("Key Typed"); }
public static void main(String[] args) { new KeyListenerExample(); } //Program
}
KeyListener Example 2: Count Words & Characters
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample2 extends Frame implements KeyListener
{ Label l; TextArea area;
KeyListenerExample2()
{ l=new Label(); l.setBounds(20,50,200,20); area=new TextArea(); area.setBounds(20,80,300, 300);
area.addKeyListener(this); add(l);add(area); setSize(400,400); setLayout(null); setVisible(true);
}
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) //Program
{ String text=area.getText(); String words[]=text.split("\\s");
l.setText("Words: "+words.length+" Characters:"+text.length());
}
public void keyTyped(KeyEvent e) {}
public static void main(String[] args)
{ new KeyListenerExample2();
}
}
END
Next…
Layout Managers