Java - Mca 2021 - Unit 5
Java - Mca 2021 - Unit 5
Checkbox Generates item events when the check box is selected or deselected
Choice Generates item events when the choice is changed
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
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
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
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.
AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.
View
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).
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”);
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.
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.*;
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 { });
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.*;
MyFlowLayout(){
JFrame f=new JFrame();
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
South
import java.awt.*;
import javax.swing.*;
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");
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.*;