0% found this document useful (0 votes)
27 views127 pages

Java - Mca 2021 - Unit 5

Uploaded by

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

Java - Mca 2021 - Unit 5

Uploaded by

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

Unit V

Event Handling: Delegation Event Model – Event Classes – Event Listener


Interfaces – Working with Graphics, Color and Font classes –
#Understanding Layout Managers# – The Origins of Swing – Key Swing
Features – The MVC Connection – Components and Containers – The Swing
Packages – A Simple Swing Application – Exploring Swing: JLabel and
ImageIcon – JTextField – Jbutton – JTabbedPane – JScrollPane –
JList – JComboBox.
Applet API is Deprecated

Java applets were deprecated in the 2017 release of Java 9 and


removed from Java SE 11, which was released in 2018.
As a result, JApplet is also removed.
Event Handling
 Procedural programming is executed in procedural order.
 In event-driven programming, code is executed upon activation of events.
 An event is an action that takes place within a program, generated by the user, such
as the clicking of a button, clicking the mouse or pressing keys.
 The mechanism to process events is called event handling
 (ie)Event handling is the way to capture the events and perform the actions
accordingly.
 Most commonly events are generated by mouse, keyboard, and various controls,
such as a push button
 Events are supported by a number of packages, including java.util, java.awt, and
java.awt.event
The Delegation Event Model
 Java uses delegation event model approach to handle events.
What is delegation event model?
 When an event is generated by the user on the component, component will delegate (hand over)
the event to the listener. The listener will delegate the event to one of its method. The method is
finally executed and the event is handled. This is called Event-Delegation-Model.
(ie) The delegation event model defines standard and consistent mechanisms to generate and process
events.
Principle:
 A source generates an event and sends it to one or more listeners.
 The listener waits until it receives an event.
 Once an event is received, the listener processes the event and then returns.
 In the delegation event model, listeners must register with a source in order to receive an event
notification.
 Event notifications are sent only to listeners that want to receive them.
The Delegation Event Model Action Events on Buttons
Event Object
ActionEvent

Event source Event listener Button ActionListener


(Event handling (actionPerformed(…))
methods)
The Delegation Event Model
Advantages:
 The application logic that processes events is cleanly separated from the user interface
logic that generates those events.
 A user interface element is able to “delegate” the processing of an event to a separate
piece of code.

The principal elements of event delegation model are:


1. Events
2. Event sources
3. Event Listeners
Events
 An event is an action that takes place within a program, such as the clicking of a button.
 In the delegation model, Event is an object that describes a state change in a source.
 When you press a button in your program the state of the button changes from
‘Unclicked’ to ‘Clicked’.
 This change in the state of our button is called an Event.
 An event in Java is an object that is created when something changes within a graphical
user interface.
 Example: If a user clicks on a button, clicks on a combo box, or types characters into a text
field, etc., then an event triggers, creating the relevant event object.
 Events are generally generated when a user interacts with the GUI.
Note: 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, a
software or hardware failure occurs, or an operation is completed.
Event sources
 An event source is an object which generates the event.
 Generation of event must cause a change in the state of the source.
 The event source is an object that is created when an event occurs.
 Some general Event Sources are Button, CheckBox, List, MenusItem, Window, TextItems
,Frame etc…
 A source may generate more than one type of event
 A source must register listeners in order to notify them about a specific type of event.
 Each type of event has its own registration method
public void addTypeListener(TypeListener el)
Here, Type is the name of the event, and el is a reference to the event listener.
i.e. addKeyListener(), addMouseMotionListener()
When an event occurs, all registered listeners are notified and receive a copy of the event
object (called multicasting)
Event sources
 Some sources allow only one listener to register (unicasting):
public void addTypeListener(TypeListener el)
throws java.util.TooManyListenersException
Here, Type is the name of the event, and el is a reference to the event listener. When such
an event occurs, the registered listener is notified. This is known as unicasting the
event.
 A source also allows a listener to unregister
public void removeTypeListener(TypeListener el)
i.e. removeKeyListener()
Sources of events
Button Generates action event when it is pressed

Checkbox Generates item events when the check box is selected or deselected
Choice Generates item events when the choice is changed

List 1. Action events when an item is double-clicked


2. Item events when an item is selected/deselected

Menu 1.Action events when a menu item is selected


Item 2.Item events when checkable menu item selected

Scrollbar Adjustment events when scroll bar is manipulated

Text box Text events when user enters a character

Window Window events when window is activated, closed, deactivated,


opened etc
Event Listeners
 The events generated by the GUI components are handled by a special group of interfaces
known as "listeners".
 Listener is a piece of code that is activated when a particular kind of event occurs
 Interfaces that handle user events are called event listeners.
 Event Listeners are the objects that get notified when an event occurs on an event source.
 ie)Event Listeners are also called as event handlers as they are responsible to handle events
occurring at the source.
Event Listener has two major requirements
1.It must have been registered with one or more sources to receive notifications about specific
types of events
2. It must implement methods to receive and process these notifications
 The methods that receive and process events are defined in a set of interfaces found in
java.awt. event.
 Every component has its own listener. For example, ActionListener handles the events of
Button, TextField, List and Menus. Listeners are from java.awt.event package.
Commonly used Event Listener Interfaces
ActionListener Defines one method to receive action events
AdjustmentListener One method to receive adjustment events
ComponentListener Four methods to recognize when a component is hidden,
moved, resized or shown
ContainerListener Two methods, added and removed
FocusListener Two methods, focusGained, focusLost
ItemListener One method, itemStateChanged
KeyListener Three methods, KeyPressed, KeyReleased, KeyTyped
MouseListener Five methods, mouseClicked, mouseEntered,
mouseExited, mousePressed, mouseReleased
MouseMotion Two methods, mouse is dragged or moved
Listener
TextListener One method, textChanged
WindowEvent Seven events, windowActivated, windowClosed,
windowClosing, windowDeactivated,
windowDeiconified, windowicinified, windowOpened
Event classes
 Almost every event source generates an event.
 An Event class is class that represents the event
 For every event, there is a predefined class in Java.
 For example, the event generated by button is known as ActionEvent and that of Checkbox is
known as ItemEvent.
 All the events are listed in java.awt.event package.
 Java defines several types of events defined by AWT and Swing classes
 EventObject (in java.util package) is the superclass for all events
 Its one constructor is shown here:
EventObject(Object src)
Here, src is the object that generates this event
 Its getSource() method returns the source of the event and toString() method returns the string
equivalent of the event
 AWTEvent (in java.awt package) is a subclass of EventObject and superclass of all AWT-based
events
 Its getID() method can be used to determine the type of the event
Main event classes in java.awt.event
Name of Event class Situation in which an Event object is created
ActionEvent Generated when a button is pressed, list item is double-
clicked, or a menu item is selected
Adjustment Event When a scroll bar is manipulated
ComponentEvent A component is hidden, moved, resized or become visible
ContainerEvent A component is added to or removed from a container

FocusEvent A component gains or loss keyboard focus


InputEvent Superclass of all input event classes
KeyEvent Input is received from the keyboard
MouseEvent Mouse is dragged, moved, clicked, released
ItemEvent A check box, list item is clicked or choice selection is made
TextEvent The value of a text area or text field is changed
WindowEvent Window is activated, closed, deactivated, opened or quit
SUMMARY:
TABLE :Events Generated by a GUI Component(Event Source), Event class, the Listener Interface,
and the Name of the Method of the Interface to Handle the Event

Event Event Class/ Listener Interface Listener Method


Source/GUI Event Nmae
component
JButtton ActionEvent ActionListener actionPerformed()
JCheckBox ItemEvent ItemListener itemStateChanged()
JChoice ItemEvent ItemListener itemStateChanged()
JComponent ComponentEvent ComponentListener componentHidden()
JComponent ComponentEvent ComponentListener componentMoved()
JComponent ComponentEvent ComponentListener componentResized()
JComponent ComponentEvent ComponentListener componentShown()
JComponent FocusEvent FocusListener focusGained()
JComponent FocusEvent FocusListener focusLost()
Container ContainerEvent ContainerListener componentAdded()
Container ContainerEvent ContainerListener componentRemoved()
Table cntd..
Event Source Event Class Listener Interface Listener Method

JList ActionEvent ActionListener actionPerformed()

JList ItemEvent ItemListener itemStateChanged()


JMenuItem ActionEvent ActionListener actionPerformed()
JScrollbar AdjustmentEvent AdjustmentListener adjustmentValueChanged()
JTextComponent TextEvent TextListener textValueChanged()
JTextField ActionEvent ActionListener actionPerformed()
Window WindowEvent WindowListener windowActivated()
Window WindowEvent WindowListener windowClosed()

Window WindowEvent WindowListener windowClosing()


Window WindowEvent WindowListener windowDeactivated()

Window WindowEvent WindowListener windowDeiconified()


Window WindowEvent WindowListener windowIconified()

Window WindowEvent WindowListener windowOpened


Events Generated by key and mouse Components
Even though hardware events like key board and mouse (low level events)are
not GUI components, they do generate events. The following table
summarizes the events generated by the key and mouse components.
Event Source Event Class Listener Interface Listener Method
key KeyEvent KeyListener keyPressed()
key KeyEvent KeyListener keyReleased()
key KeyEvent KeyListener keyTyped()
mouse MouseEvent MouseListener mouseClicked()
mouse MouseEvent MouseListener mouseEntered()
mouse MouseEvent MouseListener mouseExited()
mouse MouseEvent MouseListener mousePressed()
mouse MouseEvent MouseListener mouseReleased()
mouse MouseEvent MouseMotionListener mouseDragged()
mouse MouseEvent MouseMotionListener mouseMoved()
Using the Delegation Event Model
Writing event driven program is a two step process
1. Implement the appropriate interface in the listener so that it can receive the type of event
desired.
2. Implement code to register and unregister (if necessary) the listener as a recipient for the event
notifications.
 Remember that a source may generate several types of events. Each event must be registered
separately. Also, an object may register to receive several types of events, but it must implement
all of the interfaces that are required to receive these events.

Handling Mouse Events


• To handle mouse events, you must implement the MouseListener and the MouseMotionListener
interfaces.
//Example 1 mouse events
import java.awt.*; public void mouseReleased(MouseEvent e)
import java.awt.event.*; {setBackground(Color.green);

class MouseListenerExample extends Frame implements l.setText("Mouse Released");

MouseListener{ }
public void mouseEntered(MouseEvent e)
Label l;
{setBackground(Color.yellow);
MouseListenerExample(){
l.setText("Mouse Entered");
addMouseListener(this);
}
l=new Label();
public void mouseExited(MouseEvent e)
l.setBounds(20,50,100,20); { setBackground(Color.pink);
add(l); l.setText("Mouse Exited");
setSize(300,300); }
setLayout(null); }
setVisible(true); class MouseLis
} {

// override all the five abstract methods of MouseListener public static void main(String[] args) {
new MouseListenerExample();
public void mouseClicked(MouseEvent e)
// or
{ setBackground(Color.red);
// MouseListenerExample ml = new MouseListenerExample();
l.setText("Mouse Clicked");
}
}
}
public void mousePressed(MouseEvent e)
{ setBackground(Color.blue);
l.setText("Mouse Pressed"); F:\>javac MouseLis.java
}
F:\>java MouseLis

Ouput next slide


// Demonstrate the mouse event handlers.
import java.awt.*;
import java.awt.event.*;
class MouseMotionListenerExample extends Frame
implements MouseMotionListener{
MouseMotionListenerExample(){
addMouseMotionListener(this);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseDragged(MouseEvent e) {
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e) {}
}
class MouseMotion
{
public static void main(String[] args) {
new MouseMotionListenerExample();
}
}
Handling Keyboard Events
• To handle keyboard events, you use the same general architecture as that shown in the mouse event
example in the preceding section. The difference, of course, is that you will be implementing the
KeyListener interface.
• When a key is pressed, a KEY_PRESSED event is generated. This results in a call to the keyPressed( )
event handler.
• When the key is released, a KEY_RELEASED event is generated and the keyReleased( ) handler is
executed.
• If a character is generated by the keystroke, then a KEY_TYPED event is sent and the keyTyped( )
handler is invoked.
• Thus, each time the user presses a key, at least two and often three events are generated. If all you
care about are actual characters, then you can ignore the information passed by the key press and
release events.
• However, if your program needs to handle special keys, such as the arrow or function keys, then it
must watch for them through the keyPressed( ) handler.
import java.awt.*;
import java.awt.event.*; public void keyReleased(KeyEvent e) {
class KeyListenerExample extends Frame l.setText("Key Released");
implements KeyListener{ }
Label l; public void keyTyped(KeyEvent e) {
TextArea area; l.setText("Key Typed");
KeyListenerExample(){ } }

l=new Label(); class Keylist


l.setBounds(20,50,100,20); {
area=new TextArea(); public static void main(String[] args) {
area.setBounds(20,80,300, 300); new KeyListenerExample();
area.addKeyListener(this); }
}
add(l);add(area);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void keyPressed(KeyEvent e) {
l.setText("Key Pressed");
}
Adapter Classes

 When a listener includes many abstract methods to override, the coding becomes heavy to
the programmer.
 To avoid this heavy coding, the designers come with another group of classes known as
"adapters".
 Adapters are abstract classes defined in java.awt.event package.
 Adapters usage replaces the listeners; adapters make event handling easy to the
programmer.
 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( ). The signatures of these empty methods are exactly as defined in the
MouseMotionListener interface.
 If you were interested in only mouse drag events, then you could simply
extend MouseMotionAdapter and implement mouseDragged( ). The
empty implementation of mouseMoved( ) would handle the mouse
motion events for you.
 Every listener that has more than one abstract method has got a
corresponding adapter class.
Adapter Class Listener Interface
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListene
// Demonstrate an adaptor. public void mouseClicked(MouseEvent e) {
import java.awt.*; Graphics g=f.getGraphics();
import java.awt.event.*; g.setColor(Color.RED);
class MouseAdapterExample extends g.fillRect(e.getX(),e.getY(),30,30);
MouseAdapter{ }
Frame f; }
MouseAdapterExample(){ class adapt
f=new Frame("Mouse Adapter"); {
f.addMouseListener(this); public static void main(String[] args) {
f.setSize(300,300); new MouseAdapterExample();
f.setLayout(null); }
f.setVisible(true); }
}
Working with Graphics
 The AWT package includes several methods that support graphics
 All graphics are drawn relative to a window.
 This can be the main window of an application or a child window.
 The origin of each window is at the top-left corner and is 0,0.
 Coordinates are specified in pixels.
 All output to a window takes place through a graphics context.
 A graphics context is encapsulated by the Graphics class and is obtained in two ways:
1. It is passed to a method, such as paint( ) or update( ), as an argument.
2. It is returned by the getGraphics( ) method of Component.
 The Graphics class defines a number of methods that draw various types of objects, such as
lines, rectangles, and arcs ovals, images, texts.
 Each shape can be drawn edge-only or filled.
 Objects are drawn and filled in the currently selected graphics color, which is black by default.
 When a graphics object is drawn that exceeds the dimensions of the window, output is
automatically clipped.
Coordinate system of Java
 Java graphics uses a coordinate system based on pixels. The whole screen is made up of many pixels which are
small dots that can each be set to a separate colour.
 Modern displays support several different numbers of pixels :
 (Width X Height) 640 X 480, 800 X 600, 1024 X 768, 1152 X 864, . . .
 Each pixel has an x and y coordinate measured across and down from the top left hand corner (not like a
conventional x-y coordinate system).

 Java coordinate system has the origin (0,0) in the top-left corner. Positive x values are to the right and +ve y
values to the bottom. The values of (x,y) are in pixels.
Methods in the Graphics class
1) setColor(Color c)
Set the current color, where c has several standard choices such as Color.black, Color.blue, Color.red, etc.
2) drawLine(int x1, int y1, int x2, int y2)
Draw a line between points (x1,y1) and (x2,y2)
3) drawRect (int x, int y, int width, int height)
Draws a rectangle, (x,y) are the coordinates of the top left corner, the bottom right corner will be at (x+width,y+height).
4) fillRect (int x, int y, int width, int height)
Fills a rectangle, (x,y) are the coordinates of the top left corner, the bottom right corner will be at (x+width,y+height).
5) drawOval (int x, int y, int width, int height)
Draws an oval bounded by the rectangle specified by these parameters. If width and height are same, it draws a circle
6) fillOval (intx, int y, int width, int height)
Fills an oval bounded by the rectangle specified by these parameters.
7)draw3DRect (int x, int y, int width, int height, int arcWidth, boolean raised)
Draws a rectangle with shaded sides that provide a 3-D appearance.
8) fill3DRect (int x, int y, int width, int height, boolean raised)
Fills a rectangle with shaded sides that provide a 3-D appearance.
9) drawRoundRect (int x, int y, int width, int height, int arcWidth, int arcHeight)
Draws a rectangle with rounded corners.
Methods in the Graphics class
10) fill3DRect (int x, int y, int width, int height, int arcWidth, int arcHeight)
Fills a rectangle with rounded corners.
11) drawArc(int x,int y,int width, int height, int startAngle, int arcAngle)
An arc is formed by drawing an oval between a start angle and a finish angle. The start angle is measured
from the positive x-axis and is expressed in degrees. The arc angle is expressed in degrees from the start
angle. Angles extend from the center of the bounds box.
12) drawPolyline (int[] x, int[] y, int N)
Draws lines connecting the N points given by the x and y arrays.
13) drawPolygon (int[] x, int[] y, int N)
Draws lines connecting the points given by the x and y arrays. Connects the last point to the first if they are
not already the same point.
14) fillPolygon (int[] x, int[] y, int N)
Fills lines connecting the points given by the x and y arrays. Connects the last point to the first if they are not
already the same point
Drawing Shapes
Line: (x2, y2)
g.drawLine (x1, y1, x2, y2 ); (x1, y1) width

Rectangle: (x1, y1)


height
g.drawRect (x1, y1, width, height );
width
(x1, y1)
Oval (Circle or Ellipse):
g.drawOval (x1, y1, width, height ); height

arc
angle
(x1, y1)
Arc:
g.drawArc (x1, y1, width, height, angle1, angle );

height angle1
The Oval and Arc shapes are drawn inside
an imaginary rectangle. width
Demonstrating the Drawing Methods
import java.awt.*;
import javax.swing.*; // Draw Arcs
public class DisplayGraphics extends JPanel{ g.drawArc(20, 350, 70, 70, 0, 180);
public void paint(Graphics g) { g.fillArc(70, 350, 70, 70, 0, 75);
// Display strings // Draw a polygon
g.drawString("Hello World", 20, 40); int xpoints[] = {20, 200, 20, 200, 20};
int ypoints[] = {450, 450, 650, 650, 450};
// Draw lines. int num = 5;
g.drawLine(20, 40, 100, 90); g.drawPolygon(xpoints, ypoints, num);
g.drawLine(20, 90, 100, 40); }
g.drawLine(40, 45, 250, 80); public static void main(String[] args) {
// Draw rectangles. DisplayGraphics m=new DisplayGraphics();
g.drawRect(20, 150, 60, 50); JFrame f=new JFrame("Display Shapes");
g.fillRect(110, 150, 60, 50); f.add(m);
g.drawRoundRect(200, 150, 60, 50, 15, 15); f.setSize(400,700);
g.fillRoundRect(290, 150, 60, 50, 30, 40); f.setVisible(true);
// Draw Ellipses and Circles f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
g.drawOval(20, 250, 50, 50);
g.fillOval(100, 250, 75, 50); }
g.drawOval(200, 260, 100, 40); }
output
To run this program simply
give the command
java DisplayGraphics.java
Because this is a single
source file program
Sizing Graphics

 Some times we want to size a graphics object to fit the current size of the frame in
which it is drawn.
 For this purpose, you should first obtain the current dimensions of the frame by
calling the getSize() method .
 getSize( ) returns the dimensions as integer values stored in the width and height
fields of a Dimension instance.
 Once we obtain the size of the frame, then we can scale our graphical output as per
requirement.
Working with Color
 Java supports color in a portable, device-independent fashion.
 It then finds the best match for that color, given the limits of the display hardware currently executing your program. All
colors can be specified as a mix of three primary colors: red, green, and blue(RGB).
 Color defines several constants (for example, Color.black) to specify a number of common colors.
 You can also create your own colors, using one of the color constructors:
Color(int red, int green, int blue)
Color(int rgbValue)
Color(float red, float green, float blue)
 The first constructor takes three integers that specify the color as a mix of red, green, and blue. These values must be
between 0 and 255, as in this example:
new Color(255, 100, 100); // light red
 The second color constructor takes a single integer that contains the mix of red, green, and blue packed into an integer.
 The integer is organized with red in bits 16 to 23, green in bits 8 to 15, and blue in bits 0 to 7.
int newRed = (0xff000000 | (0xc0 << 16) | (0x00 << 8) | 0x00);
Color darkRed = new Color(newRed);
 The final constructor, Color(float, float, float), takes three float values (between 0.0 and 1.0) that specify the relative mix
of red, green, and blue.
 Once you have created a color, you can use it to set the foreground and/or background color by
using the setForeground() and setBackground() methods.
Color Methods
 The Color class defines several methods that help manipulate colors.
Using Hue, Saturation, and Brightness
 The hue-saturation-brightness (HSB) color model is an alternative to red-green-blue (RGB) for
specifying particular colors.
 Figuratively, hue is a wheel of color and is specified with a number between 0.0 and 1.0 (the
colors are approximately red, orange, yellow, green, blue, indigo, and violet).
 Saturation is another scale ranging from 0.0 to 1.0, representing light pastels to intense hues.
 Brightness values also range from 0.0 to 1.0, where 1 is bright white and 0 is black.
 Color supplies two methods that let you convert between RGB and HSB.
static int HSBtoRGB(float hue, float saturation, float brightness)
static float[ ] RGBtoHSB(int red, int green, int blue, float values[ ])
 HSBtoRGB( ) returns a packed RGB value compatible with the Color(int) constructor.
 RGBtoHSB( ) returns a float array of HSB values corresponding to RGB integers.
 If values is not null, then this array is given the HSB values and returned.
 Otherwise, a new array is created and the HSB values are returned in it.
getRed( ), getGreen( ), getBlue( )
 You can obtain the red, green, and blue components of a color independently using getRed(
), getGreen( ), and getBlue( ):
int getRed( )
int getGreen( )
int getBlue( )
getRGB( )
 To obtain a packed, RGB representation of a color, use getRGB( ), shown here:
int getRGB( )
Setting the Current Graphics Color
 By default, graphics objects are drawn in the current foreground color. You can change this
color by calling the Graphics method setColor( ):
void setColor(Color newColor)
Here, newColor specifies the new drawing color.
 You can obtain the current color by calling getColor( ), shown here:
Color getColor( )
A Color Demonstration Program
import java.awt.*;
import javax.swing.*; g.setColor(Color.CYAN);
public class ColorDemo extends JPanel{ // Draw Arcs
public void paint(Graphics g) { g.drawArc(20, 350, 70, 70, 0, 180);
g.setColor(Color.MAGENTA); g.fillArc(70, 350, 70, 70, 0, 75);
// Display strings // Draw a polygon
g.drawString("Hello World", 20, 40); int xpoints[] = {20, 200, 20, 200, 20};
g.setColor(Color.RED); int ypoints[] = {450, 450, 650, 650, 450};
// Draw lines. int num = 5;
g.drawLine(20, 40, 100, 90); g.setColor(Color.GREEN);
g.drawLine(20, 90, 100, 40); g.drawPolygon(xpoints, ypoints, num);
g.drawLine(40, 45, 250, 80);
g.setColor(Color.BLUE); }
// Draw rectangles. public static void main(String[] args) {
g.drawRect(20, 150, 60, 50); ColorDemo m=new ColorDemo();
g.fillRect(110, 150, 60, 50); JFrame f=new JFrame("Display Shapes with Colors");
g.drawRoundRect(200, 150, 60, 50, 15, 15); f.add(m);
g.fillRoundRect(290, 150, 60, 50, 30, 40); f.setSize(400,700);
g.setColor(Color.RED); f.setVisible(true);
// Draw Ellipses and Circles f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
g.drawOval(20, 250, 50, 50);
g.fillOval(100, 250, 75, 50); }
g.drawOval(200, 260, 100, 40); }
>java ColorDemo.java
Working with Fonts
 AWT supports multiple type font-manipulation operations and dynamic selection.
 Fonts have a family name, a logical font name, and a face name.
 The family name is the general name of the font, such as Courier.
 The logical name specifies a category of font, such as Monospaced.
 The face name specifies a specific font,such as Courier Italic.
 Fonts are encapsulated by the Font class.
 The Font class defines these variables:

Variable Meaning

String name Name of the font


float pointSize Size of the font in points
int size Size of the font in points
int style Font style
Some methods defined by Font class
Method Description
1. string getfamily( ) returns the name of the font family to which the invoking font belongs
2. string getfontname( ) returns the face name of the invoking fonts
3. string getname( ) returns the logical name of the invoking font
4. int getsize( ) returns the size in points of the invoking font
5. int getstyle( ) returns the style values of the invoking font.
6. Boolean is plain ( ) returns true if the font includes the plain style value otherwise false is returned
7. Boolean is italic ( ) returns true if the font includes the italic style value otherwise false is returned
8. Boolean is bold ( ) returns true if the font includes the bold style value otherwise false is returned.
Determining the Available Fonts
 When working with fonts, often you need to know which fonts are available on
 your machineTo obtain the information about the fonts that are available on the machine
we use the following methods that are defined in the graphics environment object.
 String[ ] getAvailableFontFamilyNames() returns an array of strings that contain the name of
the available font families
 Font[ ] getAllFonts returns an array of fonts object for all of the available fonts.
 Since these methods are members of GraphicsEnvironment, you need a
GraphicsEnvironment reference to call them.
 You can obtain this reference by using
static GraphicsEnvironment getLocalGraphicsEnvironment( )
Creating and Selecting a Font
To select a new font, first construct a Font object by:
Font (string fontName,int fontStyle,int pointSize)
Then set the font by setFont(Font fontObj)
Font style may be Font.PLAIN, Font.BOLD etc.
// Display Available Fonts
import java.awt.GraphicsEnvironment;
public class ListJavaFonts
{
public static void main(String[] args)
{
String fonts[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
for ( int i = 0; i < fonts.length; i++ )
{
System.out.print(fonts[i]+" ");
}
}
}

I:\Java11> java ListJavaFonts.java


Agency FB Algerian Arial Arial Black Arial Narrow Arial Rounded MT Bold Bahnschrift Baskerville Old Face Bauhaus 93 Bell MT
Berlin Sans FB Berlin Sans FB Demi Bernard MT Condensed Blackadder ITC Bodoni MT Bodoni MT Black Bodoni MT
Condensed Bodoni MT Poster Compressed Book Antiqua Bookman Old Style Bookshelf Symbol 7 Bradley Hand ITC Britannic
Bold Broadway Brush Script MT Calibri Calibri Light Californian FB Calisto MT Cambria Cambria Math Candara Candara Light
Castellar Centaur Century Century Gothic Century Schoolbook Chiller Colonna MT Comic Sans MS Consolas Constantia
Cooper Black Copperplate Gothic Bold Copperplate Gothic Light Corbel Corbel Light Courier New Curlz MT Dialog DialogInput
Ebrima Edwardian Script ITC Elephant Engravers MT Eras Bold ITC Eras Demi ITC Eras Light ITC Eras Medium ITC Felix Titling
Footlight etc..
fonts and their styles
import java.awt.*;
import javax.swing.*;

public class DisplayFont extends JPanel{

public void paint(Graphics g)


{
setBackground(Color.black);
setForeground(Color.white);
Font tr = new Font("TimesRoman", Font.PLAIN, 18);
Font trb = new Font("TimesRoman", Font.BOLD, 18);
Font tri = new Font("TimesRoman", Font.ITALIC, 18);
Font trbi = new Font("TimesRoman", Font.BOLD+Font.ITALIC, 18);
Font h = new Font("Helvetica", Font.PLAIN, 18);
Font c = new Font("Courier", Font.PLAIN, 18);
Font d = new Font("Dialog", Font.PLAIN, 18);
Font z = new Font("ZapfDingbats", Font.PLAIN, 18);

g.setFont(tr);
g.drawString("Hello World (times roman plain)",10,25);
g.setFont(trb);
g.drawString("Hello World (times roman bold)",10,50);
g.setFont(tri);
g.drawString("Hello World (times roman italic)",10,75);
g.setFont(trbi);
g.drawString("Hello World (times roman bold & italic)",10,100);
g.setFont(h);
g.drawString("Hello World (helvetica)",10,125);
g.setFont(c);
g.drawString("Hello World (courier)",10,150);
g.setFont(d);
g.drawString("Hello World (dialog)",10,175);
g.setFont(z);
g.drawString("Hello World (zapf dingbats)",10,200);
}
public static void main(String[] args) {
DisplayFont m=new DisplayFont();
JFrame f=new JFrame("Display Fonts and types");
f.add(m);
f.setSize(400,400);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
Swings - Introduction
Java Foundation Classes (JFC)
 The Java Foundation Classes, or JFC, is a collection of APIs for developing graphical
user interfaces.
 The JFC consists of the following APIs :
 Abstract Window Toolkit (AWT): native GUI components
 Swing: lightweight GUI components
 Java 2D: rendering two-dimensional shapes, text, and images
 Accessibility: allowing compatibility with, for example, screen readers and screen
magnifiers
 The two sets of JFC classes that are used to build GUI are AWT and Swing classes.
 To learn and understand these swing programs, AWT Programming knowledge is not
required.
https://www.youtube.com/watch?
v=g3gTT34Ctlw&list=PLf8EAse10pKenfwuh0N6M2DU9JItVta6z
Swings
 Although the AWT is still a crucial part of Java, its component set is no longer widely used to
create graphical user interfaces. Today, most programmers use Swing or JavaFX for this
purpose.
 (ie) The Swing package is an improved version of the AWT
 Swing does not stand for anything
 Swing is a Java Graphical User Interface (GUI) toolkit.
 It is used to create a GUI with Java
 It is an Application Programming Interface (API) for providing a Graphical User Interface (GUI)
for Java programs.
 Swing is a collection of libraries that contains primitive widgets or controls used for designing
Graphical User Interfaces (GUIs).
 In addition to the familiar components, such as buttons, check boxes, and labels, Swing
supplies several exciting additions, including tabbed panes, scroll panes, trees, and tables.
 Unlike AWT components, Swing components are not implemented by platform-specific code.
Instead, they are written entirely in Java and, therefore, are platform-independent.
 The term lightweight is used to describe such elements.
 The number of classes and interfaces in the Swing packages is substantial.
The origins of the Swing
 Earlier, the concept of Swing did not exist in Java and the GUIs were built by using the Java’s
original GUI system, Abstract Window Toolkit (AWT).
 AWT translates it visual components into platform-specific equivalents (peers).
 This means that the look and feel of a component is defined by the platform, not by Java.
 Because the AWT components use native code resources, they are referred to as
heavyweight.
The use of native peers led to several problems.
1. First, because of variations between operating systems, a component might look, or even
act, differently on different platforms. This threatened the philosophy of Java: write once,
run anywhere.
2. Second, Under AWT, the look and feel of each component was fixed and defined by the
platform(OS), not by Java.
3. Third, the use of heavyweight components caused some restrictions.
 to overcome the limitations and restrictions present in the AWT, Swing was introduced in
1997 as part of the Java Foundation Classes (JFC).
Swing Is Built on the AWT
 Although Swing eliminates a number of the limitations inherent in the AWT, Swing
does not replace it.
 Instead, Swing is built on the foundation of the AWT. This is why the AWT is still a
crucial part of Java.
 Swing also uses the same event handling mechanism as the AWT. Therefore, a
basic understanding of the AWT and of event handling is required to use Swing.

Advantage of Swing over AWT.


 Swing components are Platform independent.
 It is lightweight.
 It supports pluggable look and feel.
 It has more powerful components like tables, lists, scroll panes, color
chooser, tabbed pane etc.
 It follows MVC (Model View Controller) architecture
AWT vs Swings
AWT Swing
Java swing components are platform-
AWT components are platform-dependent.
independent.

AWT components are heavyweight. Swing components are lightweight.

AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.

Swing provides more powerful


componentssuch as tables, lists,
AWT provides less components than Swing.
scrollpanes, colorchooser, tabbedpane
etc.

AWT doesn't follows MVC(Model View


Controller) where model represents data,
view represents presentation and controller
acts as an interface between model and view. Swing follows MVC.
Two Key Swing Features
1. Swing Components Are Lightweight
2. Swing Supports a Pluggable Look and Feel
1.Swing Components Are Lightweight:
 Swings are written entirely in Java and do not map directly to platform-specific
peers.
 Thus, these components are often called lightweight components.
 Lightweight components are more efficient and more flexible.
 Each component will work in a consistent manner across all platforms.
 Almost all Swing components are lightweight except JApplet, JFrame, JDialog,
and Jwindow, which must be drawn using native GUI on a specific platform
(called heavyweight components)
Two Key Swing Features
2. Swing supports a pluggable look and feel (PLAF) .
 A look and feel is the default appearance and behavior of any GUI.
 Swing supports pluggable look and feel , giving you the option to choose a particular look and feel instead of its
default “ metal look and feel.
 We can choose between Java look-and-feel and the look-and-feel of the underlying OS (e.g., Windows, UNIX or
macOS).
 For example, the same program can use either the Java Look & Feel or the Windows Look & Feel.
 If the later(underlying OS) is chosen, a Swing button runs on the Windows looks like a Windows' button and feels
like a Window's button. Similarly, a Swing button runs on the UNIX looks like a UNIX's button and feels like a
UNIX's button.
 Pluggable look and feel(PLAF) is a mechanism used in the Java Swing component toolkit allowing to change the
look and feel of the graphical user interface at runtime.
 PLAF means that you ( the programmer) can add a few extra lines of code to allow users to select which look and
feel they want anytime they run your program which operating system is running underneath.
 Look and feel of each component is determined by Swing, not by the underlying OS
Look And Feel
 You can change the look and feel of the GUI displayed to the user.
 The look and feel is provided by the following packages and their sub-packages.
javax.swing.plaf
javax.swing.plaf.basic
javax.swing.plaf.metal
javax.swing.plaf.multi
javax.swing.plaf.synth
 The System Look and Feel packages are shipped along with Java SDK
com.sun.java.swing.plaf.gtk.GTKLookAndFeel (for Solaris/Linux)
com.sun.java.swing.plaf.motif.MotifLookAndFeel (any platform)
com.sun.java.swing.plaf.windows.WindowsLookAndFeel (only Windows)
Look and Feel examples
The appearance of the Jframe Look and Feel provided
by the operating system in which the program is The appearance of the Jframe Look and Feel provided by
running (in this case, Windows) java

import javax.swing.*; import javax.swing.*;


public class JFrame1 public class JFrame2
{ {
public static void main(String[] args) public static void main(String[] args)
{ {
JFrame aFrame = new JFrame("First frame"); JFrame.setDefaultLookAndFeelDecorated(true);
aFrame.setSize(250, 100); JFrame aFrame = new JFrame("Second frame");
aFrame.setVisible(true); aFrame.setSize(250, 100);
} aFrame.setVisible(true);
} }
}
Note that Java’s look and feel has similar features to that of Windows,
but their appearance is different.
Look And Feel
 Java provides the following look and feel:
1. A cross-platform look and feel (aka Metal) is the default look and feel in Java. The beauty of this look
and feel is that it looks uniform on all platforms (javax.swing.plaf.metal.MetalLookAndFeel).
2. A system-defined (native) look and feel shows the GUI according to the look and feel of the native
system.
3. Synth – Using this, you can create your own look and feel (javax.swing.plaf.synth. SynthLookAndFeel).
4. Multiplexing – Delegates to different look and feel at same time.
 The look and feel can be set and get using the methods getLookAndFeel() and
setLookAndFeel() of the javax.swing.UIManager class. Their signatures are as follows:
– static LookAndFeel getLookAndFeel()
– static void setLookAndFeel(LookAndFeel l)
– static void setLookAndFeel(String className)

The javax.swing.UIManager class manages the look-and-feel of the user interface


public static void main(String[] args) {
try {
UIManager.setLookAndFeel(
// Put your favorite Look and Feel here!!!
);
} catch (Exception e) { }
new SwingApplication();
}
MVC (Model-View-Controller)
 The fundamental idea behind MVC is the separation of the data model for an item
from its presentation.
 For example, we can draw different representations (e.g., bar graphs, pie charts) of
the data in a spreadsheet.
 The data is the model ; the particular representation is the view .
 A single model can have many views that present the data differently.
 A user interface component’s controller defines and governs its behavior.
 Typically, this includes changes to the model, which, in turn, cause the view(s) to
change, also.
 Example: For a checkbox component, the data model could be a single boolean
variable, indicating whether it’s checked or not.
 The behavior for handling mouse-press events would alter the model, and the view
would examine that data when it draws the on-screen representation.
MVC (Model-View-Controller)
 MVC is a software architecture that separates the state of an object (the model), the way the object is displayed to
the user (the view), and the way that the object's state is updated (the controller).
In general a visual component has 3 distinct aspects
(ie) MVC breaks GUI (Graphical User Interface) into three components:
1. The model corresponds to the state information associated with the component. (ie A Model controls the data in
components, from example the state of a check box is checked or unchecked or the pressed/unpressed state of a
push button.
2. The view determines how the component is displayed on the screen. (View represents visual representation of
the component's model.) For example, the view displays the correct color of a component, whether the
component appears raised or lowered (in the case of a button), and the rendering of a desired font.
3. The controller determines how the component responds to the user.(The controller is responsible for
determining whether the component should react to any input events from input devices such as the keyboard or
mouse.) ((ie)Handle events, button clicks)
Example : in the case of a check box,
 model contains a field that indicates if the box is checked or unchecked
 view determines how the component (checkbox) is displayed on the screen
 Controller-when user clicks a checkbox, the controller reacts by changing the model to reflect user’s choice
(checked or unchecked).
MVC (Model-View-Controller)
 In MVC architecture, model, view and controller are independent of one another.
 By separating a component into a model, a view, and a controller, the specific implementation of each
can be changed without affecting the other two.
 Although the MVC architecture and the principles behind it are conceptually sound, the high level of
separation between the view and the controller is not beneficial for Swing components.
MVC in Swing
 Swing’s component architecture is based on MVC, it does not use a classical implementation of it.
 In swing,Each component is actually composed of two pieces.
 The first piece, called the UI-delegate, is responsible for the “view” and “controller”
roles.
 It takes care of drawing the component and responding to user events.
 The second piece is the data model itself.
 This separation makes it possible for multiple Swing components to share a single
data model. For example, a read-only text box and a drop-down list box could use
the same list of strings as a data model.
 For this reason, Swing’s approach is called either the Model-Delegate architecture or the Separable Model
architecture.
The Model-View-Controller Architecture
 Swing’s pluggable look and feel is made possible by its Model-Delegate architecture.
 Because the view (look) and controller (feel) are separate from the model, the look and feel can be
changed without affecting how the component is used within a program.
 Models are defined by interfaces. For example, the model for a button is defined by the ButtonModel
interface.
 UI delegates are classes that inherit ComponentUI. For example, the UI delegate for a button is
ButtonUI.

View

Swing MVC Model

Controller

Component UI-Delegate

With Swing, the view and the controller are combined into a UI-Delegate object
Components and Containers
A Swing GUI consists of two key items:
1) components and
2) containers.
 A Component is a graphics object that can be displayed on a screen and can interact with a user.
 (ie) A component is an independent visual control, such as a push button or slider.
 A container is a GUI component that can contain other components
 A Container is an area where components are placed.
 A container is for displaying components, and components must be displayed within a container.
A Button is an example of a component, whereas a JFrame is an example of a container
 Thus, a container is a special type of component that is designed to hold other components.
 java.awt.Container extends java.awt.Component so containers are themselves components.
 All Swing GUIs will have at least one container.
 Because container is a component it can hold other containers also.
 In general, we create one or more components and add them to a container to display
them on the screen
Components
 Swing components are derived from the JComponent class.
(The only exceptions are the four top-level containers: JFrame, JApplet, JWindow, and
JDialog.)
 JComponent provides the functionality that is common to all components.
 For example, JComponent supports the pluggable look and feel.
 JComponent inherits the AWT classes Container and Component.
 Thus, a Swing component is built on and compatible with an AWT component.
 All the Swing components are represented by classes in the javax.swing package.
 All the component classes start with J: JLabel, JButton, JScrollbar, ...
The following table shows the class names for Swing components (including
those used as containers).

JApplet (Depricated) J Button JCheckBox JCheckBoxMenultem


JColorChooser JComboBox JComponent JDesktopPane
JDialog JEditorPane JFileChooser JFormattedTextReld
J Frame JlnternalFrame JLabel JLayeredPane
JList JMenu JMenuBar JMenultem
JOptionPane JPanel JPasswordField JPopupMenu
JProgressBar JRadioButton JRadioButtonMenultem JRootPane
JScrollBar JScrollPane JSeparator JSlider
JSpinner JSplitPane JTabbedPane JTable
JTextArea JTextField JTextPane JTogglebutton
JToolBar JToolTip JTree JViewport
JWindow
Basic components to gather input
 Jbutton: Causes an action to occur when it is clicked
 JCheckBox : a toggled on/off button displaying state to user.
 JRadioButton: a toggled on/off button displaying its state to user.
 JComboBox: a drop-down list with optional editable text field. The user can key in a
value or select a value from drop-down list.
 Jlist: allows a user to select one or more items from a list.
 Jmenu:popup list of items from which the user can select.
 Jslider: lets user select a value by sliding a knob.
 JTextField :area for entering a single line of input.
Basic components to present information
Jlabel: contains text string, an image, or both.
JProgressBar: communicates progress of some work.
JToolTip: describes purpose of another component.
Jtree: a component that displays hierarchical data in outline form.
Jtable: a component user to edit and display data in a two-dimensional grid.
JTextArea, JTextPane, JEditorPane :
define multi-line areas for displaying, entering, and editing text.
Swing Components
Containers
Swing defines two types of containers.
1.Top-level containers or Heavyweight containers :
• Originally are four top-level Swing containers
Since applets are now removed, there are now only 3 top-level containers
1. JFrame: A JFrame provides the "main window" for the GUI application, which has a title bar (containing an
icon, a title, the minimize, maximize/restore-down and close buttons), an optional menu bar, and the content
display area
2. JDialog: This is a "pop-up window" used for interacting with the users. A Dialog has a title-bar (containing an
icon, a title and a close button) and a content display area
3. JApplet: An Applet (in package javax.swing.JApplet) is the top-level container for an applet, which is a Java
program running inside a browser
4. Jwindow: Jwindow is a top-level container window without a title bar, windows menu, etc.
 These containers do not inherit JComponent.
 They however, inherit the AWT classes Component and Container.
 Unlike Swing’s other components, which are lightweight, the top-level containers are
heavyweight.
 As the name implies, a top-level container must be at the top of a containment hierarchy.
 Top-level containers cannot be added to other containers.
 Furthermore, every containment hierarchy must begin with a top-level container.
 The one most commonly used for applications is JFrame.
Containers
2.Light weight containers or Middle level containers:
 The second type of containers supported by Swing are lightweight containers.
 Lightweight containers do inherit JComponent.
 An example of a lightweight container is JPanel, which is a general-purpose container.
 Lightweight containers are often used to organize and manage groups of related components because a
lightweight container can be contained within another container.
 Thus, you can use lightweight containers such as JPanel to create subgroups of related controls that are
contained within an outer container.
note:
 A JPanel is a middle-level container because JPanel is both a Container and a Component
 Because it’s a container, you can put other components into it
 Because it’s a component, you can put it into other containers
The Top-Level Container Panes
 A pane represents an area of a window where some text or components can be displayed.
 Each top-level container defines a set of panes.
 Swing's top-level containers are organized into a series of panes: root pane, layered pane, content pane, and glass pane.

JFrame / JDialog

Root Pane

Layered Pane

File Edit

Undo
Redo
Cut

Content Pane

Glass Pane
The Top-Level Container Panes
1.Root pane
 Whenever you create a top-level container, an intermediate container of the top-level container
named JRootPane is automatically created.
 JRootPane is a lightweight container whose purpose is to manage layered pane, content pane,
and glass pane.
 It also helps manage the optional menu bar.
 JRootPane is at the top of the pane hierarchy
2.Glass pane
 The glass pane is the top-level pane.
 It sits above and completely covers all other panes.
 By default, it is a transparent instance of JPanel.
 The glass pane enables you to manage mouse events that affect the entire container
 In most cases, you won’t need to use the glass pane directly, but it is there if you need it.
The Top-Level Container Panes
3.Layered Pane
 The layered pane is an instance of JLayeredPane.
 The layered pane allows components to be given a depth value. This value determines which component
overlays another.
 The layered pane holds the content pane and the (optional) menu bar.
4.Content pane:
 we cannot add components directly to a top level container like JFrame, we must add them to the content
pane for the window.
 A content pane is the area in a top level container that can hold other components.
 Every top-level container has a content pane (Inner area of GUI window -below title bar, inside border)
that can contain components like JButtons directly, or it can hold other containers, like JPanels, that in turn
contain such components.
 The content pane can be retrieved using the getContentPane() method.
Note:
• After Java 5.0, the use of getContentPane( ) is no longer necessary.
• We can simply call add( ), remove( ), and setLayout( ) directly on Jframe because these methods have been
Top level containers : JDialog
 A Dialog box is a top-level window with a title and a border that is used to displays a message to the
user or requests input.
 A dialog box is a container, because it can have buttons, text fields, and other components within it.
 The JDialog class is used to create custom(Creating our own dialog) dialog boxes
 JDialog is a subclass of the AWT’s Dialog
 Like a JFrame, Components are added to a JDialog’s content pane
 Unlike JFrame, it doesn't have maximize and minimize buttons.
 Has support for default window close operations

 Swing provides several classes for displaying “ready-made(standard dialogs)” dialog boxes – already
discussed in basic Java I/O in unit i)
 JOptionPane creates dialog boxes that consist of a title, a message, an icon, and a couple of buttons
 JColorChooser presents a dialog box for choosing a color
 JFileChooser presents a dialog box for choosing a file.
Top level containers : JDialog
 JDialog class represents a Swing dialog window. Note that the JDialog class extends the Dialog class.
 It is displayed by invoking its setVisible method with an argument of true, and is hidden by invoking its
setVisible method with an argument of false
 A dialog window is either modal or modeless. A modal dialog window must be closed before the program
can continue.
 A modeless dialog window is one that does not need to be closed, and you still can interact with the
program or programs behind the modeless dialog.
 We can use JDialog class to create a custom dialog, or invoke the many class methods in JOptionPane to
create a variety of standard dialogs.
 We can create a JDialog with an owner, which could be another JDialog, a JFrame, or a JWindow.
 By specifying an owner for a JDialog, we are creating a parent-child relationship.
 When the owner of a JDialog is closed, the JDialog is also closed. When the owner is minimized or
maximized, the JDialog is also minimized or maximized.
 A JDialog with an owner is always displayed on top of its owner.
 We can specify an owner of a JDialog in its constructors.
A typical constructor is specified as follows:
public JDialog (Frame owner, String title, boolean modal)
Example:JDialog
import javax.swing.*;
public class CreateDialog {
public static void main( String[] args) {
JFrame parent = new JFrame();
JDialog jd = new JDialog(parent, "JMC", true);
JLabel myLabel = new JLabel("Hello World");
jd.setSize(300,200);
jd.getContentPane().add(myLabel);
jd.setVisible(true);
}
}
Swing Packages
 In Java, GUI-based programs are implemented by using classes from the javax.swing and java.awt
packages.
 The Swing components are in javax.swing.*, so you always need to import that for a Swing
application
 Note the letter x that appears after the word java.
 Swing is a very large subsystem and makes use of many packages

 Beginning the JDK 9, the Swing packages are part of the java.desktop module.
 The main package is javax.swing. This package must be imported into any program that uses Swing. It contains
the classes that implement the basic Swing components, such as push buttons, labels, and check boxes.
A Simple Swing Application
 Swing programs differ from both the console-based programs and the AWT-based programs .
 For example, they use a different set of components and a different container hierarchy than does the
AWT. Swing programs also have special requirements that relate to threading. The best way to
understand the structure of a Swing program is to work through an example.
 There were two types of Java programs in which Swing is typically used.
 The first is a desktop application.
 This type of Swing application is widely used, and is the type of Swing program described here.
 The second is the applet.
Because applets are now deprecated and not suitable for use in new code, they are not discussed
Top level containers : JFrame
 JFrame, a Swing version of Frame, is a top-level container for Java GUI applications.
 Like Frame, JFrame is displayed as a standalone window with a title bar and a border.
 JFrame is a subclass of java.awt. Frame so it inherits all the features of an AWT Frame.
 JFrame works like the main window where components like labels, buttons, textfields are added to create a
GUI.
 It can be moved, resized, iconified.
 JFrame provides the basic building block for screen-oriented applications.
 Note:Whenever you create a top-level container, an intermediate container of the top-level container named
Root Pane (JRootPane) is automatically created.

JFrame is the main window component of any Swing application. To create an application window, you just
need to create a class that extends JFrame.
Consturctor:
JFrame win = new JFrame(“Optional Window Title”);

To add a component to a JFrame, add it to the content pane:


JFrame Methods
JFrame Method What It Does
Container getContentPane () Returns the frame’s container to
which components can be added
void setResizable (boolean b) If b is false, the user cannot resize the
window; if b is true, the user can
resize the window. The default is that
the window is resizable.

void setDefaultCloseOperation (int Sets the operation that will happen by


operation) default when the user initiates a
"close" on this frame.

void setSize(int width, int height) Sets the size of the frame to the width
and height in pixels.
void setTitle (String title) Displays the title in the frame’s title
bar
void setVisible (boolean b) Displays the frame if b is true or hides
it if b is false
Differences between Jfarme and JWindow
 Windows and frames are the top-level containers for Java components.
 A JWindow is simply a plain, graphical screen that displays in your windowing system
 JFrame, on the other hand, is a subclass of JWindow that has a titlebar, window-managed buttons (close,
minimize, etc.), and border.
import javax.swing.*;
public class TopLevelWindows {
public static void main(String[] args) {
JFrame frame = new JFrame("The Frame");
frame.setSize(300, 300);
frame.setLocation(100, 100);
JWindow window = new JWindow();
window.setSize(300, 300);
window.setLocation(500, 100);
frame.setVisible(true);
window.setVisible(true);
}
}
Program using Event Dispatching Thread
Program without using Event Dispatching Thread
import javax.swing.*;
import javax.swing.*;
class SwingDemo {
SwingDemo() { class SwingDemo1 {
// Create a new JFrame container. SwingDemo1() {
JFrame jfrm = new JFrame("A Simple Swing Application"); // Create a new JFrame container.
// Give the frame an initial size. JFrame jfrm = new JFrame("A Simple Swing Application");
jfrm.setSize(275, 100);
// Give the frame an initial size.
// Terminate the program when the user closes the application.
jfrm.setSize(275, 100);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a text-based label. // Terminate the program when the user closes the application.
JLabel jlab = new JLabel(" Swing means powerful GUIs."); jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add the label to the content pane. // Create a text-based label.
jfrm.add(jlab); JLabel jlab = new JLabel(" Swing means powerful GUIs.");
// Display the frame.
// Add the label to the content pane.
jfrm.setVisible(true);
}
jfrm.add(jlab);
public static void main(String args[]) { // Display the frame.
// Create the frame on the event dispatching thread. jfrm.setVisible(true);
SwingUtilities.invokeLater(new Runnable() { }
public void run() { // Anonymous inner class! public static void main(String args[]) {
new SwingDemo(); Note: The invokeLater() method places the application on
} the Swing Event Queue. It is used to ensure that all UI
}); updates are concurrency-safe. In other words, it is tonew SwingDemo1();
} prevent GUI from hanging in certain situations. }
} }
Launch the swing Application from Main Method
By default all AWT and Swing-based applications start off with two threads.
 One is the main application thread which handles execution of the main() method.
The other, referred to as the event-dispatching thread, is responsible for handling events, painting, and
layout.
 GUI event handling code executes in a thread, called the Event dispatcher thread.
So far, we have launched our GUI application from the main method by creating a frame and making it
visible.
 This works fine for most applications.
In certain situations, however, it could cause problems.
To avoid possible thread deadlock, you should launch GUI creation from the event dispatcher thread as
follows:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() { // Anonymous inner class
new ConstructorOfClass(); // Place the code for creating a frame and setting it properties
}
});
Launch the swing Application from Main Method
For example, the SwingDemo constructor is invoked using these lines of code:
SwingUtilities.invokeLater(new Runnable() {
public void run() { // Anonymous inner class!
new SwingDemo();
}}
 This sequence causes a SwingDemo object to be created on the event
dispatching thread rather than on the main thread of the application.
 In general, Swing programs are event-driven.
 For example, when a user interacts with a component, an event is generated.
 An event is passed to the application by calling an event handler defined by
the application.
Launch the swing Application from Main Method
 But, handler is executed on the event dispatching thread provided by Swing and not on the main thread of
the application
 Event handlers are called on the thread that is not created by the program
 All swing GUI components are created and updated from event dispatching thread, and not the main thread
 Main is executed from the main thread
 Main cannot directly instantiate a class object, it must create a Runnable object that executes on the event
dispatching thread and have this object create the GUI
 To enable the GUI code to be created on the event dispatching thread, you must use one of two methods
which are invokeLater( ) and invokeAndWait( )
The general form are shown here:
1. static void invokeLater(Runnable obj)
2. static void invokeAndWait(Runnable obj) throws InterruptedException, InvocationTargetException
 Here, obj is a Runnable object that will have its run( ) method called by the event dispatching thread
 The invokeLater() method returns immediately, without waiting for the event dispatcher thread to execute
the code.
 The invokeAndWait() method is just like invokeLater(), except that invokeAndWait ()doesn't return until the
event-dispatching thread has executed the specified code.
Event Handling
 The preceding example showed the basic form of a Swing program, but it left out one
important part: event handling.
 The event handling mechanism used by Swing is the same as that used by the AWT.
 This approach is called the delegation event model.
 In many cases, Swing uses the same events as does the AWT, and these events are packaged in java.awt.event.
Events specific to Swing are stored in javax.swing.event.
 Although events are handled in Swing in the same way as they are with the AWT, it is still useful to work through a
simple example.
Elements needed to create a GUI
• The four principal elements needed to create a GUI include:
 Components - A component is a visual object containing text or graphics that can respond to
keyboard or mouse inputs. Examples of components include buttons, labels, text boxes,
check boxes, and lists. All components inherit a common set of methods, the most common
of which is paint.
 Container - A container is a graphical object that can hold components or other containers.
The most important type of container is a JFrame.
 Layout Manager - A layout manager is automatically associated with each container when it
is created, but the layout manager can be changed. Examples include BorderLayout,
BoxLayout, GridLayout.
 Event Handlers - Events, such as the click of a mouse, are handled by creating listener classes
which implement listener interfaces. The standard listener interfaces are in java.awt.event.
Step to perform event handling in GUI Application
1. Create a window(container) in which to display things—usually a JFrame (for an
application)
2. Create some Components, such as buttons, Text areas, panels, etc.
3. Use the setLayout(LayoutManager manager) method to specify a layout manager
4. Add the components to the Container (window), according to the chosen layout
manager
5. Write some Listeners and attach them to your Components
 Interacting with a Component causes an Event to occur
 A Listener gets a message when an interesting event occurs, and
executes some code to deal with it
6. Display your window

84
Event Handling
// Handle an event in a Swing program. // Add action listener for Beta.
import java.awt.*; jbtnBeta.addActionListener(new ActionListener() {public void
import java.awt.event.*; actionPerformed(ActionEvent ae)
{jlab.setText("Beta was pressed.");
import javax.swing.*;
}});
class EventDemo {
JLabel jlab;
// Add the buttons to the content pane.
EventDemo() {
jfrm.add(jbtnAlpha);
// Create a new JFrame container.
jfrm.add(jbtnBeta);
JFrame jfrm = new JFrame("An Event Example"); // Create a text-based label.
// Specify FlowLayout for the layout manager. jlab = new JLabel("Press a button.");
jfrm.setLayout(new FlowLayout()); // Add the label to the content pane.
// Give the frame an initial size. jfrm.add(jlab);
jfrm.setSize(320, 100); // Display the frame.
// Terminate the program when the user closes the application. jfrm.setVisible(true);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
// Make two buttons. public static void main(String args[]) {
JButton jbtnAlpha = new JButton("Alpha"); // Create the frame on the event dispatching thread.
JButton jbtnBeta = new JButton("Beta"); SwingUtilities.invokeLater(new Runnable() {
// Add action listener for Alpha. public void run() { new EventDemo();
jbtnAlpha.addActionListener(new ActionListener() { public void }
actionPerformed(ActionEvent ae) });
{ jlab.setText("Alpha was pressed."); }
}
} });
Painting in Swing :Painting Fundamentals

 Swing allows you write directly into the display area of a frame, panel, or one of Swing’s other components, such as JLabel.
 To write output directly to the surface of a component, you will use one or more drawing methods defined by the AWT, such as drawLine()
or drawRect().
Painting Fundamentals
Swing's approach to painting is built on the original AWT-based mechanism.

 The AWT class Component defines a method called paint( ) that is used to draw output directly to the surface of a component.
 In most of the time paint( ) method is not directly called by your program.
 Rather, paint( ) is called by the run-time system whenever a component must be rendered(displayed).
 Because JComponent inherits Component, all Swing’s lightweight components inherit the paint( ) method.
 However, you will not override it to paint directly to the surface of a component.
 The reason is that Swing uses a bit more sophisticated approach to painting that involves three distinct methods: paintComponent( ), paintBorder( ),
and paintChildren( ).
 These methods paint the indicated portion of a component and divide the painting process into its three distinct, logical actions.
 To paint to the surface of a Swing component, you will create a subclass of the component and then override its paintComponent( ) method. This is the
method that paints the interior of the component.
 When overriding paintComponent( ), the first thing you must do is call super.paintComponent( ), so that the superclass portion of the painting process
takes place.
 After that, write the output that you want to display.
The paintComponent( ) method is :
protected void paintComponent(Graphics g)
The parameter g is the graphics context to which output is written
 To cause a component to be painted under program control, call repaint( ).
 Inside the overridden paintComponent( ), you will draw the stored output.
Painting in Swing :Painting Fundamentals

 In order to draw things on a Swing component, you need to define a class that extends Jpanel and overrides its paintComponent()
method to specify what to draw.
 The paintComponent method takes one parameter of type Graphics.
 A Graphics object remembers a collection of settings for drawing images and text, such as the font you set or the current color.
The signature of the paintComponent method is as follows:
protected void paintComponent(Graphics g)
 This method, defined in the JComponent class, is invoked whenever a component is first displayed or redisplayed.
 paintComponent() overrides the method of the same name in the super class of JPanel.
 Call the super class method super.paintComponent( g ) before doing custom painting.
 If you forget to do this the background color will be the default color.
class MYyPanel extends JPanel
{
public void paintComponent(Graphics g)
{ super.paintComponent(g);
// code for drawing
}
 Never call the paintComponent method yourself. It is called automatically whenever a part of your application needs to be redrawn, and
you should not interfere with this automatic process
 The argument to paintComponent () is a Graphics object that gives you a surface to draw on, which will end up on the screen.
Note: Instead of extending Jpanel, some programmers prefer to extend the JComponent class.
In that case, To draw on a swing component, you define a class that extends JComponent and override the paintComponent method in that
class.
Compute the Paintable Area
 When drawing to the surface of a component, you must be careful to restrict your output to
the area that is inside the border.
 Although Swing automatically clips any output that will exceed the boundaries of a
component.
 Insets specify a container’s margins
 Insets are described by an Insets object, which has four public int fields: top, bottom, left,
and right.
 You normally don’t need to worry about the insets; the container sets them automatically,
taking into account extras like the menu bar that may appear at the top of a frame.
 To obtain the border width, call getInsets( ), shown here:
Insets getInsets( )
 This method is defined by Container and overridden by JComponent.
 You can obtain the width and height of the component by calling getWidth( ) and
getHeight( ) on the component.
import java.awt.*;
// Demonstrate painting directly onto a panel.
import javax.swing.*;
class PaintDemo {
import java.util.*;
PaintDemo() {
// This class extends JPanel.
// Create a new JFrame container.
class PaintPanel extends JPanel {
PaintPanel() { JFrame jfrm = new JFrame("Some Geometric Figures");
this.setBackground (Color.cyan); // Give the frame an initial size.
} jfrm.setSize(500, 400);
// Override the paintComponent() method. // Terminate the program when the user closes the
public void paintComponent (Graphics g) application.
{ jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
super.paintComponent (g); // Create the panel that will be painted.
g.drawRect (50,50,50,50); PaintPanel pp = new PaintPanel();
g.drawString ("Square", 50, 115); // Add the panel to the content pane.
g.drawOval (200,50,50,50); jfrm.add(pp);
g.drawString ("Circle", 200, 115); // Display the frame.
g.drawRoundRect (350,50,75,50,20,20); jfrm.setVisible(true);
g.drawString ("Rectangle", 350, 115); }
// Draw a line across the middle:
public static void main(String args[]) {
g.drawLine (0,150,500,150);
// Create the frame on the event dispatching thread.
g.fillRect (50,200,50,50);
SwingUtilities.invokeLater(new Runnable() {
g.drawString ("Square", 50, 265);
public void run() {
g.fillOval (200,200,50,50);
g.drawString ("Circle", 200, 265); new PaintDemo();
g.fillRoundRect (350,200,75,50,20,20); }
g.drawString ("Rectangle", 350, 265); });
} }
} }
Exploring Swing
The Swing components provide rich functionality and allow a
high level of customization
These components are all lightweight, which means that they
are all derived from JComponent.
Some of the Swing component classes are:
Swing component classes : JLabel and ImageIcon

JLabel
 A label is a display area for a short text, an image, or both
 JLabel is Swing's easiest-to-use component.
 JLabel can be used to display text and/or an icon.
 It is a passive component in that it does not respond to userinput.
Constructors defined in JLabel:
1. JLabel(Icon icon)
2. JLabel(String str)
3. JLabel(String str, Icon icon, int align)
 Where, str and icon are text and icon used for label and align argument specifies the
horizontal alignment of the text and/or icon within the dimension of the label.
ImageIcon
 An icon is a small picture, typically displayed as part of a GUI component such as a label or
button.
 In Java, an icon is an instance of the ImageIcon class, and is constructed with a digital picture
file, such as a .gif (Graphics Interchange Format) , .jpg( Joint Photographic Experts Group)
or .png (Portable Network Graphics).
 The class ImageIcon is used to convert a picture file to a Swing icon
ImageIcon’s Constructor
 ImageIcon NameOfImageIcon = new ImageIcon("PictureFileName");
Example:
 ImageIcon pic = new ImageIcon(“pic.gif”);
 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.
 The icon and text associated with the label can be obtained by following
methods:
1. Icon getIcon()
2. String getText()
 The icon and Text associated with a label can be set by following
methods:
1. void setIcon(Icon icon)
2. void setText(String str)
setText() method can be used to change the text of label.
 ImageIcon class implements the following methods:
1. int getIconHeight() Returns the height of the icon in pixels.
2. int getIconWidth() Returns the width of the icon in pixels.
Example
// Demonstrate JLabel and ImageIcon. public static void main(String[] args) {
import java.awt.*; // Create the frame on the event
dispatching thread.
import javax.swing.*;
SwingUtilities.invokeLater(
public class JLabelDemo { new Runnable() {
public JLabelDemo() { public void run() {
// Set up the JFrame. new JLabelDemo();
JFrame jfrm = new JFrame("JLabelDemo"); }
jfrm.setLayout(new FlowLayout()); }
);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
jfrm.setSize(260, 210); }
// Create an icon.
ImageIcon ii = new ImageIcon("jamal.png");
// Create a label.
JLabel jl = new JLabel("Jamal Mohamed College", ii, JLabel.CENTER);
// Add the label to the content pane.
jfrm.add(jl);
// Display the frame.
jfrm.setVisible(true);
}

JTextField
A text field is a component that allows the user to enter a single line of text.
 The JTextField class is used to create text fields.
 JTextField allows editing/displaying of a single line of text.
 (ie) JTextField is an area in which the user may type a single line of input from the keyboard.
 Derived from JTextComponent.

 A text area is like a text field that can accept multiple lines of input.
Constructors:
JTextField(int cols)
JTextField(String str , int cols)
JTextField(String str)
Where, str is the string to be initially presented, col represents number of columns in text field.
If no string is specified, text field is initially empty.
Example:
JTextField name = new JTextField( "Enter name here.", 30);
• String getText() method - obtain the text currently in the text field.
JTextField Demo Program

// Demonstrate JTextField.
import java.awt.*; When the user presses Enter in a JTextField ,
import java.awt.event.*; an action event is generated. This is handled by
import javax.swing.*;
displaying the text in the status window.
public class JTextFieldDemo {
// Handle action events.
public JTextFieldDemo() { jtf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// Show text when user presses ENTER.
// Set up the JFrame. jlab.setText(jtf.getText());
JFrame jfrm = new JFrame("JTextFieldDemo"); }
jfrm.setLayout(new FlowLayout()); });
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Display the frame.
jfrm.setSize(260, 120);
jfrm.setVisible(true);
}
// Add a text field to content pane. public static void main(String[] args) {
JTextField jtf = new JTextField(15);
jfrm.add(jtf); // Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(
new Runnable() {
// Add a label.
public void run() {
JLabel jlab = new JLabel(); new JTextFieldDemo();
jfrm.add(jlab); }
}
);
}
}
Buttons
 A push button or a button is a component that contains a label and that generates an event when it is pressed.
 Swing defines four types of buttons: JButton, JToggleButton, JCheckBox, and JRadioButton.
 All are subclasses of the AbstractButton class, which extends JComponent.
 AbstractButton contains many methods that allow you to control the behavior of buttons.

• Methods to control behaviour of buttons:


void setDisabledIcon(Icon di)
void setPressedIcon(Icon pi)
void setSelectedIcon(Icon si)
void setRolloverIcon(Icon ri)

here, di,pi,si,ri icon would be displayed when button is disabled, pressed, selected, mouse is positioned over a button.

 The text associated with a button can be read and written using,
 String getText( )
 void setText(String str)
The JButton Class
 The JButton represents a clickable button that can have a text label, an image label, or both.
 It generates an ActionEvent for each mouse click.
 In addition to text, JButtons can also display icons.
Constructors:
JButton(Icon icon)
JButton(String str)
JButton(String str,Icon icon)
 Using ActionEvent object passed to actionPerformed() method , action command associated with
button can be obtained.
 String getActionCommand() - The action command identifies the pressed button.
 void setActionCommand(String str)- Used to set the action command
 When using two or more buttons within same app, the action command helps to determine which
button has been pressed.
 Unlike Button, Jbutton provides an ability to add any of the component inside a button itself using
 Add(Component comp) method
Example: The following example displays four push buttons and a text field. Each button displays an icon
that represents the flag of a country. When a button is pressed, the name of that country is displayed
in the text field.
ImageIcon Japan = new ImageIcon("Japan.png");
// Demonstrate an icon-based JButton.
jb = new JButton(Japan);
import java.awt.*;
jb.setActionCommand("Japan");
import java.awt.event.*;
jb.addActionListener(this);
import javax.swing.*;
public class JButtonDemo implements ActionListener {
jfrm.add(jb);
JLabel jlab; // Create and add the label to content pane.
public JButtonDemo() { jlab = new JLabel("Choose a Country");
// Set up the JFrame. jfrm.add(jlab);
JFrame jfrm = new JFrame("JButtonDemo"); // Display the frame.
jfrm.setLayout(new FlowLayout()); jfrm.setVisible(true);
Jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
jfrm.setSize(300, 250); // Handle button events.
// Add buttons to content pane.
public void actionPerformed(ActionEvent ae) {
ImageIcon India = new ImageIcon("India.png");
jlab.setText("You selected " +
JButton jb = new JButton(India);
ae.getActionCommand());
jb.setActionCommand("India");
}
jb.addActionListener(this);
public static void main(String[] args) {
jfrm.add(jb);
ImageIcon Saudi= new ImageIcon("Saudi.png");
// Create the frame on the event dispatching
thread.
jb = new JButton(Saudi);
SwingUtilities.invokeLater(
jb.setActionCommand("Saudi");
jb.addActionListener(this); new Runnable() {
jfrm.add(jb); public void run() {
ImageIcon Srilanka = new ImageIcon("Srilanka.png"); new JButtonDemo();
jb = new JButton(Srilanka); }
jb.setActionCommand("Srilanka"); }
jb.addActionListener(this); );
jfrm.add(jb); }
Check Boxes
 A check box is a control that is used to turn an option on or off.
 It consists of a small box that can either contain a check mark or not.
 There is a label associated with each check box that describes what option the box represents. You change the state of a check box
by clicking on it.
 The JCheckBox class provides the functionality of a check box. Its immediate superclass is JToggleButton, which provides
support for two-state buttons, as just described. 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. Other constructors let you specify the initial selection state of
the button and specify an icon.
 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.
 The following example illustrates check boxes. It displays four check boxes and a label.
 When the user clicks a check box, an ItemEvent is generated. Inside the itemStateChanged( ) method, getItem( ) is called to obtain
a reference to the JCheckBox object that generated the event. Next, a call to isSelected( ) determines if the box was selected or
cleared. The getText( ) method gets the text for that check box and uses it to set the text inside the label
// Demonstrate JCheckbox.
// Create the label and add it to the content pane.
import java.awt.*;
jlab = new JLabel("Select languages");
import java.awt.event.*;
jfrm.add(jlab);
import javax.swing.*;

// Display the frame.


public class JCheckBoxDemo implements ItemListener {
JLabel jlab; jfrm.setVisible(true);
}
public JCheckBoxDemo() {
// Handle item events for the check boxes.
// Set up the JFrame. public void itemStateChanged(ItemEvent ie) {
JFrame jfrm = new JFrame("JCheckBoxDemo"); JCheckBox cb = (JCheckBox)ie.getItem();
jfrm.setLayout(new FlowLayout());
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); if(cb.isSelected())
jfrm.setSize(250, 100); jlab.setText(cb.getText() + " is selected");
else
// Add check boxes to the content pane. jlab.setText(cb.getText() + " is cleared");
JCheckBox cb = new JCheckBox("C"); }
cb.addItemListener(this);
jfrm.add(cb); public static void main(String[] args) {

cb = new JCheckBox("C++");
// Create the frame on the event dispatching thread.
cb.addItemListener(this);
SwingUtilities.invokeLater(
jfrm.add(cb);
new Runnable() {
public void run() {
cb = new JCheckBox("Java");
new JCheckBoxDemo();
cb.addItemListener(this);
}
jfrm.add(cb);
}
cb = new JCheckBox("Perl"); );
cb.addItemListener(this); }
jfrm.add(cb); }
Combo Boxes or 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 dropdown 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. Other constructors are available.
 JComboBox uses the ComboBoxModel. Mutable combo boxes (those whose entries
can be changed) use the MutableComboBoxModel.
 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)
 Here, obj is the object to be added to the combo box. This method must be used only
with mutable combo boxes.
JComboBox
 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. Often, it is sufficient to simply listen for action events, but both event
types are available for your use.
 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.

The following example demonstrates the combo box. The combo box
contains entries for "India", "Saudi", "Srilanka", "Japan". When a
country is selected, an icon-based label is updated to display it.
Example: // Handle selections.
// Demonstrate JComboBox. jcb.addActionListener(new ActionListener() {
import java.awt.*; public void actionPerformed(ActionEvent ae)
import java.awt.event.*; {
String s = (String) jcb.getSelectedItem();
import javax.swing.*; jlab.setIcon(new ImageIcon(s + ".png"));
}
public class JComboBoxDemo { });

// Display the frame.


String countries[] = { "India", "Saudi", "Srilanka", "Japan" }; jfrm.setVisible(true);
}
public JComboBoxDemo() {
public static void main(String[] args) {
// Set up the JFrame.
// Create the frame on the event dispatching
JFrame jfrm = new JFrame("JCombBoxDemo"); thread.
jfrm.setLayout(new FlowLayout()); SwingUtilities.invokeLater(
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); new Runnable() {
public void run() {
jfrm.setSize(400, 250);
new JComboBoxDemo();
}
// Instantiate a combo box and add it to the content pane. }
JComboBox<String> jcb = new JComboBox<String>(countries); );
}
jfrm.add(jcb);
}

// Create a label and add it to the content pane.


JLabel jlab = new JLabel(new ImageIcon("India.png"));
jfrm.add(jlab);
JList
 In Swing, the basic list class is called JList. It supports the selection of one or more items from a list. Although the list
often consists of strings, it is possible to create a list of just about any object that can be displayed. JList is so widely
used in Java that it is highly unlikely that you have not seen one before.
 In the past, the items in a JList were represented as Object references. However,
beginning with JDK 7, JList was made generic and is now declared like this:
class JList<E>
 Here, E represents the type of the items in the list.
 JList provides several constructors. The one used here is
JList(E[ ] items)
 This creates a JList that contains the items in the array specified by items.
 JList is based on two models. The first is ListModel. This interface defines how access to the list data is achieved. The
second model is the ListSelectionModel interface, which defines methods that determine what list item or items are
selected.
 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. It also makes it easy to change the number of entries
in a list without having to change the size of the JList component.
 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)
 Here, le is a reference to the event. Although ListSelectionEvent does provide some methods of its own,
normally you will interrogate the JList object itself to determine what has occurred. 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
 The default, multiple-interval selection, lets the user select multiple ranges of items within a list. With
single-interval selection, the user can select one range of items. With single selection, the user can select
only a single item. 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.
The following program demonstrates a simple JList, which holds a list of
cities. Each time a city is selected in the list, a ListSelectionEvent is
generated, which is handled by the valueChanged( ) method defined by
ListSelectionListener. It responds by obtaining the index of the selected item
and displaying the name of the selected city in a label.
// Demonstrate JList. // Add selection listener for the list.
import javax.swing.*; jlst.addListSelectionListener(new ListSelectionListener() {
import javax.swing.event.*; public void valueChanged(ListSelectionEvent le) {
import java.awt.*; // Get the index of the changed item.
import java.awt.event.*; int idx = jlst.getSelectedIndex();
public class JListDemo {
// Create an array of cities. // Display selection, if item was selected.
String Cities[] = { "New York", "Chicago", "Los Angeles",
if(idx != -1)
"London", "Paris“, "New Delhi", "Hong Kong",
jlab.setText("Current selection: " + Cities[idx]);
"Tokyo", "Sydney" };
public JListDemo() {
else // Othewise, reprompt.
jlab.setText("Choose a City");
// Set up the JFrame. }
JFrame jfrm = new JFrame("JListDemo"); });
jfrm.setLayout(new FlowLayout()); // Add the list and label to the content pane.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jfrm.add(jscrlp);
jfrm.setSize(200, 200); jfrm.add(jlab);
// Display the frame.
// Create a JList. jfrm.setVisible(true);
JList<String> jlst = new JList<String>(Cities);
}
public static void main(String[] args) {
// Set the list selection mode to single-selection.
jlst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(
// Add the list to a scroll pane. new Runnable() {
JScrollPane jscrlp = new JScrollPane(jlst); public void run() {
new JListDemo();
// Set the preferred size of the scroll pane. }
jscrlp.setPreferredSize(new Dimension(120, 90)); }
);
// Make a label that displays the selection. }
JLabel jlab = new JLabel("Choose a City");
}
Tabbed Panes

 JTabbedPane encapsulates a tabbed pane. It manages a set of components by linking


them with tabs. Selecting a tab causes the component associated with that tab to come
to the forefront.
 A tabbed pane is a container that groups components such as buttons, checkboxes, and
text fields on multiple panels.
 Each panel has a title and a tab that the end user clicks to view the panel contents.
 (ie) A tabbed pane is a container with one or more components. Only one component
can be active (visible) at a time.
 It manages a set of components by linking them with tabs.
 The JTabbedPane class is a component that allows the user switch between a group of
components by clicking on a tab with a given title and/or icon.
 JTabbedPane defines three constructors. We will use its default constructor, which creates an empty control with
the tabs positioned across the top of the pane. The other two constructors let you specify the location of the tabs,
which can be along any of the four sides. JTabbedPane uses the SingleSelectionModel model.
 Tabs are added by calling addTab( ). Here is one of its forms:
void addTab(String name, Component comp)
 Here, name is the name for the tab, and comp is the component that should be added to the tab. Often, the
component added to a tab is a JPanel that contains a group of related components. This technique allows a tab to
hold a set of components.
 The general procedure to use a tabbed pane is outlined here:
1. Create an instance of JTabbedPane.
2. Add each tab by calling addTab( ).
3. Add the tabbed pane to the content pane.
 The following example illustrates a tabbed pane. The first tab is titled "Cities" and contains four buttons. Each
button displays the name of a city. The second tab is titled "Colors" and contains three check boxes. Each check
box displays the name of a color. The third tab is titled "Flavors" and contains one combo box. This enables the
user to select one of three flavors.
// Make the panels that will be added to the tabbed pane.
// Demonstrate JTabbedPane. class CitiesPanel extends JPanel {
import javax.swing.*;
public CitiesPanel() {
import java.awt.*; JButton b1 = new JButton("New York");
public class JTabbedPaneDemo { add(b1);
public JTabbedPaneDemo() { JButton b2 = new JButton("London");
// Set up the JFrame. add(b2);
JFrame jfrm = new JFrame("JTabbedPaneDemo"); JButton b3 = new JButton("Hong Kong");
add(b3);
jfrm.setLayout(new FlowLayout());
JButton b4 = new JButton("Tokyo");
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); add(b4);
jfrm.setSize(400, 200); }
// Create the tabbed pane. }
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("Cities", new CitiesPanel()); class ColorsPanel extends JPanel {
jtp.addTab("Colors", new ColorsPanel());
public ColorsPanel() {
jtp.addTab("Flavors", new FlavorsPanel()); JCheckBox cb1 = new JCheckBox("Red");
jfrm.add(jtp); add(cb1);
// Display the frame. JCheckBox cb2 = new JCheckBox("Green");
jfrm.setVisible(true); add(cb2);
} JCheckBox cb3 = new JCheckBox("Blue");
add(cb3);
public static void main(String[] args) {
}
// Create the frame on the event dispatching thread. }
SwingUtilities.invokeLater(
new Runnable() { class FlavorsPanel extends JPanel {
public void run() {
new JTabbedPaneDemo(); public FlavorsPanel() {
JComboBox<String> jcb = new JComboBox<String>();
}
jcb.addItem("Vanilla");
} jcb.addItem("Chocolate");
); jcb.addItem("Strawberry");
} add(jcb);
} }
Output from the tabbed pane example is shown in the following three illustrations:
Scroll Panes
 A scroll pane is a GUI element that enables the user to scroll another GUI component both horizontally
and vertically by using a scroll bar.
 JScrollPane is a lightweight container that automatically handles the scrolling of another
component.
 The component being scrolled can be either an individual component, such as a table, or a group of
components contained within another lightweight container, such as a JPanel. In either case, if the
object being scrolled is larger than the viewable area, horizontal and/or vertical scroll bars are
automatically provided, and the component can be scrolled through the pane.
 Because JScrollPane automates scrolling, it usually eliminates the need to manage individual scroll
bars.
 The viewable area of a scroll pane is called the viewport. It is a window in which the component being
scrolled is displayed. Thus, the viewport displays the visible portion of the component being scrolled.
The scroll bars scroll the component through the viewport.
 In its default behavior, a JScrollPane will dynamically add or remove a scroll bar as needed. For
example, if the component is taller than the viewport, a vertical scroll bar is added. If the component
will completely fit within the viewport, the scroll bars are removed.
 JScrollPane defines several constructors. The one used in this chapter is shown here:
JScrollPane(Component comp)
• The component to be scrolled is specified by comp. Scroll bars are automatically displayed when
the content of the pane exceeds the dimensions of the viewport.
• Here are the steps to follow to use a scroll pane:
1. Create the component to be scrolled.
2. Create an instance of JScrollPane, passing to it the object to scroll.
3. Add the scroll pane to the content pane.
• The following example illustrates a scroll pane. First, a JPanel object is created, and 400 buttons are
added to it, arranged into 20 columns. This panel is then added to a scroll pane, and the scroll pane is
added to the content pane. Because the panel is larger than the viewport, vertical and horizontal scroll
bars appear automatically. You can use the scroll bars to scroll the buttons into view.
// Demonstrate JScrollPane. // Create the scroll pane.
import java.awt.*; JScrollPane jsp = new JScrollPane(jp);
import javax.swing.*;
// Add the scroll pane to the content pane.
// Because the default border layout is used,
public class JScrollPaneDemo { // the scroll pane will be added to the center.
jfrm.add(jsp, BorderLayout.CENTER);
public JScrollPaneDemo() {
// Display the frame.
jfrm.setVisible(true);
// Set up the JFrame. Use the default BorderLayot.
}
JFrame jfrm = new JFrame("JScrollPaneDemo");
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); public static void main(String[] args) {
jfrm.setSize(400, 400);
// Create the frame on the event dispatching thread.
// Create a panel and add 400 buttons to it. SwingUtilities.invokeLater(
new Runnable() {
JPanel jp = new JPanel();
public void run() {
jp.setLayout(new GridLayout(20, 20)); new JScrollPaneDemo();
}
int b = 0; }
for(int i = 0; i < 20; i++) { );
for(int j = 0; j < 20; j++) { }
}
jp.add(new JButton("Button " + b));
++b;
}
}
Understanding Layout Managers
 The term layout refers to the positioning and sizing of components
 A layout manager (is an object that) determines the manner in which components are arranged
in a container.
 (ie) A layout manager automatically arranges your controls within a window instead of laying out
your controls by hand.
 A layout manager is an instance of any class that implements the LayoutManager interface.
 There are several predefined layout managers defined in the Java standard class library:

Flow Layout
Border Defined in the AWT
Layout
Card Layout
Grid Layout

Box Layout
Defined in Swing
Overlay Layout
 Every Container has a layout manager
 The default layout for a JPanel is FlowLayout
 The default layout for a JApplet is BorderLayout
 You can set the layout manager explicitly
 The layout manager is set by the setLayout( ) method.
 The setLayout( ) method has the following general form:
void setLayout(LayoutManager layoutObj)
Example:
setLayout(new FlowLayout());
setLayout(new BorderLayout());
or
FlowLayout lo = new FlowLayout();
setLayout(lo);
FlowLayout
 FlowLayout places components sequentially on a row from left to right in the order added and then
floes (moves) to the next row.
 Rows are created as needed to accommodate all of the components.
 Components placement depends on the current size of the container.
 When the container is resized the components are automatically resized.
 Each row of components is centered horizontally in the window by default, but could also be aligned
left or right
 The horizontal and vertical gaps between the components can be explicitly set also.
• Constructors:
(1) FlowLayout()
Creates a FlowLayout object with center alignment and horizontal and vertical gaps of five pixel each.
(2) FlowLayout(int alignment)
Constructs a FlowLayout object with the specified alignment and a default gap of five pixels in each
direction.
(3) FlowLayout(int alignment, int hGap, int vGap)
Constructs a FlowLayout object with the specified alignment and gaps
Example:
import java.awt.*;
import javax.swing.*;

public class MyFlowLayout{

MyFlowLayout(){
JFrame f=new JFrame();

JButton b1=new JButton("1");


JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");

f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setTitle("Flow Layout Demo");
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment

f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}
Border Layout
 BorderLayout places components according to five areas: "North", "South", "East", "West" and "Center“.
 Each area displays one component. At most five components can be added
 BorderLayout will automatically resize the Component(s) (particularly in the Center) to fill the available space.
Constructors:
(1) BorderLayout()
Creates a BorderLayout object with center alignment and horizontal and vertical gaps of zero pixels each.
(2) BorderLayout(int hGap, int vGap)
Constructs a BorderLayout object with center alignment and the specified alignment and gaps
 BorderLayout defines the following constants that specify the regions:
BorderLayout.CENTER BorderLayout.SOUTH
BorderLayout.EAST BorderLayout.WEST
BorderLayout.NORTH.

North

West Center East

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

public class Border {


Border(){
JFrame f=new JFrame();
f.setTitle("Border Layout Demo");

JButton b1=new JButton("NORTH");;


JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;

f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);

f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
Grid Layout
 A grid layout presents a container’s components in a rectangular grid of rows and columns like a
spreadsheet.
 One component is placed in each cell of the grid, and all cells have the same size.
 As components are added to the container, they fill the grid from left-to-right and top-to-bottom (by
default).
 The size of each cell is determined by the overall size of the container.
Constructors:
1. GridLayout()
Creates a new GridLayout with one row, and unlimited number of columns, and no horizontal and
vertical gaps between cells.
2. GridLayout(int rows, int cols)
Creates a new GridLayout with the number of rows and columns as specified.
3. GridLayout(int rows, int cols, int hgap, int vgap)
Creates a new GridLayout with number of rows, columns, horizontal, and vertical gaps as specified.
import java.awt.*;
import javax.swing.*;
public class MyGridLayout{
MyGridLayout(){
JFrame f=new JFrame();
f.setTitle("Grid Layout Demo");

JButton b1=new JButton("1");


JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
f.setLayout(new GridLayout(3,3));
//creating grid layout of 3 row and 3 columns
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}
CardLayout
 In Swing, by default, Layout is CardLayout.
 In CardLayout, components overlap with each other. Hence, if we want to use multiple components, we have to
use other Layouts like FlowLayout, GridLayout etc.
 (ie) The CardLayout is used to lay out the components in the form of a deck of cards where only one card is visible
at a time.
 (ie) The Card Layout manager helps you manage two or more components that share the same display space.
When using Card Layout, you need to provide a way to let the user choose between the components.
 It is similar to tabbed panes, but a tabbed pane provides its own GUI, so using a tabbed pane is simpler than using
Card Layout.
Constructors of CardLayout class:
CardLayout(): creates a card layout with zero horizontal and vertical gap.
CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap.
Commonly used methods of CardLayout class:
public void next(Container parent): is used to flip to the next card of the given container.
public void previous(Container parent): is used to flip to the previous card of the given container.
public void first(Container parent): is used to flip to the first card of the given container.
public void last(Container parent): is used to flip to the last card of the given container.
public void show(Container parent, String name): is used to flip to the specified card with the given name.
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
public static void main(String[] args) {
CardLayoutExample
public class CardLayoutExample extends JFrame implements ActionListener{
cl=new CardLayoutExample();
CardLayout card;
cl.setSize(200,200);
JButton b1,b2,b3;
cl.setVisible(true);
Container c;
CardLayoutExample(){
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
c=getContentPane();
}
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
c.setLayout(card);

b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);c.add("b",b2);c.add("c",b3);

}
public void actionPerformed(ActionEvent e) {
card.next(c);
}
BoxLayout

 A box layout organizes components either horizontally (in one row) or vertically (in one column).
 Components are placed top-to-bottom or left-to-right in the order in which they are added to the
container.
• For this purpose, BoxLayout provides four constants.
1. public static final int X_AXIS
2. public static final int Y_AXIS
3. public static final int LINE_AXIS
4. public static final int PAGE_AXIS.
Constructor of BoxLayout class:
BoxLayout(Container c, int axis): creates a box layout that arranges the components with the given axis.
• Note: BoxLayout class is found in javax.swing package.
import java.awt.*;
import javax.swing.*;

public class BoxLayoutTest {


BoxLayoutTest()
{ JFrame frame = new JFrame("BoxLayout Test");
frame.setSize(300,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BoxLayout boxLayout = new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS); // top to bottom
frame.setLayout(boxLayout);
frame.add(new JButton("Button 1"));
frame.add(new JButton("Button 2"));
frame.add(new JButton("Button 3"));
frame.setVisible(true);
}
public static void main(String[] args) {
new BoxLayoutTest();
}
}

You might also like