Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java Unit-5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 60

UNIT - 5

Adapter Classes
Adapter Class Listener Interface
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener

Java provides a special feature, called an adapter class, that can simplify the creation of event handlers in certain
situations. An adapter class provides an empty implementation of all methods in an event listener interface.
Adapter classes are useful when you want to receive and process only some of the events that are handled by a
particular event listener interface. You can define a new class to act as an event listener by extending one of the
adapter classes and implementing only those events in which you are interested. For example, the
MouseMotionAdapter class has two methods, mouseDragged( ) and mouseMoved( ), which are the methods
defined by the MouseMotionListener interface. If you were interested in only mouse drag events, then you
could simply extend MouseMotionAdapter and override mouseDragged( ). The empty implementation of
mouseMoved( ) would handle the mouse motion events for you.
The following example demonstrates an adapter. It displays a message in the status bar of an applet viewer or
browser when the mouse is clicked or dragged. However, all other mouse events are silently ignored. The
program has three classes. AdapterDemo extends Applet. Its init( ) method creates an instance of
MyMouseAdapter and registers that object to receive notifications of mouse events. It also creates an instance
of MyMouseMotionAdapter and registers that object to receive notifications of mouse motion events. Both of
the constructors take a reference to the applet as an argument. MyMouseAdapter extends MouseAdapter and
overrides the mouseClicked( ) method. The other mouse events are silently ignored by code inherited from the
MouseAdapter class. MyMouseMotionAdapter extends MouseMotionAdapter and overrides the
mouseDragged( ) method. The other mouse motion event is silently ignored by code inherited from the
MouseMotionAdapter class.
Note that both of the event listener classes save a reference to the applet. This information is provided as an
argument to their constructors and is used later to invoke the showStatus( ) method.
// Demonstrate an adapter.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AdapterDemo" width=300 height=100>
</applet>
*/
public class AdapterDemo extends Applet {
public void init() {
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
}
}
class MyMouseAdapter extends MouseAdapter {
AdapterDemo adapterDemo;
public MyMouseAdapter(AdapterDemo adapterDemo) {
this.adapterDemo = adapterDemo;
1
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
adapterDemo.showStatus("Mouse clicked");
}
}
class MyMouseMotionAdapter extends MouseMotionAdapter {
AdapterDemo adapterDemo;
public MyMouseMotionAdapter(AdapterDemo adapterDemo) {
this.adapterDemo = adapterDemo;
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
adapterDemo.showStatus("Mouse dragged");
}
}
Inner Classes
// Inner class demo.
import java.applet.*;
import java.awt.event.*;
/*
<applet code="InnerClassDemo" width=200 height=100>
</applet>
*/
public class InnerClassDemo extends Applet {
public void init() {
addMouseListener(new MyMouseAdapter());
}
class MyMouseAdapter extends MouseAdapter {
public void mousePressed(MouseEvent me) {
showStatus("Mouse Pressed");
}
}
}
Anonymous Inner Classes
An anonymous inner class is one that is not assigned a name. This section illustrates how an anonymous inner
class can facilitate the writing of event handlers. Consider the applet shown in the following listing. As before,
its goal is to display the string “Mouse Pressed” in the status bar of the applet viewer or browser when the mouse
is pressed.
// Anonymous inner class demo.
import java.applet.*;
import java.awt.event.*;
/*
<applet code="AnonymousInnerClassDemo" width=200 height=100>
</applet>
*/
public class AnonymousInnerClassDemo extends Applet {
public void init() {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
2
showStatus("Mouse Pressed");
}
});
}
}
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It runs
inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os etc.
Drawback of Applet
o Plugin is required at client browser to execute applet.

Hierarchy of Applet

As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is the
subclass of Component.
Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

Lifecycle methods for Applet:


java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to start the
Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.

3
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be
used for drawing oval, rectangle, arc etc.
Who is responsible to manage the life cycle of an applet?
Java Plug-in software.
How to run an Applet?
There are two ways to run an applet
1. By html file.
2. By appletViewer tool (for testing purpose).
Simple example of Applet by html file:
To execute the applet by html file, create an applet and compile it. After that create an html file and place the
applet code in html file. Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}

Note: class must be public because its object is created by Java Plugin software that resides on the browser.

myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>

Simple example of Applet by appletviewer tool:


To execute the applet by appletviewer tool, create an applet that contains applet tag in comment and compile it.
After that run it by: appletviewer First.java. Now Html file is not required but it is for testing purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java

4
Example:
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
String str;
public void init()
{
Str=”hello”;
}
public void paint(Graphics g)
{
g.drawString(str,150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java

Displaying Graphics in Applet


java.awt.Graphics class provides many methods for graphics programming.
Commonly used methods of Graphics class:
1. public abstract void drawString(String str, int x, int y): is used to draw the specified string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified width and
height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the default
color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the specified
width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the default color
and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the points(x1,
y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw the
specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used draw
a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used to fill a
circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color to the specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font to the specified font.

Example of Graphics in applet:


import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
5
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>
Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose, Applet class provides a
method named getParameter(). Syntax:
public String getParameter(String parameterName)

Example of using parameter in Applet:


import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet{
public void paint(Graphics g){
String str=getParameter("msg");
g.drawString(str,50, 50);
}
}
myapplet.html
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>

Java AWT Tutorial


Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in java.
Java AWT components are platform-dependent i.e. components are displayed according to the view of operating
system. AWT is heavyweight i.e. its components are using the resources of OS.
The java.awt package provides classes for AWT api such as TextField, Label, TextArea, RadioButton,
CheckBox, Choice, List etc.
Java AWT Hierarchy
The hierarchy of Java AWT classes are given below.
6
Container
The Container is a component in AWT that can contain another components like buttons, textfields, labels etc.
The classes that extends Container class are known as container such as Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or another window
for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other components like button,
textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other components like
button, textfield etc.

Useful Methods of Component class

Method Description

public void add(Component c) inserts a component on this component.

public void setSize(int width,int height) sets the size (width and height) of the
component.

public void setLayout(LayoutManager m) defines the layout manager for the component.

public void setVisible(boolean status) changes the visibility of the component, by


default false.

Java AWT Example


To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
o By extending Frame class (inheritance)
o By creating the object of Frame class (association)

7
AWT Example by Inheritance
Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing Button
component on the Frame.
import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[]){
First f=new First();
}}
The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above example that sets the
position of the awt button.

AWT Example by Association


Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are showing Button
component on the Frame.
import java.awt.*;
class First2{
First2(){
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
First2 f=new First2();
}}

8
Event and Listener (Java Event Handling)
The Delegation Event Model
The modern approach to handling events is based on the delegation event model, which defines standard and
consistent mechanisms to generate and process events. Its concept is quite simple: a source generates an event
and sends it to one or more listeners. In this scheme, the listener simply waits until it receives an event. Once an
event is received, the listener processes the event and then returns. The advantage of this design is that the
application logic that processes events is cleanly separated from the user interface logic that generates those
events. A user interface element is able to “delegate” the processing of an event to a separate piece of code.
In the delegation event model, listeners must register with a source in order to receive an event notification. This
provides an important benefit: notifications are sent only to listeners that want to receive them. This is a more
efficient way to handle events than the design used by the old Java 1.0 approach. Previously, an event was
propagated up the containment hierarchy until it was handled by a component. This required components to
receive events that they did not process, and it wasted valuable time. The delegation event model eliminates this
overhead.
Events
In the delegation model, an event is an object that describes a state change in a source. It can be generated as a
consequence of a person interacting with the elements in a graphical user interface. Some of the activities that
cause events to be generated are pressing a button, entering a character via the keyboard, selecting an item in a
list, and clicking the mouse. Many other
user operations could also be cited as examples. 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. You are free to define
events that are appropriate for your application.
Event Sources
Asource is an object that generates an event. This occurs when the internal state of that object changes in some
way. Sources may generate more than one type of event. A source must register listeners in order for the listeners
to receive notifications about
a specific type of event. Each type of event has its own registration method. Here is the general form:
public void addTypeListener(TypeListener el)
Here, Type is the name of the event, and el is a reference to the event listener. For example, the method that
registers a keyboard event listener is called addKeyListener( ). The method that registers a mouse motion
listener is called addMouseMotionListener( ). When an event occurs, all registered listeners are notified and
receive a copy of the event object. This is known as multicasting the event. In all cases, notifications are sent
only to listeners that register to
receive them.
Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The
java.awt.event package provides many event classes and Listener interfaces for event handling.
Java Event classes and Listener interfaces
Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener
9
TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener
Steps to perform Event Handling
Following steps are required to perform event handling:
1. Register the component with the Listener
Registration Methods
For registering the component with the Listener, many classes provide the registration methods. For example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}

Java Event Handling Code


We can put the event handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class

Java event handling by implementing ActionListener


import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);

10
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above example that sets
the position of the component it may be button, textfield etc.

Example AWT- Applet

import java.awt.*;
import java.lang.String;
import java.awt.event.*;
import java.applet.Applet;
public class Fact extends Applet implements ActionListener
{
String str;
Button b0;
TextField t1,t2;
Label l1;
public void init(){
Panel p=new Panel();
p.setLayout(new GridLayout());
add(new Label("Enter any Integer value"));
add(t1=new TextField(20));
add(new Label("Factorial value is: "));
add(t2=new TextField(20));
add(b0=new Button("compute"));
11
b0.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
int i,n,f=1;
n=Integer.parseInt(t1.getText());
for(i=1;i<=n;i++)
f=f*i;
t2.setText(String.valueOf(f));
repaint();
}
}

Handling Mouse Events


To handle mouse events, you must implement the MouseListener and the MouseMotionListener interfaces.
(You may also want to implement MouseWheelListener, but we won’t be doing so, here.) The following applet
demonstrates the process. It displays the current coordinates of the mouse in the applet’s status window. Each
time a button is pressed, the word “Down” is displayed at the location of the mouse pointer. Each time the button
is released, the word “Up” is shown. If a button is clicked, the message “Mouse clicked” is displayed in the
upperleft corner of the applet display area. As the mouse enters or exits the applet window, a message is
displayed in the upper-left corner of the applet display area. When dragging the mouse, a * is shown, which
tracks with the mouse pointer as it is dragged. Notice that the two variables, mouseX and mouseY, store the
location of the mouse when a mouse pressed, released, or dragged event occurs. These coordinates are then used
by paint( ) to display output at the point of these occurrences.
// Demonstrate the mouse event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
public class MouseEvents extends Applet
implements MouseListener, MouseMotionListener {
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
// Handle mouse entered.
public void mouseEntered(MouseEvent me) {
12
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}
}

13
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.
Before looking at an example, it is useful to review how key events are generated. 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 keypress 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. The following program demonstrates keyboard input. It echoes keystrokes to the
applet window and shows the pressed/released status of each key in the status window.
// Demonstrate the key event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="SimpleKey" width=300 height=100>
</applet>
*/
public class SimpleKey extends Applet
implements KeyListener {
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init() {
addKeyListener(this);
}
public void keyPressed(KeyEvent ke) {
showStatus("Key Down");
}
public void keyReleased(KeyEvent ke) {
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke) {
msg += ke.getKeyChar();
repaint();
}
// Display keystrokes.
public void paint(Graphics g) {
g.drawString(msg, X, Y);
}
}

If you want to handle the special keys, such as the arrow or function keys, you need to respond to them within
the keyPressed( ) handler. They are not available through keyTyped( ). To identify the keys, you use their
virtual key codes. For example, the next applet outputs the name of a few of the special keys:
// Demonstrate some virtual key codes.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
14
/*
<applet code="KeyEvents" width=300 height=100>
</applet>
*/
public class KeyEvents extends Applet
implements KeyListener {
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init() {
addKeyListener(this);
}
public void keyPressed(KeyEvent ke) {
showStatus("Key Down");
int key = ke.getKeyCode();
switch(key) {
case KeyEvent.VK_F1:
msg += "<F1>";
break;
case KeyEvent.VK_F2:
msg += "<F2>";
break;
case KeyEvent.VK_F3:
msg += "<F3>";
break;
case KeyEvent.VK_PAGE_DOWN:
msg += "<PgDn>";
break;
case KeyEvent.VK_PAGE_UP:
msg += "<PgUp>";
break;
case KeyEvent.VK_LEFT:
msg += "<Left Arrow>";
break;
case KeyEvent.VK_RIGHT:
msg += "<Right Arrow>";
break;
}
repaint();
}
public void keyReleased(KeyEvent ke) {
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke) {
msg += ke.getKeyChar();
repaint();
}
// Display keystrokes.
public void paint(Graphics g) {
g.drawString(msg, X, Y);
}
15
}

Java AWT Button


The button class is used to create a labeled button that has platform independent implementation. The application
result in some action when the button is pushed.
AWT Button Class declaration
public class Button extends Component implements Accessible

Java AWT Button Example


import java.awt.*;
public class ButtonExample {
public static void main(String[] args) {
Frame f=new Frame("Button Example");
Button b=new Button("Click Here");
b.setBounds(50,100,80,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:

Java AWT Button Example with ActionListener


import java.awt.*;
import java.awt.event.*;
public class ButtonExample {
public static void main(String[] args) {
Frame f=new Frame("Button Example");
final TextField tf=new TextField();
tf.setBounds(50,50, 150,20);
Button b=new Button("Click Here");
b.setBounds(50,100,60,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}
});
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
16
}
}
Output:

Java AWT Label


The object of Label class is a component for placing text in a container. It is used to display a single line of read
only text. The text can be changed by an application but a user cannot edit it directly.
AWT Label Class Declaration
public class Label extends Component implements Accessible

Java Label Example


import java.awt.*;
class LabelExample{
public static void main(String args[]){
Frame f= new Frame("Label Example");
Label l1,l2;
l1=new Label("First Label.");
l1.setBounds(50,100, 100,30);
l2=new Label("Second Label.");
l2.setBounds(50,150, 100,30);
f.add(l1); f.add(l2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:

Java Swing Tutorial


Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.

17
Difference between AWT and Swing
There are many differences between java awt and swing that are given below.
No. Java AWT Java Swing

1) AWT components are platform-dependent. Java swing components are platform-


independent.

2) AWT components are heavyweight. Swing components are lightweight.

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

4) AWT provides less components than Swing provides more powerful


Swing. componentssuch as tables, lists, scrollpanes,
colorchooser, tabbedpane etc.

5) AWT doesn't follows MVC(Model View Swing follows MVC.


Controller) where model represents data,
view represents presentation and controller
acts as an interface between model and
view.

Model-View-Controller (MVC) Connection


MVC is an architectural pattern widely used in development of software. Every GUI control or component
contains three aspects:
1. The way the component looks (appearance) when rendered on the screen.
2. The way the component reacts to the user.
3. The state information associated with the component.
MVC can be used to separate the three aspects mentioned above. By separating them, each aspect can be
modified independently without any changes to the remaining aspects.
In MVC terminology, model corresponds to the state information of a component. For example, a button might
contain a field that might represent if it is pressed or released. The view corresponds to the look or appearance of
the component when rendered on the screen. For example, a button is displayed as a rectangle.
The controller determines how the component reacts to the user events. For example, when user presses a
button, a new frame can be displayed.
The controller changes the model and the model notifies the state change to the view to be updated accordingly.
Java Swings uses a modified version of MVC architecture, in which view and controller are combined into
single entity called UIDelegate. This modified architecture is called as Model-Delegate architecture or Separable
Model architecture.

18
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop
applications.

Hierarchy of Java Swing classes


The hierarchy of java swing API is given below.

Commonly used Methods of Component class


The methods of Component class are widely used in java swing that are given below.
Method Description

public void add(Component c) add a component on another component.

public void setSize(int width,int height) sets size of the component.

public void setLayout(LayoutManager m) sets the layout manager for the component.

public void setVisible(boolean b) sets the visibility of the component. It is by


default false.
Java Swing Examples
There are two ways to create a frame:
o By creating the object of Frame class (association)
o By extending Frame class (inheritance)
We can write the code of swing inside the main(), constructor or any other method.

Simple Java Swing Example


Let's see a simple swing example where we are creating one button and adding it on the JFrame object inside the
main() method.
File: FirstSwingExample.java
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton

19
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}

Example of Swing by Association inside constructor


We can also write all the codes of creating JFrame, JButton and method call inside the java constructor.
File: Simple.java
import javax.swing.*;
public class Simple {
JFrame f;
Simple(){
f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
public static void main(String[] args) {
new Simple();
}
}
The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that sets the position of the
button.

Simple example of Swing by inheritance


We can also inherit the JFrame class, so there is no need to create the instance of JFrame class explicitly.
File: Simple2.java
import javax.swing.*;
public class Simple2 extends JFrame{//inheriting JFrame
JFrame f;
Simple2(){
JButton b=new JButton("click");//create button
b.setBounds(130,100,100, 40);
add(b);//adding button on frame
20
setSize(400,500);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new Simple2();
}}
Java JButton
The JButton class is used to create a labeled button that has platform independent implementation. The
application result in some action when the button is pushed. It inherits AbstractButton class.
JButton class declaration
Let's see the declaration for javax.swing.JButton class.
public class JButton extends AbstractButton implements Accessible
Commonly used Constructors:
Constructor Description

JButton() It creates a button with no text and icon.

JButton(String s) It creates a button with the specified text.

JButton(Icon i) It creates a button with the specified icon object.

Commonly used Methods of AbstractButton class:


Methods Description

void setText(String s) It is used to set specified text on button

String getText() It is used to return the text of the button.

void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the button.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

void addActionListener(ActionListener a) It is used to add the action listener to this object.

Java JButton Example


import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
21
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:

Java JButton Example with ActionListener


import java.awt.event.*;
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
final JTextField tf=new JTextField();
tf.setBounds(50,50, 150,20);
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}
});
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:

22
Example of displaying image on the button:
import javax.swing.*;
public class ButtonExample{
ButtonExample(){
JFrame f=new JFrame("Button Example");
JButton b=new JButton(new ImageIcon("D:\\icon.png"));
b.setBounds(100,100,100, 40);
f.add(b);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new ButtonExample();
}
}
Output:

Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to display a single line of read
only text. The text can be changed by an application but a user cannot edit it directly. It inherits JComponent
class.
JLabel class declaration
Let's see the declaration for javax.swing.JLabel class.
public class JLabel extends JComponent implements SwingConstants, Accessible
Commonly used Constructors:
Constructor Description

JLabel() Creates a JLabel instance with no image and with an empty


string for the title.

JLabel(String s) Creates a JLabel instance with the specified text.

JLabel(Icon i) Creates a JLabel instance with the specified image.

JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image, and

23
horizontalAlignment) horizontal alignment.

Commonly used Methods:

Methods Description

String getText() t returns the text string that a label displays.

void setText(String text) It defines the single line of text this component will
display.

void setHorizontalAlignment(int alignment) It sets the alignment of the label's contents along
the X axis.

Icon getIcon() It returns the graphic image that the label displays.

int getHorizontalAlignment() It returns the alignment of the label's contents


along the X axis.
Java JLabel Example
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
Output:

Java JLabel Example with ActionListener


import javax.swing.*;
24
import java.awt.*;
import java.awt.event.*;
public class LabelExample extends Frame implements ActionListener{
JTextField tf; JLabel l; JButton b;
LabelExample(){
tf=new JTextField();
tf.setBounds(50,50, 150,20);
l=new JLabel();
l.setBounds(50,100, 250,20);
b=new JButton("Find IP");
b.setBounds(50,150,95,30);
b.addActionListener(this);
add(b);add(tf);add(l);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try{
String host=tf.getText();
String ip=java.net.InetAddress.getByName(host).getHostAddress();
l.setText("IP of "+host+" is: "+ip);
}catch(Exception ex){System.out.println(ex);}
}
public static void main(String[] args) {
new LabelExample();
}}
Output:

Java JTextField
The object of a JTextField class is a text component that allows the editing of a single line text. It inherits
JTextComponent class.
JTextField class declaration
Let's see the declaration for javax.swing.JTextField class.
public class JTextField extends JTextComponent implements SwingConstants
Commonly used Constructors:
Constructor Description

JTextField() Creates a new TextField

JTextField(String text) Creates a new TextField initialized with the specified text.
25
JTextField(String text, int columns) Creates a new TextField initialized with the specified text and
columns.

JTextField(int columns) Creates a new empty TextField with the specified number of
columns.

Commonly used Methods:


Methods Description

void addActionListener(ActionListener l) It is used to add the specified action listener to receive action
events from this textfield.

Action getAction() It returns the currently set Action for this ActionEvent
source, or null if no Action is set.

void setFont(Font f) It is used to set the current font.

void removeActionListener(ActionListener It is used to remove the specified action listener so that it no


l) longer receives action events from this textfield.

Java JTextField Example


import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");
t1.setBounds(50,100, 200,30);
t2=new JTextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:

26
Java JTextField Example with ActionListener
import javax.swing.*;
import java.awt.event.*;
public class TextFieldExample implements ActionListener{
JTextField tf1,tf2,tf3;
JButton b1,b2;
TextFieldExample(){
JFrame f= new JFrame();
tf1=new JTextField();
tf1.setBounds(50,50,150,20);
tf2=new JTextField();
tf2.setBounds(50,100,150,20);
tf3=new JTextField();
tf3.setBounds(50,150,150,20);
tf3.setEditable(false);
b1=new JButton("+");
b1.setBounds(50,200,50,50);
b2=new JButton("-");
b2.setBounds(120,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s1=tf1.getText();
String s2=tf2.getText();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()==b1){
c=a+b;
}else if(e.getSource()==b2){
c=a-b;
}
String result=String.valueOf(c);
tf3.setText(result);
}
public static void main(String[] args) {
new TextFieldExample();
}}
Output:

27
Java JTextArea
The object of a JTextArea class is a multi line region that displays text. It allows the editing of multiple line text.
It inherits JTextComponent class
JTextArea class declaration
Let's see the declaration for javax.swing.JTextArea class.
public class JTextArea extends JTextComponent
Commonly used Constructors:
Constructor Description

JTextArea() Creates a text area that displays no text initially.

JTextArea(String s) Creates a text area that displays specified text initially.

JTextArea(int row, int column) Creates a text area with the specified number of rows and columns
that displays no text initially.

JTextArea(String s, int row, int Creates a text area with the specified number of rows and columns
column) that displays specified text.

Commonly used Methods:

Methods Description

void setRows(int rows) It is used to set specified number of rows.

void setColumns(int cols) It is used to set specified number of columns.

void setFont(Font f) It is used to set the specified font.

void insert(String s, int position) It is used to insert the specified text on the specified position.

void append(String s) It is used to append the given text to the end of the document.

Java JTextArea Example


import javax.swing.*;
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to javatpoint");
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
28
}}
Output:

Java JTextArea Example with ActionListener


import javax.swing.*;
import java.awt.event.*;
public class TextAreaExample implements ActionListener{
JLabel l1,l2;
JTextArea area;
JButton b;
TextAreaExample() {
JFrame f= new JFrame();
l1=new JLabel();
l1.setBounds(50,25,100,30);
l2=new JLabel();
l2.setBounds(160,25,100,30);
area=new JTextArea();
area.setBounds(20,75,250,200);
b=new JButton("Count Words");
b.setBounds(100,300,120,30);
b.addActionListener(this);
f.add(l1);f.add(l2);f.add(area);f.add(b);
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e){
String text=area.getText();
String words[]=text.split("\\s");
l1.setText("Words: "+words.length);
l2.setText("Characters: "+text.length());
}
public static void main(String[] args) {
new TextAreaExample();
}
}
Output:

29
Java JPasswordField
The object of a JPasswordField class is a text component specialized for password entry. It allows the editing of
a single line of text. It inherits JTextField class.
JPasswordField class declaration
Let's see the declaration for javax.swing.JPasswordField class.
public class JPasswordField extends JTextField
Commonly used Constructors:
Constructor Description

JPasswordField() Constructs a new JPasswordField, with a default document, null


starting text string, and 0 column width.

JPasswordField(int columns) Constructs a new empty JPasswordField with the specified


number of columns.

JPasswordField(String text) Constructs a new JPasswordField initialized with the specified


text.

JPasswordField(String text, int Construct a new JPasswordField initialized with the specified
columns) text and columns.

Java JPasswordField Example


import javax.swing.*;
public class PasswordFieldExample {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");
JPasswordField value = new JPasswordField();
JLabel l1=new JLabel("Password:");
l1.setBounds(20,100, 80,30);
value.setBounds(100,100,100,30);
f.add(value); f.add(l1);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
Output:

Java JPasswordField Example with ActionListener


import javax.swing.*;
import java.awt.event.*;
public class PasswordFieldExample {
30
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");
final JLabel label = new JLabel();
label.setBounds(20,150, 200,50);
final JPasswordField value = new JPasswordField();
value.setBounds(100,75,100,30);
JLabel l1=new JLabel("Username:");
l1.setBounds(20,20, 80,30);
JLabel l2=new JLabel("Password:");
l2.setBounds(20,75, 80,30);
JButton b = new JButton("Login");
b.setBounds(100,120, 80,30);
final JTextField text = new JTextField();
text.setBounds(100,20, 100,30);
f.add(value); f.add(l1); f.add(label); f.add(l2); f.add(b); f.add(text);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Username " + text.getText();
data += ", Password: "
+ new String(value.getPassword());
label.setText(data);
}
});
}
}
Output:

Displaying Text in the Frame:(Painting in Swings)


paintComponent (Graphics g) method of JPanel class is used to paint the portion of a component in swing. We
should override this method in our class. In the following example, we are writing our class MyPanel as a
subclass to JPanel and override the paintComponent () method.
Ex: Wrire a program to display text in the frame.
import javax.swing.*;
import java.awt.*;
class MyPanel extends JPanel
{
public void paintComponent (Graphics g)
{
super.paintComponent (g); //call JPanel’s method

31
setBackground (Color.red);
g.setColor (Color.white);
g.setFont (new Font("Courier New",Font.BOLD,30));
g.drawString ("Hello Readers!", 50, 100);
}
}
class FrameDemo extends JFrame
{
FrameDemo ()
{
Container c = getContentPane ();
MyPanel mp = new MyPanel ();
c.add (mp);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
FrameDemo ob = new FrameDemo ();
ob.setSize (600, 200);
ob.setVisible (true);
}
}

Compilation & Execution:


javac FrameDemo.java
java FrameDemo

Output:

Java JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off (false). Clicking on
a CheckBox changes its state from "on" to "off" or from "off" to "on ".It inherits JToggleButton class.
JCheckBox class declaration
Let's see the declaration for javax.swing.JCheckBox class.
public class JCheckBox extends JToggleButton implements Accessible
Commonly used Constructors:

Constructor Description

JJCheckBox() Creates an initially unselected check box button with no text,


no icon.

JChechBox(String s) Creates an initially unselected check box with text.

32
JCheckBox(String text, boolean selected) Creates a check box with text and specifies whether or not it
is initially selected.

JCheckBox(Action a) Creates a check box where properties are taken from the
Action supplied.
Commonly used Methods:
Methods Description

AccessibleContext getAccessibleContext() It is used to get the AccessibleContext associated with


this JCheckBox.

protected String paramString() It returns a string representation of this JCheckBox.

Java JCheckBox Example


import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}}
Output:

Java JCheckBox Example with ItemListener


import javax.swing.*;
import java.awt.event.*;
public class CheckBoxExample
{
CheckBoxExample(){
33
JFrame f= new JFrame("CheckBox Example");
final JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
JCheckBox checkbox1 = new JCheckBox("C++");
checkbox1.setBounds(150,100, 50,50);
JCheckBox checkbox2 = new JCheckBox("Java");
checkbox2.setBounds(150,150, 50,50);
f.add(checkbox1); f.add(checkbox2); f.add(label);
checkbox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
checkbox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}
}
Output:

Java JCheckBox Example: Food Order


import javax.swing.*;
import java.awt.event.*;
public class CheckBoxExample extends JFrame implements ActionListener{
JLabel l;
JCheckBox cb1,cb2,cb3;
JButton b;
CheckBoxExample(){
l=new JLabel("Food Ordering System");

34
l.setBounds(50,50,300,20);
cb1=new JCheckBox("Pizza @ 100");
cb1.setBounds(100,100,150,20);
cb2=new JCheckBox("Burger @ 30");
cb2.setBounds(100,150,150,20);
cb3=new JCheckBox("Tea @ 10");
cb3.setBounds(100,200,150,20);
b=new JButton("Order");
b.setBounds(100,250,80,30);
b.addActionListener(this);
add(l);add(cb1);add(cb2);add(cb3);add(b);
setSize(400,400);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
float amount=0;
String msg="";
if(cb1.isSelected()){
amount+=100;
msg="Pizza: 100\n";
}
if(cb2.isSelected()){
amount+=30;
msg+="Burger: 30\n";
}
if(cb3.isSelected()){
amount+=10;
msg+="Tea: 10\n";
}
msg+="-----------------\n";
JOptionPane.showMessageDialog(this,msg+"Total: "+amount);
}
public static void main(String[] args) {
new CheckBoxExample();
}
}
Output:

35
Java JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option from multiple options. It
is widely used in exam systems or quiz.
It should be added in ButtonGroup to select one radio button only.
JRadioButton class declaration
Let's see the declaration for javax.swing.JRadioButton class.
public class JRadioButton extends JToggleButton implements Accessible
Commonly used Constructors:
Constructor Description

JRadioButton() Creates an unselected radio button with no text.

JRadioButton(String s) Creates an unselected radio button with specified


text.

JRadioButton(String s, boolean selected) Creates a radio button with the specified text and
selected status.

Commonly used Methods:


Methods Description

void setText(String s) It is used to set specified text on button.

String getText() It is used to return the text of the button.

void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the


button.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

void addActionListener(ActionListener a) It is used to add the action listener to this


object.

Java JRadioButton Example


import javax.swing.*;
public class RadioButtonExample {
JFrame f;
RadioButtonExample(){
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
36
bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new RadioButtonExample();
}
}
Output:

Java JRadioButton Example with ActionListener


import javax.swing.*;
import java.awt.event.*;
class RadioButtonExample extends JFrame implements ActionListener{
JRadioButton rb1,rb2;
JButton b;
RadioButtonExample(){
rb1=new JRadioButton("Male");
rb1.setBounds(100,50,100,30);
rb2=new JRadioButton("Female");
rb2.setBounds(100,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(rb1);bg.add(rb2);
b=new JButton("click");
b.setBounds(100,150,80,30);
b.addActionListener(this);
add(rb1);add(rb2);add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(rb1.isSelected()){
JOptionPane.showMessageDialog(this,"You are Male.");
}
if(rb2.isSelected()){
JOptionPane.showMessageDialog(this,"You are Female.");
}
}
public static void main(String args[]){
new RadioButtonExample();

37
}}
Output:

Java JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by user is shown on the top
of a menu. It inherits JComponent class.
JComboBox class declaration
Let's see the declaration for javax.swing.JComboBox class.
public class JComboBox extends JComponent implements ItemSelectable, ListDataListener, ActionListener, A
ccessible
Commonly used Constructors:
Constructor Description

JComboBox() Creates a JComboBox with a default data model.

JComboBox(Object[] items) Creates a JComboBox that contains the elements in the


specified array.

JComboBox(Vector<?> items) Creates a JComboBox that contains the elements in the


specified Vector.

Commonly used Methods:


Methods Description

void addItem(Object anObject) It is used to add an item to the item list.

void removeItem(Object anObject) It is used to delete an item to the item list.

void removeAllItems() It is used to remove all the items from the list.

void setEditable(boolean b) It is used to determine whether the JComboBox


is editable.

void addActionListener(ActionListener a) It is used to add the ActionListener.

void addItemListener(ItemListener i) It is used to add the ItemListener.


Java JComboBox Example
import javax.swing.*;
public class ComboBoxExample {
JFrame f;
38
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args) {
new ComboBoxExample();
}
}
Output:

Java JComboBox Example with ActionListener


import javax.swing.*;
import java.awt.event.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
final JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
JButton b=new JButton("Show");
b.setBounds(200,100,75,20);
String languages[]={"C","C++","C#","Java","PHP"};
final JComboBox cb=new JComboBox(languages);
cb.setBounds(50, 100,90,20);
f.add(cb); f.add(label); f.add(b);
f.setLayout(null);
f.setSize(350,350);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected: "
+ cb.getItemAt(cb.getSelectedIndex());
label.setText(data);
}
});
}
39
public static void main(String[] args) {
new ComboBoxExample();
}
}
Output:

Java JTabbedPane
The JTabbedPane class is used to switch between a group of components by clicking on a tab with a given title
or icon. It inherits JComponent class.
JTabbedPane class declaration
Let's see the declaration for javax.swing.JTabbedPane class.
public class JTabbedPane extends JComponent implements Serializable, Accessible, SwingConstants
Commonly used Constructors:
Constructor Description

JTabbedPane() Creates an empty TabbedPane with a default tab


placement of JTabbedPane.Top.

JTabbedPane(int tabPlacement) Creates an empty TabbedPane with a specified tab


placement.

JTabbedPane(int tabPlacement, int Creates an empty TabbedPane with a specified tab


tabLayoutPolicy) placement and tab layout policy.

Java JTabbedPane Example


import javax.swing.*;
public class TabbedPaneExample {
JFrame f;
TabbedPaneExample(){
f=new JFrame();
JTextArea ta=new JTextArea(200,200);
JPanel p1=new JPanel();
p1.add(ta);
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JTabbedPane tp=new JTabbedPane();
tp.setBounds(50,50,200,200);
tp.add("main",p1);
tp.add("visit",p2);
tp.add("help",p3);
40
f.add(tp);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new TabbedPaneExample();
}}
Output:

Java JToggleButton
JToggleButton is used to create toggle button, it is two-states button to switch on or off.
Nested Classes
Modifier and Class Description
Type

protected class JToggleButton.AccessibleJToggleButton This class implements accessibility


support for the JToggleButton class.

static class JToggleButton.ToggleButtonModel The ToggleButton model


Constructors
Constructor Description

JToggleButton() It creates an initially unselected toggle button


without setting the text or image.

JToggleButton(Action a) It creates a toggle button where properties are taken


from the Action supplied.

JToggleButton(Icon icon) It creates an initially unselected toggle button with


the specified image but no text.

JToggleButton(Icon icon, boolean selected) It creates a toggle button with the specified image
and selection state, but no text.

JToggleButton(String text) It creates an unselected toggle button with the


specified text.

JToggleButton(String text, boolean selected) It creates a toggle button with the specified text and

41
selection state.

JToggleButton(String text, Icon icon) It creates a toggle button that has the specified text
and image, and that is initially unselected.

JToggleButton(String text, Icon icon, boolean It creates a toggle button with the specified text,
selected) image, and selection state.
Methods
Modifier and Type Method Description

AccessibleContext getAccessibleContext() It gets the AccessibleContext associated with this


JToggleButton.

String getUIClassID() It returns a string that specifies the name of the l&f
class that renders this component.

protected String paramString() It returns a string representation of this JToggleButton.

Void updateUI() It resets the UI property to a value from the current


look and feel.

JToggleButton Example
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
public class JToggleButtonExample extends JFrame implements ItemListener {
public static void main(String[] args) {
new JToggleButtonExample();
}
private JToggleButton button;
JToggleButtonExample() {
setTitle("JToggleButton with ItemListener Example");
setLayout(new FlowLayout());
setJToggleButton();
setAction();
setSize(200, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void setJToggleButton() {
button = new JToggleButton("ON");
add(button);
}
private void setAction() {
button.addItemListener(this);
}
42
public void itemStateChanged(ItemEvent eve) {
if (button.isSelected())
button.setText("OFF");
else
button.setText("ON");
}
}
Output

Java JScrollBar
The object of JScrollbar class is used to add horizontal and vertical scrollbar. It is an implementation of a
scrollbar. It inherits JComponent class.
JScrollBar class declaration
Let's see the declaration for javax.swing.JScrollBar class.
public class JScrollBar extends JComponent implements Adjustable, Accessible
Commonly used Constructors:
Constructor Description

JScrollBar() Creates a vertical scrollbar with the initial


values.

JScrollBar(int orientation) Creates a scrollbar with the specified orientation


and the initial values.

JScrollBar(int orientation, int value, int extent, int Creates a scrollbar with the specified
min, int max) orientation, value, extent, minimum, and
maximum.

Java JScrollBar Example


import javax.swing.*;
class ScrollBarExample
{
ScrollBarExample(){
JFrame f= new JFrame("Scrollbar Example");
JScrollBar s=new JScrollBar();
s.setBounds(100,100, 50,100);
f.add(s);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
43
{
new ScrollBarExample();
}}
Output:

Java JScrollBar Example with AdjustmentListener


import javax.swing.*;
import java.awt.event.*;
class ScrollBarExample
{
ScrollBarExample(){
JFrame f= new JFrame("Scrollbar Example");
final JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
final JScrollBar s=new JScrollBar();
s.setBounds(100,100, 50,100);
f.add(s); f.add(label);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
s.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
label.setText("Vertical Scrollbar value is:"+ s.getValue());
}
});
}
public static void main(String args[])
{
new ScrollBarExample();
}}
Output:

44
Java JList
The object of JList class represents a list of text items. The list of text items can be set up so that the user can
choose either one item or multiple items. It inherits JComponent class.
JList class declaration
Let's see the declaration for javax.swing.JList class.
public class JList extends JComponent implements Scrollable, Accessible
Commonly used Constructors:
Constructor Description

JList() Creates a JList with an empty, read-only, model.

JList(ary[] listData) Creates a JList that displays the elements in the specified
array.

JList(ListModel<ary> dataModel) Creates a JList that displays elements from the specified, non-
null, model.

Commonly used Methods:


Methods Description

Void addListSelectionListener(ListSelectionListener It is used to add a listener to the list, to be


listener) notified each time a change to the selection
occurs.

int getSelectedIndex() It is used to return the smallest selected cell


index.

ListModel getModel() It is used to return the data model that holds a


list of items displayed by the JList component.

void setListData(Object[] listData) It is used to create a read-only ListModel from


an array of objects.
Java JList Example
import javax.swing.*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
45
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}}
Output:

Java JList Example with ActionListener


import javax.swing.*;
import java.awt.event.*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
final JLabel label = new JLabel();
label.setSize(500,100);
JButton b=new JButton("Show");
b.setBounds(200,150,80,30);
final DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("C");
l1.addElement("C++");
l1.addElement("Java");
l1.addElement("PHP");
final JList<String> list1 = new JList<>(l1);
list1.setBounds(100,100, 75,75);
DefaultListModel<String> l2 = new DefaultListModel<>();
l2.addElement("Turbo C++");
l2.addElement("Struts");
l2.addElement("Spring");
l2.addElement("YII");
final JList<String> list2 = new JList<>(l2);
46
list2.setBounds(100,200, 75,75);
f.add(list1); f.add(list2); f.add(b); f.add(label);
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "";
if (list1.getSelectedIndex() != -1) {
data = "Programming language Selected: " + list1.getSelectedValue();
label.setText(data);
}
if(list2.getSelectedIndex() != -1){
data += ", FrameWork Selected: ";
for(Object frame :list2.getSelectedValues()){
data += frame + " ";
}
}
label.setText(data);
}
});
}
public static void main(String args[])
{
new ListExample();
}}
Output:

JTable:
JTable represents data in the form of a table. The table can have rows of data, and column headings.
 To create a JTable: JTable tab = new JTable (data, column_names); Here, data and column_names
can be a 2D array or both can be vector of vectors.
 To create a row using a vector: Vector row = new Vector();
row.add(object); //here object represents a column row.add (object);
row.add (object);
 To create a table heading, we use getTableHeader () method of JTable class.
JTableHeader head = tab.getTableHeader ();

Note: JTableHeader class is defined in javax.swing.table package.


47
Ex: Write a program that creates a table with some rows and columns. //creating a table
import java.awt.*;
import javax.swing.*;
import java.util.*;
import javax.swing.table.*;
class JTableDemo extends JFrame
{
JTableDemo ()
{
Vector <Vector> data = new Vector <Vector> ();
//create first row
Vector <String> row = new Vector <String> ();
row.add ("Ravi");
row.add ("Manager");
row.add ("50000");
data.add (row);
row = new Vector <String>(); //create second row
row.add ("Kiran");
row.add ("Clerk");
row.add ("5000");
data.add (row);
row = new Vector<String> (); //create third row
row.add ("Hari");
row.add ("Analyst");
row.add ("10000");
data.add (row);
//create a row with column names
Vector <String> cols = new Vector<String> ();
cols.add ("Employee Name");
cols.add ("Designation");
cols.add ("Salary");
//create the table
JTable tab = new JTable (data, cols);
//create table header object
JTableHeader head = tab.getTableHeader ();
Container c = getContentPane ();
c.setLayout (new BorderLayout ());
c.add ("North", head);
c.add ("Center", tab);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
JTableDemo demo = new JTableDemo ();
demo.setSize (600, 250);
demo.setVisible (true);
}
48
}
Output:

JMenu Class:
A menu represents a group of items or options for the user to select. To create a menu, the following steps should
be used:
 Create a menu bar using JMenuBar class object: JMenuBar mb = new JMenuBar ();
 Attach this member to the container. c.add (mb);
 Create separate menu to attach to the menubar. JMenu file = new JMenu ("File");
 Note: Here, "File" is title for the menu which appear in the menubar.
 Attach this menu to the menubar. mb.add (file);
 Create menuitems using JMenuItem or JCheckBoxMenuItem or JRadioButtonMenuItem classes.
JMenuItem op = new JMenuITem ("Open");
 Attach this menuitem to the menu. file.add (op);
 Creating a submenu:
o Create a menu: JMenu font = new JMenu ("Font");
Here, font represents a submenu to be attached to a menu.
o Now attach it to a menu: file.add (font);
o Attach menuitems to the font submenu. font.add (obj);
Note: obj can be a JMenuItem or JCheckBoxMenuItem or JRadioButtonMenuItem

Ex: Write a program to create a menu with several menu items. //Menu Creation
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class MyMenu extends JFrame implements ActionListener
{
JMenuBar mb;
JMenu file, edit, font;
JMenuItem op, cl, cp, pt;
JCheckBoxMenuItem pr;
MyMenu ()
{
Container c = getContentPane ();
c.setLayout (new BorderLayout ());
mb = new JMenuBar ();
c.add ("North", mb);
//create file, edit menus
file = new JMenu ("File");
49
edit = new JMenu ("Edit");
//add menus to mb
mb.add (file);
mb.add (edit);
//create menuitems
op = new JMenuItem ("Open");
cl = new JMenuItem ("Close");
cp = new JMenuItem ("Copy");
pt = new JMenuItem ("Paste");
//add menu items to menus
file.add (op);
file.add (cl);
file.add (cp);
file.add (pt);
//disable close
cl.setEnabled (false);
//create checkbox menu item
pr = new JCheckBoxMenuItem ("Print");
//add checkbox menu item to file menu
file.add (pr);
//display line (separator)
file.addSeparator ();
//create submenu
font = new JMenu ("Font");
//add this submenu in file
file.add (font);
//add menu items to font
font.add ("Arial");
font.add ("Times New Roman");
//add action listeners to menu items
op.addActionListener (this);
cl.addActionListener (this);
cp.addActionListener (this);
pt.addActionListener (this);
pr.addActionListener (this);
//close the frame
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{
if (op.isArmed())
System.out.println ("Open is selected");
if (cl.isArmed())
System.out.println ("Close is selected");
if (cp.isArmed())
System.out.println ("Copy is selected");
if (pt.isArmed())
System.out.println ("Paste is selected");
if (pr.isArmed())
System.out.println ("Print is selected");
50
}
public static void main (String args[])
{
MyMenu ob = new MyMenu ();
ob.setSize (600,450);
ob.setVisible (true);
}
}
Output:

Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an interface that
is implemented by all the classes of layout managers. There are following classes that represents the layout
managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout

Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east, west and center. Each
region (area) may contain one component only. It is the default layout of frame or window. The BorderLayout
provides five constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
51
4. public static final int WEST
5. public static final int CENTER
Constructors of BorderLayout class:
o BorderLayout(): creates a border layout but with no gaps between the components.
o JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps
between the components.

Example of BorderLayout class:

import java.awt.*;
import javax.swing.*;
public class Border {
JFrame f;
Border(){
f=new JFrame();
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();
}
}
Java GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each
rectangle.
Constructors of GridLayout class
1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps
between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows and
columns alongwith given horizontal and vertical gaps.
Example of GridLayout class

52
import java.awt.*;
import javax.swing.*;
public class MyGridLayout{
JFrame f;
MyGridLayout(){
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");
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));
//setting grid layout of 3 rows and 3 columns
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}
Java FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default layout
of applet or panel.
Fields of FlowLayout class
1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING
Constructors of FlowLayout class
1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical
gap.
53
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal
and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the given
horizontal and vertical gap.

Example of FlowLayout class

import java.awt.*;
import javax.swing.*;
public class MyFlowLayout{
JFrame f;
MyFlowLayout(){
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.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();
} }
Java CardLayout
The CardLayout class manages the components in such a manner that only one component is visible at a time. It
treats each component as a card that is why it is known as CardLayout.
Constructors of CardLayout class
1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap.
Commonly used methods of CardLayout class
o public void next(Container parent): is used to flip to the next card of the given container.
o public void previous(Container parent): is used to flip to the previous card of the given container.
o public void first(Container parent): is used to flip to the first card of the given container.
o public void last(Container parent): is used to flip to the last card of the given container.
o public void show(Container parent, String name): is used to flip to the specified card with the given
name.

Example of CardLayout class


54
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample extends JFrame implements ActionListener{
CardLayout card;
JButton b1,b2,b3;
Container c;
CardLayoutExample(){
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);
}
public static void main(String[] args) {
CardLayoutExample cl=new CardLayoutExample();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Java GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or along their baseline.
The components may not be of same size. Each GridBagLayout object maintains a dynamic, rectangular grid of
cells. Each component occupies one or more cells known as its display area. Each component associates an
instance of GridBagConstraints. With the help of constraints object we arrange component's display area on the
grid. The GridBagLayout manages each component's minimum and preferred sizes in order to determine
component's size.
Fields

55
Modifier and Type Field Description

double[] columnWeights It is used to hold the


overrides to the column
weights.

int[] columnWidths It is used to hold the


overrides to the column
minimum width.

protected comptable It is used to maintains the


Hashtable<Component,GridBagConstraints> association between a
component and its gridbag
constraints.

protected GridBagConstraints defaultConstraints It is used to hold a gridbag


constraints instance
containing the default
values.

protected GridBagLayoutInfo layoutInfo It is used to hold the


layout information for the
gridbag.

protected static int MAXGRIDSIZE No longer in use just for


backward compatibility

protected static int MINSIZE It is smallest grid that can


be laid out by the grid bag
layout.

protected static int PREFERREDSIZE It is preferred grid size that


can be laid out by the grid
bag layout.

int[] rowHeights It is used to hold the


overrides to the row
minimum heights.

double[] rowWeights It is used to hold the


overrides to the row
weights.
Useful Methods
Modifier and Method Description
Type

void addLayoutComponent(Component comp, It adds specified component to the


Object constraints) layout, using the specified constraints

56
object.

void addLayoutComponent(String name, It has no effect, since this layout


Component comp) manager does not use a per-
component string.

protected adjustForGravity(GridBagConstraints It adjusts the x, y, width, and height


void constraints, Rectangle r) fields to the correct values depending
on the constraint geometry and pads.

protected AdjustForGravity(GridBagConstraints This method is for backwards


void constraints, Rectangle r) compatibility only

protected arrangeGrid(Container parent) Lays out the grid.


void

protected ArrangeGrid(Container parent) This method is obsolete and supplied


void for backwards compatibility

GridBagCon getConstraints(Component comp) It is for getting the constraints for the


straints specified component.

float getLayoutAlignmentX(Container parent) It returns the alignment along the x


axis.

float getLayoutAlignmentY(Container parent) It returns the alignment along the y


axis.

int[][] getLayoutDimensions() It determines column widths and row


heights for the layout grid.

protected getLayoutInfo(Container parent, int sizeflag) This method is obsolete and supplied
GridBagLay for backwards compatibility.
outInfo

protected GetLayoutInfo(Container parent, int This method is obsolete and supplied


GridBagLay sizeflag) for backwards compatibility.
outInfo

Point getLayoutOrigin() It determines the origin of the layout


area, in the graphics coordinate space
of the target container.

double[][] getLayoutWeights() It determines the weights of the


layout grid's columns and rows.

protected getMinSize(Container parent, It figures out the minimum size of the


Dimension GridBagLayoutInfo info) master based on the information from
getLayoutInfo.

57
protected GetMinSize(Container parent, This method is obsolete and supplied
Dimension GridBagLayoutInfo info) for backwards compatibility only
Example
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class GridBagLayoutExample extends JFrame{
public static void main(String[] args) {
GridBagLayoutExample a = new GridBagLayoutExample();
}
public GridBagLayoutExample() {
GridBagLayoutgrid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(grid);
setTitle("GridBag Layout Example");
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
this.add(new Button("Button One"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
this.add(new Button("Button two"), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
gbc.gridx = 0;
gbc.gridy = 1;
this.add(new Button("Button Three"), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
this.add(new Button("Button Four"), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
this.add(new Button("Button Five"), gbc);
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

}
Output:

58
Example 2
public class GridBagLayoutDemo {
final static boolean shouldFill = true;
final static boolean shouldWeightX = true;
final static boolean RIGHT_TO_LEFT = false;
public static void addComponentsToPane(Container pane) {
if (RIGHT_TO_LEFT) {
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}
JButton button;
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
if (shouldFill) {
//natural height, maximum width
c.fill = GridBagConstraints.HORIZONTAL;
}
button = new JButton("Button 1");
if (shouldWeightX) {
c.weightx = 0.5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
pane.add(button, c);
button = new JButton("Button 2");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 1;
c.gridy = 0;
pane.add(button, c);
button = new JButton("Button 3");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 2;
c.gridy = 0;
pane.add(button, c);
button = new JButton("Long-Named Button 4");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 40; //make this component tall

59
c.weightx = 0.0;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 1;
pane.add(button, c);
button = new JButton("5");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 0; //reset to default
c.weighty = 1.0; //request any extra vertical space
c.anchor = GridBagConstraints.PAGE_END; //bottom of space
c.insets = new Insets(10,0,0,0); //top padding
c.gridx = 1; //aligned with button 2
c.gridwidth = 2; //2 columns wide
c.gridy = 2; //third row
pane.add(button, c);
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("GridBagLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
addComponentsToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Output:

Dialog Boxes
Often, you will want to use a dialog box to hold a set of related controls. Dialog boxes are primarily used to
obtain user input and are often child windows of a top-level window. Dialog boxes don’t have menu bars, but in
other respects, they function like frame windows. (You can add controls to them, for example, in the same way
that you add controls to a frame window.) Dialog boxes may be modal or modeless. When a modal dialog box is
active, all input is directed to it until it is closed. This means that you cannot access other parts of your program
until you have closed the dialog box. When a modeless dialog box is active, input focus can be directed to
another window in your program. Thus, other parts of your program remain active and accessible. Dialog boxes
are of type Dialog. Two commonly used constructors are shown here:
Dialog(Frame parentWindow, boolean mode)
Dialog(Frame parentWindow, String title, boolean mode)
Here, parentWindow is the owner of the dialog box. If mode is true, the dialog box is modal.
Otherwise, it is modeless. The title of the dialog box can be passed in title. Generally, you
will subclass Dialog, adding the functionality required by your application.
60

You might also like