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

ch1 - GUI & Event-Driven Programming

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

CHAPTER-1

1.INTRODUCTION TO GUI AND EVENT-DRIVEN PROGRAMMING:


The type of user interface we cover in this chapter is called a graphical user interface (GUI).

Till now we use the user interface that uses System.in and System.out and these are known
as non-GUI, or console user interface.

GUI-based programs are implemented by using the GUI classes and these classes are present
in standard javax.swing and java.awt packages. And we can refer to them collectively
known as GUI classes.

When we need to differentiate them, we will refer to the classes from javax.swing as Swing
classes and those from java.awt as AWT classes.

In the older versions of Java (before Java 2 SDK 1.2), we had only AWT classes to build GUI-
based programs. Many of the AWT classes are now supressed by the Swing classes (e.g.,
AWT Button class is supressed by Swing JButton class).

AWT classes are still available, but it is generally preferable to use Swing classes.
There are two main advantages in using the Swing classes over the AWT classes are
1. First, the Swing classes provide greater compatibility across different operating
systems. The Swing classes are implemented fully in Java, and they behave the same
on different operating systems. The AWT classes are implemented by using the native
GUI objects. For example, an AWT Button is implemented by using the Windows
button object for the Windows operating system, the Macintosh button object for
the Mac operating system, and so on. So, we can call the Swing classes are called
lightweight classes and the AWT classes heavyweight classes. Depending on their
implementation.
2. Second, the Swing classes support many new functionalities not supported by the
AWT counterparts. For example, we can easily display an image inside a button in
addition to a text by using a Swing JButton, but only text can be displayed inside a
button with an AWT Button.
To build an effective graphical user interface using objects from the javax.swing and
java.awt packages, we must learn a new style of program control called event driven
programming. An event occurs when the user interacts with a GUI object. For example,
when you move the cursor, click on a button, or select a menu choice, an event occurs.
In this chapter we will learn the fundamentals of event-driven programming.
2. Simple GUI I/O with JOptionPane
One of the easiest ways to provide a simple GUI-based input and output is by using the
JOptionPane class.
In a GUI environment, there are basically two types of windows:
1.a general purpose frame

2. a special-purpose dialog.
In Java, we use a JFrame object for a frame window and a JDialog object for a dialog.
The first argument to the showMessageDialog method is a frame object that controls
this dialog.
Example 1:
1. Display the message I Love Java by using JOptionPane.
/*Chapter 14 Sample Program: Shows a Message Dialog*/
/*File: Ch14ShowMessageDialog1.java*/
import javax.swing.*;
class Ch14ShowMessageDialog1 {
public static void main (String [] args) {

JOptionPane.showMessageDialog(null, "I LOVE JAVA");

}
}

The second argument is the text to display.


In the example statement, we pass null, a reserved word, meaning there is no frame
object. If we pass null as the first argument, the dialog appears on the center of the
screen. If we pass a frame object, then the dialog is positioned at the center of the
frame. Run the Ch14ShowMessageDia log class and confirm this behavior.
Example 2:
/* Chapter 14 Sample Program: Shows a Message Dialog
File: Ch14ShowMessageDialog.java*/
import javax.swing.*;
class Ch14ShowMessageDialog {
public static void main(String[] args){
JFrame jFrame;
jFrame = new JFrame();
jFrame.setSize(400,300);
jFrame.setVisible(true);
JOptionPane.showMessageDialog(jFrame, "How are you?");
JOptionPane.showMessageDialog(null, "Good Bye");
}
OUTPUT: When we Press OK then it will display a msg that GOOd Bye

Good Bye msg is not going to print on Frame why because we r not passing in jframe.
We r putting the null value. If we pass jFrame then Good Bye msg will display in
frame only.
Give the assignment.

Program 3: If we want to display multiple lines of text, we can use a special


character sequence \n to separate the lines
/*File: Ch14ShowMessageDialog2.java*/
import javax.swing.*;
class Ch14ShowMessageDialog2 {
public static void main (String [] args) {
JOptionPane.showMessageDialog(null, "one\ntwo\nthree");
}
}
OUTPUT:
Output will be print on Window
Program 4:If we want to display multiple lines of text, we can use a special
character sequence \n to separate the lines on a frame then

/*File: Ch14ShowMessageDialog3.java*/
import javax.swing.*;
class Ch14ShowMessageDialog3 {
public static void main (String [] args) {
JFrame jFrame;
jFrame = new JFrame();
jFrame.setSize(400,300);
jFrame.setVisible(true);
JOptionPane.showMessageDialog(jFrame,"one\ntwo\nthree" );
}
}
OUTPUT:
Output will print on FRAME

We can also use the JOptionPane class for input by using its showInputDialog
method. For example, when we execute JOptionPane.showInputDialog(null, "Enter
text:"); the dialog shown on the screen.
To assign the name input to an input string, we write String input; input =
JOptionPane.showInputDialog(null, "Enter text:");
Program 5: Write a Program to print the text
/*File: Ch14ShowMessageDialog4.java*/
import javax.swing.*;
class Ch14ShowMessageDialog4 {
public static void main (String [] args) {
String input;
input = JOptionPane.showInputDialog(null, "Enter text:");
}
}
OUTPUT:

The Scanner class supports different input methods for specific data types, for example
nextInt and nextDouble but the JOptionPane supports only a string input. To input a
numerical value, we need to perform the string conversion ourselves.

If the user enters a string that cannot be converted to an int, for example, 12.34 or abc123, a
NumberFormatException error will result. We use corresponding wrapper classes to
convert the string input to other numerical data values.

List of common wrapper classes and their corresponding conversion methods:

Exercise:

2.Using JOptionPane input dialog, write a statement to input the person’s first name.
/*File: Ch14ShowMessageDialog5.java*/
import javax.swing.*;
class Ch14ShowMessageDialog5 {
public static void main (String [] args) {
String firstname;
firstname = JOptionPane.showInputDialog(null, "Enter the First Name:");
}
}
OUTPUT:

2. Using JOptionPane input dialog, write a statement to input the person’s age
(integer)
/*File: Ch14ShowMessageDialog6.java*/
import javax.swing.*;
class Ch14ShowMessageDialog6 {
public static void main (String [] args) {
String str;
str= JOptionPane.showInputDialog(null, "Enter age:");
int age = Integer.parseInt(str);
}
}
OUTPUT:

14.2 Customizing Frame Windows


To create a customized user interface, we often define a subclass of the JFrame class.
The JFrame class contains the most basic functionalities to support features found in
any frame window, such as minimizing the window, moving the window, and resizing
the window.
In writing practical programs, we normally do not create an instance of the JFrame
class because a JFrame object is not capable of doing anything meaningful. For
example, if we want to use a frame window for a word processor, we need a frame
window capable of allowing the user to enter, cut and paste text; change font; print
text; and so forth. To design such a frame window, we would define a subclass of the
JFrame class and add methods and data members to implement the needed
functionalities.
Program:1
/*Chapter 14 Sample Program: Displays a default JFrame window*/
/* File: Ch14DefaultJFrame.java*/
import javax.swing.*;
class Ch14DefaultJFrame {
public static void main(String[] args){
JFrame defaultJFrame;
defaultJFrame = new JFrame();
defaultJFrame.setVisible(true);
}
}
OUTPUT:

Now let’s define a subclass of the JFrame class and add some default characteristics.
To define a subclass of another class, we declare the subclass with the reserved word
extends.
Example:
class Ch14JFrameSubclass1 extends JFrame {
...
}
For the Ch14JFrameSubclass1 class, we will add the following default characteristics:
• The title is set to My First Subclass.
• The program terminates when the Close box is clicked.
• The size of the frame is set to 300 pixels wide and 200 pixels high.
• The frame is positioned at screen coordinate (150, 250).

All these properties are set inside the default constructor. To set the frame’s title, we
pass the title to the setTitle method. To set the frame’s size, we pass its width and
height to the setSize method. To position the frame’s top left corner to the
coordinate (x, y), we pass the values x and y to the setLocation method. Finally, to
terminate the program when the frame is closed, we call the
setDefaultCloseOperation with the class constant EXIT_ON_CLOSE as an argument.
Notice the methods such as setTitle, setSize, and others are all defined in the JFrame
and its ancestor classes or superclasses in the inheritance hierarchy. Every method of
a superclass is inherited by its subclass. Because the subclass superclass relationships
are formed into an inheritance hierarchy, a subclass inherits all methods defined in
its ancestor classes or super classes. And we can call an inherited method from the
method of a subclass in the manner identical to calling a method defined in the
subclass, that is, without using dot notation or by using dot notation with the
reserved word this.
TheCh14JFrameSubclass1 class is declared as follows:
/* Chapter 14 Sample Program: A simple subclass of JFrame
File: Ch14JFrameSubclass1.java*/
import javax.swing.*;
class Ch14JFrameSubclass1 extends JFrame {
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 200;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
public Ch14JFrameSubclass1( ){
//set the frame default properties
setTitle("My First Subclass");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setLocation (FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
//register 'Exit upon closing' as a default close operation
setDefaultCloseOperation( EXIT_ON_CLOSE );
}
}
/*Chapter 14 Sample Program: Displays a default Ch14JFrameSubclass window
File: Ch14TestJFrameSubclass.java */
/* Also notice that there’s no need to import the javax.swing package because the
main class does not make any direct reference to the classes in this package./

class Ch14TestJFrameSubclass {
public static void main(String[] args){
Ch14JFrameSubclass1 myFrame;
myFrame = new Ch14JFrameSubclass1();
myFrame.setVisible(true);
}
}

OUTPUT:
C:>javac Ch14TestJFrameSubclass.java
C:>java Ch14TestJFrameSubclass

Inherited methods are called from the method of a subclass without using dot
notation or by using dot notation with the reserved word this.

Since we did not set the background color for Ch14JFrameSubclass1, the default
white was used as the frame’s background color. (Note: If you see a different
background color, such as gray, then most likely you are using an older version of
Java, SDK 1.4 or earlier.) Let’s define another subclass named Ch14JFrameSubclass2
that has a blue background color instead. We will define this class as an instantiable
main class so we don’t have to define a separate main class. To make the background
appear in blue, we need to access the content pane of a frame. Aframe’s content
pane designates the area of the frame that excludes the title and menu bars and the
border. It is the area we can use to display the content (text, image, etc.). We access
the content pane of a frame by calling the frame’s getContentPane method. And to
change the background color to blue, we call the content pane’s setBackground
method. We carry out these operations in the private:

/*Chapter 14 Sample Program: A simple subclass of JFrame


that changes the background color to blue.
Chapter 14 GUI and Event-Driven Programming
File: Ch14JFrameSubclass2.java */
import javax.swing.*;
import java.awt.*;
class Ch14JFrameSubclass2 extends JFrame {
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 200;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
public static void main(String[] args){
Ch14JFrameSubclass2 frame = new Ch14JFrameSubclass2();
frame.setVisible(true);
}
public Ch14JFrameSubclass2() {
//set the frame default properties
setTitle("Blue Background JFrame Subclass");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
//register 'Exit upon closing' as a default close operation
setDefaultCloseOperation(EXIT_ON_CLOSE);
changeBkColor();
}
private void changeBkColor() {
Container contentPane = getContentPane();
contentPane.setBackground(Color.BLUE); // IF WE WANT TO PRINT RED THEN
WRITE Color.RED
}
}

OUTPUT:
C:>javac Ch14JFrameSubclass2.java
C:>java Ch14JFrameSubclass2

14.3 GUI Programming Basics:


In this section, we will develop a sample frame window that illustrates the funda
mentals of GUI programming. The sample frame window has two buttons labelled
CANCEL and OK. When you click the CANCEL button, the window’s title is changed to
You clicked CANCEL. Likewise, when you click the OK button, the window’s title is
changed to You clicked OK.
There are two key aspects involved in GUI programming. One is the placement of
GUI objects on the content pane of a frame and the other is the handling of events
generated by these GUI objects.
Button Placement
The type of button we use here is called a pushbutton. Since we discuss the push
buttons only in this chapter, we will simply call them buttons. To use a button in a
program, we create an instance of the javax.swing.JButton class. We will create two
buttons and place them on the frame’s content pane in the constructor. Let’s name
the two buttons cancelButton and okButton. We declare and create these buttons in
the following manner:
import javax.swing.*;
...
JButton cancelButton, okButton;
cancelButton = new JButton("CANCEL");
okButton = new JButton("OK");
The text we pass to the constructor is the label of a button. After the buttons are
created, we must place them on the frame’s content pane. There are two general
approaches to placing buttons (and other types of GUI objects) on a frame’s content
pane, one that uses a layout manager and another that does not. The layout
manager for a container is an object that controls the placement of the GUI objects.
For example, the simplest layout manager called FlowLayout places GUI objects in
the top-to-bottom, left-to-right order. If we do not use any lay out manager, then we
place GUI objects by explicitly specifying their position and size on the content pane.
We call this approach absolute positioning. In this section, we will use FlowLayout.

To use the flow layout, we set the layout manager of a frame’s content pane by
passing an instance of FlowLayout to the setLayout method:

contentPane.setLayout(new FlowLayout());
After the layout manager is set, we add the two buttons to the content pane, so they
become visible when the frame is displayed on the screen:
contentPane.add(okButton);
contentPane.add(cancelButton);
Notice that the sizes of the OK and CANCEL buttons are different. The de fault size of
a button depends on the number of characters in the button’s label. We can override
the default by calling the setSize method. For example, we can set their width to 80
pixels and height to 30 pixels by writing
okButton.setSize(80, 30);
cancelButton.setSize(80, 30);
However, the setSize method does not take effect when the layout manager is used.
It only works with absolute positioning. We won’t be using the setSize method
here.
/* Chapter 14 Sample Program: Displays a frame with two buttons
File: Ch14JButtonFrame.java*/
import javax.swing.*;
import java.awt.*;
class Ch14JButtonFrame extends JFrame {
static final int FRAME_WIDTH = 300;
static final int FRAME_HEIGHT = 200;
static final int FRAME_X_ORIGIN = 150;
static final int FRAME_Y_ORIGIN = 250;
JButton cancelButton;
JButton okButton;
public static void main(String[] args){
Ch14JButtonFrame frame = new Ch14JButtonFrame();
frame.setVisible(true);
}
public Ch14JButtonFrame() {
Container contentPane = getContentPane( );
//set the frame properties
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setTitle("Program Ch14JButtonFrame");
setLocation (FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
//set the layout manager
contentPane.setLayout(new FlowLayout());
//create and place two buttons on the frame's content pane
okButton = new JButton("OK");
contentPane.add(okButton);
cancelButton = new JButton("CANCEL");
contentPane.add(cancelButton);
//register 'Exit upon closing' as a default close operation
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
OUTPUT:

When we run the program, we see two buttons appear on the frame. We can click
the buttons, but nothing happens, of course, because the code to handle the button
clicks is not yet added to the class. We’ll add the required code next.
Handling Button Events
Now let’s study how we process the button clicks. An action such as clicking a but ton
is called an event, and the mechanism to process the events event handling. The
event-handling model of Java is based on the concept known as the
delegationbased event model. With this model,
event handling is implemented by two types of objects: event source objects and
event listener objects.
AGUI object, such as a button, where the event occurs is called an event, or simply,
the event source. We say an event source generates events. So, for example, when
the user clicks on a button, the corresponding JButton object will generate an action
event. When an event is generated, the system notifies the relevant event listener
objects. An event listener object, or simply an event listener, is an object that
includes a method that gets executed in response to generated events. It is possible
for a single object to be both an event source and an event listener.
Among the many different types of events, the most common one is called an action
event. For example, when a button is clicked or a menu item is selected, an event
source will generate an action event. For the generated events to be processed, we
must associate, or register, event listeners to the event sources. If the event sources
have no registered listeners, then generated events are simply ignored (this is what
happened in the Ch14JButtonFrame program).
For each type of event, we have a corresponding listener. For example, we have
action listeners for action events, window listeners for window events, mouse
listeners for mouse events, and so forth.
If we wish to process the action events generated by a button, then we must
associate an action listener to the button.
An object that can be registered as an action listener must be an instance of a
class that is declared specifically for the purpose. We call such class an action
listener class. For this sample program, let’s name the action listener class
ButtonHandler. We will describe how to define the ButtonHandler class shortly.
But first we will show the step to register an instance of ButtonHandler as the action
listenerof the two action event sources—okButton and cancelButton—of the sample
frame window.
An action listener is associated to an action event source by calling the event
source’s addActionListener method with this action listener as its argument. For ex
ample, to register an instance of ButtonHandler as an action listener of okButton
and cancelButton, we can execute the following code:
ButtonHandler handler = new ButtonHandler( );
okButton.addActionListener(handler);
cancelButton.addActionListener(handler);
Notice that we are associating a single ButtonHandler object as an action listener of
both buttons, because, although we can, it is not necessary to associate two separate
listeners, one for the OK button and another for the CANCEL button. A single listener
can be associated to multiple event sources. multiple listeners can be associated to
a single event source.
A single listener can be associated to multiple event sources,and multiple listeners
can be associated to a single event source
When an event source generates an event, the system checks for matching
registered listeners (e.g., for action events the system looks for registered action
listeners, for window events the system looks for registered window listeners, and
so forth). If there is no matching listener, the event is ignored. If there is a matching
listener, the system notifies the listener by calling the listener’s corresponding
method. In case of action events, this method is actionPerformed. To ensure that the
programmer includes the necessary actionPerformed method in the action listener
class, the class must implement the ActionListener interface. The ButtonHandler
class, for example, must be defined in the following way:
An argument to the actionPerformed method is an ActionEvent object that repre
sents an action event, and the ActionEvent class includes methods to access the
properties of a generated event.
We want to change the title of a frame to You clicked OK or You clicked CANCEL
depending on which button is clicked. This is done inside the actionPerformed
method. The general idea of the method is as follows:

The first statement retrieves the text of the event source (the text of the okButton is
the string OK and the text of the cancelButton is the string CANCEL). We can do this
in two ways. The first way is to use the getActionCommand method of the action
event object evt. Using this method, we can retrieve the text of the clicked button as

String buttonText = evt.getActionCommand();

The second way is to use the getSource method of the action event object evt.
Using this method, we can retrieve the text of the clicked button as
Notice the typecasting of an object returned by the getSource method to JButton.
The object returned by the getSource method can be an instance of any class, so we
need to typecast the returned object to a proper class in order to use the desired
method. Now, to find the frame that contains the event source, we proceed in two
steps. First, we get the root pane to which this event source belongs. Second, we get
the frame that contains this root pane. Here’s the necessary sequence of statements
to access the frame that contains the event source:

A frame window contains nested layers of panes (the content pane in which we place
GUI objects is one of them). The topmost pane is called the root pane (an instance of
JRootPane). We can access the root pane of a frame by calling the GUI object’s
getRootPane method. From the root pane, we can access the frame object by calling
the root pane’s getParent method. Because a root pane can be contained by
different types of containers (frames, dialogs, etc.), we need to typecast the re
turned object to JFrame in this example.

Program : Write a sample program that a frame window has two buttons labeled
CANCEL and OK. When you click the CANCEL button, the window’s title is changed
to You clicked CANCEL. Likewise, when you click the OK button, the window’s title
is changed to You clicked OK.
Program:
/* Chapter 14 Sample Program: Displays a frame with two buttons
and associates an instance of ButtonHandler to the two buttons
File: Ch14JButtonEvents.java*/
import javax.swing.*;
import java.awt.*;
class Ch14JButtonEvents extends JFrame {
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 200;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
private JButton cancelButton;
private JButton okButton;
public static void main(String[] args){
Ch14JButtonEvents frame = new Ch14JButtonEvents();
frame.setVisible(true);
}
public Ch14JButtonEvents() {
Container contentPane = getContentPane( );
//set the frame properties
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable (false);
setTitle("Program Ch14JButtonFrame");
setLocation (FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
//set the layout manager
contentPane.setLayout(new FlowLayout());
//create and place two buttons on the frame's content pane
okButton = new JButton("OK");
contentPane.add(okButton);
cancelButton = new JButton("CANCEL");
contentPane.add(cancelButton);
//registering a ButtonHandler as an action listener of the
//two buttons
ButtonHandler handler = new ButtonHandler();
cancelButton.addActionListener(handler);
okButton.addActionListener(handler);
//register 'Exit upon closing' as a default close operation
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
/* Chapter 14 Sample Program: Event listener for button click events
File: ButtonHandler.java*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class ButtonHandler implements ActionListener {
public ButtonHandler() {
}
public void actionPerformed(ActionEvent event){
JButton clickedButton = (JButton) event.getSource();
JRootPane rootPane = clickedButton.getRootPane();
Frame frame = (JFrame) rootPane.getParent();
String buttonText = clickedButton.getText();
frame.setTitle("You clicked " + buttonText);
}
}
Output:
C:\Users\drraf>javac Ch14JButtonEvents.java
C:\Users\drraf>java Ch14JButtonEvents

Making a Frame the Event Listener:


Instead of creating a separate event listener class such as ButtonHandler, it is actually
more common to let a frame be the event listener of the GUI objects it contains.
We already know that any class can implement the ActionListener interface.
We can declare a subclass of JFrame that implements the ActionListener interface.
As an illustration of this technique, let’s define a subclass of JFrame called
Ch14JButton FrameHandler. This class combines the functionalities of the
Ch14JButtonEvents and ButtonHandler classes.
/* Chapter 14 Sample Program: Displays a frame with two buttons
and handles the button events File: Ch14JButtonFrameHandler.java*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Ch14JButtonFrameHandler extends JFrame implements ActionListener {
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 200;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
private JButton cancelButton;
private JButton okButton;
public static void main(String[] args){
Ch14JButtonFrameHandler frame = new Ch14JButtonFrameHandler();
frame.setVisible(true);
}
public Ch14JButtonFrameHandler() {
Container contentPane = getContentPane( );
//set the frame properties
setSize
(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setTitle
("Program Ch14JButtonFrameHandler");
setLocation (FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
//set the layout manager
contentPane.setLayout(new FlowLayout());
//create and place two buttons on the frame's content pane
okButton = new JButton("OK");
contentPane.add(okButton);
cancelButton = new JButton("CANCEL");
contentPane.add(cancelButton);
//register this frame as an action listener of the two buttons
cancelButton.addActionListener(this);
okButton.addActionListener(this);
//register 'Exit upon closing' as a default close operation
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent event){
JButton clickedButton = (JButton) event.getSource();
String buttonText = clickedButton.getText();
setTitle("You clicked " + buttonText);
}
}
OUTPUT:
Notice how we call the addActionListener method of cancelButton and okButton.
This frame object is the action event listener, so we pass it as an argument to the
method as
cancelButton.addActionListener(this);
okButton.addActionListener(this);
Likewise, because the actionPerformed method now belongs to this frame class
itself, we can call other methods of the frame class from the actionPerformed
method without dot notation. So the statement to change the title is simply
setTitle("You clicked " + buttonText);
1. What is the purpose of a layout manager?
The layout manager for a container is an object that controls the placement of
the GUI objects. For example, the simplest layout manager called FlowLayout
places GUI objects in the top-to-bottom, left-to-right order. If we do not use any
lay out manager, then we place GUI objects by explicitly specifying their position
and size on the content pane. We call this approach absolute positioning.
2. Which object generates events? Which object processes events?
An event source generates events. So, for example, when the user clicks on a
button, the corresponding JButton object will generate an action event. When an
event is generated, the system notifies the relevant event listener objects. An
event listener object, or simply an event listener, is an object that includes a
method that gets executed in response to generated events. It is possible for a
single object to be both an event source and an event listener.
3. A class that implements the ActionListener interface must implement which
method?
When an event source generates an event, the system checks for matching registered
listeners (e.g., for action events the system looks for registered action listeners, for
window events the system looks for registered window listeners, and so forth). If
there is no matching listener, the event is ignored. If there is a matching listener, the
system notifies the listener by calling the listener’s corresponding method. In case of
action events, this method is actionPerformed. To ensure that the programmer
includes the necessary actionPerformed method in the action listener class, the
class must implement the ActionListener interface.

3. What does the getActionCommand method of the ActionEvent class return?


use the getActionCommand method of the action event object evt. Using this
method, we can retrieve the text of the clicked button as
String buttonText = evt.getActionCommand();
14.4: Text-Related GUI Components:

There are 3 swing GUI classes are there which deals with text—JLabel, JTextField,
and JTextArea. The first two deal with a single line of text and the last with
multiple lines of text.
A JTextField object allows the user to enter a single line of text, while a JLabel
object is for displaying uneditable text. A JTextArea object allows the user to
enter multiple lines of text. It can also be used for displaying multiple lines of
uneditable text.
JLabel object doesn’t generate any event.
JTextField object generates an action event when the user presses the Enter key
while the object is active.
A JTextArea object also generates text events and document events.
In JTextField class first We set a JTextField object’s size and position and register
its action listener in the same way as we did for the JButton class.
public Ch14TextFrame1
{
JTextField inputLine;
inputLine = new JTextField();
inputLine.setColumns(22);
add(inputLine);
inputLine.addActionListener(this);
}
Now we need to modify the actionPerformed method to handle both the button
click events and the Enter key events. We have three event sources (two buttons
and one text field), so the first thing we must do in the actionPerformed method
is to determine the source. We will use the instanceof operator to determine the
class
to which the event source belongs.
Here’s the general idea:
if (event.getSource() instanceof JButton){
//event source is either cancelButton
//or okButton
...
} else { //event source must be inputLine
...
}
/*Chapter 14 Sample Program: Displays a frame with two buttons and one text
field File: Ch14TextFrame1.java */
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Ch14TextFrame1 extends JFrame implements ActionListener {
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 200;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
private JButton cancelButton;
private JButton okButton;
private JTextField inputLine;
public static void main(String[] args)
{
Ch14TextFrame1 frame = new Ch14TextFrame1();
frame.setVisible(true);
}
public Ch14TextFrame1() {
Container contentPane;
//set the frame properties
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setTitle ("Program Ch14SecondJFrame");
setLocation (FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
inputLine = new JTextField( );
inputLine.setColumns(82);
contentPane.add(inputLine);
inputLine.addActionListener(this);
//create and place two buttons on the frame
okButton = new JButton ("OK");
contentPane.add(okButton);
cancelButton = new JButton ("CANCEL");
contentPane.add(cancelButton);
//register this frame as an action listener of the two buttons
cancelButton.addActionListener(this);
okButton.addActionListener(this);
//register 'Exit upon closing' as a default close operation
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent event){
if (event.getSource() instanceof JButton){
JButton clickedButton = (JButton) event.getSource();
String buttonText = clickedButton.getText();
setTitle("You clicked " + buttonText);
} else { //the event source is inputLine
setTitle("You entered '" + inputLine.getText() + "'");
}
}
}
OUTPUT:
C:\Users\drraf>javac Ch14TextFrame1.java

C:\Users\drraf>java Ch14TextFrame1

Now, let’s add a JLabel object to the frame. In the Ch14TextFrame1 class, we have
one text field without any indication of what this text field is for. A JLabel object is
useful in displaying a label that explains the purpose of the text field.
Let’s modify the Ch14TextFrame1 class by placing the label Please enter your
name above the inputLine text field. We will call the modified class
Ch14TextFrame2.
public Ch14TextFrame2 {
...
prompt = new JLabel( );
prompt.setText("Please enter your name");
prompt.setSize(150, 25);
contentPane.add(prompt);
...
}
We can also set the text at the time of object creation as
prompt = new JLabel("Please enter your name");
/*Chapter 14 Sample Program: Displays a frame with two buttons and one text
field File: Ch14TextFrame2.java */
import javax.swing.*;
import java.awt.*;
import java.
awt.event.*;
class Ch14TextFrame2 extends JFrame implements ActionListener {
private static final int FRAME_WIDTH = 600;
private static final int FRAME_HEIGHT = 400;
private static final int FRAME_X_ORIGIN = 50;
private static final int FRAME_Y_ORIGIN = 150;
private JButton cancelButton;
private JButton okButton;
private JTextField inputLine;
private JLabel prompt;
private JLabel image;
public static void main(String[] args)
{
Ch14TextFrame2 frame = new Ch14TextFrame2();
frame.setVisible(true);
}
public Ch14TextFrame2() {
Container contentPane;
//set the frame properties
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setTitle ("Program Ch14SecondJFrame");
setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
//image = new JLabel(new ImageIcon("cat.gif"));
//image.setSize(50, 50);
//contentPane.add(image);
prompt = new JLabel( );
prompt = new JLabel("Please enter your name");
contentPane.add(prompt);
inputLine = new JTextField( );
inputLine.setColumns(84);
contentPane.add(inputLine);
inputLine.addActionListener(this);
//create and place two buttons on the frame
okButton = new JButton ("OK");
contentPane.add(okButton);
cancelButton = new JButton ("CANCEL");
contentPane.add(cancelButton);
//register this frame as an action listener of the two buttons
cancelButton.addActionListener(this);
okButton.addActionListener(this);
//register 'Exit upon closing' as a default close operation
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent event){
if (event.getSource() instanceof JButton){
JButton clickedButton = (JButton) event.getSource();
String buttonText = clickedButton.getText();
setTitle("You clicked " + buttonText);
} else { //the event source is inputLine
setTitle("You entered '" + inputLine.getText() + "'");
}
}
}
OUTPUT:
C:\Users\drraf>javac Ch14TextFrame2.java
C:\Users\drraf>java Ch14TextFrame2

If we want to add any image then


private JLabel image;
and then create it in the constructor as
public Ch14TextFrame2 {
...
image = new JLabel(new ImageIcon("cat.gif"));
image.setSize(50, 50);
contentPane.add(image);
...
}
OUTPUT:
Now let’s create the third example by using a JTextArea object. We will call the
sample class Ch14TextFrame3. In this sample program, we will add two buttons
labeled ADD and CLEAR, one text field, and one text area to a frame.

In BorderFactory class we called the createLineBorder method with a Color


object as its argument. We passed Color.RED so the red rectangle is displayed.
The createLineBorder method returns a properly created Border object, and we
pass this Border object to the setBorder method of the text area object.

/* Chapter 14 Sample Program: Displays a frame with two buttons,


one text field, and one text area
File: Ch14TextFrame3.java */
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Ch14TextFrame3 extends JFrame implements ActionListener
{
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 250;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
private static final String EMPTY_STRING = "";
private static final String NEWLINE=System.getProperty("line.separator");
private JButton clearButton;
private JButton addButton;
private JTextField inputLine;
private JTextArea textArea;
public static void main(String[] args)
{
Ch14TextFrame3 frame = new Ch14TextFrame3();
frame.setVisible(true);
}
public Ch14TextFrame3()
{
Container contentPane;
//set the frame properties
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setTitle("Program Ch14TextFrame3");
setLocation (FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
contentPane = getContentPane();
contentPane.setLayout(new FlowLayout ());
textArea = new JTextArea();
textArea.setColumns(22);
textArea.setRows(8);
textArea.setBorder(BorderFactory.createLineBorder(Color.RED));
textArea.setEditable(false);
contentPane.add(textArea);
inputLine = new JTextField();
inputLine.setColumns(22);
contentPane.add(inputLine);
inputLine.addActionListener(this);
//create and place two buttons on the frame
addButton = new JButton ("ADD");
contentPane.add(addButton);
clearButton = new JButton ("CLEAR");
contentPane.add(clearButton);
//register this frame as an action listener of the two buttons
clearButton.addActionListener(this);
addButton.addActionListener(this);
//register 'Exit upon closing' as a default close operation
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent event){
if (event.getSource() instanceof JButton)
{
JButton clickedButton = (JButton) event.getSource();
if (clickedButton == addButton)
{
addText(inputLine.getText());
}
else
{
clearText();
}
}
else
{
//the event source is inputLine
addText(inputLine.getText());
}
}
private void addText(String newline)
{
textArea.append(newline + NEWLINE);
inputLine.setText("");
}
private void clearText()
{
textArea.setText(EMPTY_STRING);
inputLine.setText(EMPTY_STRING);
}
}
OUTPUT:
C:\Users\drraf>javac Ch14TextFrame3.java
C:\Users\drraf>java Ch14TextFrame3

Using a JScrollPane to Add Scroll Bars Automatically


When we run the Ch14TextFrame3 class and add more rows (lines) of text than
the number of rows set by calling the setRows method, what happens? The
height
of the text area gets taller. Likewise, the text area expands horizontally when
we enter a line longer than the specified width. This is not a desired behavior.
The
easiest way to handle the situation is to wrap the text area with an instance of
javax.swing.JScrollPane that adds the vertical and horizontal scroll bars when
necessary.
In the original Ch14TextFrame3 class, this is what we did to create and set the
JTextArea object:
textArea = new JTextArea();
textArea.setColumns(22);
textArea.setRows(8);
textArea.setBorder( BorderFactory.createLineBorder(Color.RED));
textArea.setEditable(false);
contentPane.add(textArea);
To add scroll bars that will appear automatically when needed, we replace the
last
statement above with the following:
JScrollPane scrollText= new JScrollPane(textArea);
scrollText.setSize(200, 135);
contentPane.add(scrollText);
Notice that the properties, such as the border and bounds, of the JScrollPane
object
are set, no longer the properties of the JTextArea.
OUTPUT:

14.5 Layout Managers:


A benefit of using a layout manager is the automatic adjustment of GUI objects
when their container (frame,dialog,applet,etc.) is resized. For example,if we place
a JButton at the center of the container by using some layout manager, then this
JButton will still be positioned at the center when the size of the container is
changed.
This automatic adjustment is important also when we consider running our
program on different platforms,because by using a layout manager effectively we
will get a more consistent look to our frames and dialogs across different
platforms With absolute positioning, a frame that looks nice on one platform may
not appear as nice on another platform.
The most basic layout is java.awt.FlowLayout.
In using this layout, GUI com ponents are placed in left-to-right order.
When the component does notfiton the same line, left-to-right placement
continues on the next line.
As a default, components on each line are centered. When the frame containing
the component is resized, the placement of components is adjusted accordingly.
Example Placement of 5 buttons by using FlowLayout.
Before we add any components, first we assign the desired layout manager to the
container, in this case the content pane of a frame, in the frame’s constructor.
Container contentPane = getContentPane();
...
contentPane.setLayout(new FlowLayout());
After the layout manager is set, we create five buttons and add them to the
content pane.
JButton button1, button2, button3, button4, button5;
...
button1 = new JButton("button1");
//do the same for other buttons
contentPane.add(button1);
contentPane.add(button2);
contentPane.add(button3);
contentPane.add(button4);
contentPane.add(button5);

Notice the default is center alignment. We can change it to left or right alignment
as
contentPane.setLayout(new FlowLayout(FlowLayout.LEFT));
or
contentPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
/* Chapter 14 Sample Program: Illustrates the use of FlowLayout File:
Ch14FlowLayoutSample.java*/
import javax.swing.*;
import java.awt.*;
class Ch14FlowLayoutSample extends JFrame {
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 200;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
public static void main(String[] args)
{
Ch14FlowLayoutSample frame = new Ch14FlowLayoutSample();
frame.setVisible(true);
}
public Ch14FlowLayoutSample() {
Container contentPane;
JButton button1, button2, button3, button4, button5;
//set the frame properties
setSize
(FRAME_WIDTH, FRAME_HEIGHT);
setTitle
("Program Ch14FlowLayoutSample");
setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
contentPane = getContentPane( );
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(new FlowLayout());
//create and place four buttons on the content pane
button1 = new JButton("button 1");
button2 = new JButton("button 2");
button3 = new JButton("button 3");
button4 = new JButton("button 4");
button5 = new JButton("button 5");
contentPane.add(button1);
contentPane.add(button2);
contentPane.add(button3);
contentPane.add(button4);
contentPane.add(button5);
//register 'Exit upon closing' as a default close operation
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
OUTPUT:
. C:\Users\drraf>javac Ch14FlowLayoutSample.java
C:\Users\drraf>java Ch14FlowLayoutSample
BorderLayout:
The second layout manager is java.awt.BorderLayout. This layout manager di
vides the container into five regions: center, north, south, east, and west.
contentPane.setLayout(new BorderLayout());
and then we place the GUI components, in this case, buttons, with the second
argument specifying the region.
contentPane.add(button1, BorderLayout.NORTH);
contentPane.add(button2, BorderLayout.SOUTH);
contentPane.add(button3, BorderLayout.EAST);
contentPane.add(button4, BorderLayout.WEST);
contentPane.add(button5, BorderLayout.CENTER);
The BorderLayout used in Figures 14.13 and 14.14 has no gapsbetween the
regions, which is the default. We can specify the amount of vertical and
horizontal gaps between the regions in pixels. For example, to leave 10-pixel-wide
gaps and 20-pixel-high gaps between the regions, we create a BorderLayout
object by pass ing these values as arguments to the constructor.
contentPane.setLayout(new BorderLayout(10, 20));
/* Chapter 14 Sample Program: Illustrates the use of BorderLayout
File: Ch14BorderLayoutSample.java */
import javax.swing.*;
import java.awt.*;
class Ch14BorderLayoutSample extends JFrame {
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 200;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
public static void main(String[] args){
Ch14BorderLayoutSample frame = new Ch14BorderLayoutSample();
frame.setVisible(true);
}
public Ch14BorderLayoutSample() {
Container contentPane;
JButton button1, button2, button3, button4, button5;
//set the frame properties
setSize (FRAME_WIDTH, FRAME_HEIGHT);
setTitle ("Program Ch14BorderLayoutSample");
setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
contentPane = getContentPane( );
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(new BorderLayout());
//contentPane.setLayout(newBorderLayout(/*hgap*/10,/*vgap*/11));
//create and place four buttons on the content pane
button1 = new JButton("button 1");
button2 = new JButton("button 2");
button3 = new JButton("button 3");
button4 = new JButton("button 4");
button5 = new JButton("button 5");
contentPane.add(button1, BorderLayout.NORTH);
contentPane.add(button2, BorderLayout.SOUTH);
contentPane.add(button3, BorderLayout.EAST);
contentPane.add(button4, BorderLayout.WEST);
contentPane.add(button5, BorderLayout.CENTER);
//register 'Exit upon closing' as a default close operation
setDefaultCloseOperation( EXIT_ON_CLOSE );
}
}
OUTPUT:
C:\Users\drraf>javac Ch14BorderLayoutSample.java
C:\Users\drraf>java Ch14BorderLayoutSample

There is no gaps between the regions, which is the default. We can specify the
amount of vertical and horizontal gaps between the regions in pixels. For
example, to leave 10-pixel-wide gaps and 20-pixel-high gaps between the regions,
we create a BorderLayout object by pass ing these values as arguments to the
constructor. contentPane.setLayout(new BorderLayout(10, 20));
OUTPUT:
If we want to place only two buttons then
button4 = new JButton("button 4");
button5 = new JButton("button 5");
contentPane.add(button4, BorderLayout.WEST);
contentPane.add(button5, BorderLayout.CENTER);
OUTPUT:

GridLayout:
This layout manager places GUI components on equal-size NX M grids. We can
place five buttons on 2 X3 grids. Components are placed in top-to-bottom, left-
to-right order. We can resized the frame in that the number of rows and columns
remains the same, but the width and height of each region are changed.
To create a GridLayout object, we pass two arguments: number of rows and
number of columns.
contentPane.setLayout(new GridLayout(2, 3));
/* Chapter 14 Sample Program: Illustrates the use of GridLayout
File: Ch14GridLayoutSample.java */
import javax.swing.*;
import java.awt.*;
class Ch14GridLayoutSample extends JFrame {
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 200;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
public static void main(String[] args){
Ch14GridLayoutSample frame = new Ch14GridLayoutSample();
frame.setVisible(true);
}
public Ch14GridLayoutSample() {
Container contentPane;
JButton button1, button2, button3, button4, button5;
//set the frame properties
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setTitle("Program Ch14GridLayoutSample");
setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
contentPane = getContentPane( );
contentPane.setBackground( Color.WHITE );
contentPane.setLayout(new GridLayout(2,3));
//create and place five buttons on the content pane
button1 = new JButton("button 1");
button2 = new JButton("button 2");
button3 = new JButton("button 3");
button4 = new JButton("button 4");
button5 = new JButton("button 5");
contentPane.add(button1);
contentPane.add(button2);
contentPane.add(button3);
contentPane.add(button4);
contentPane.add(button5);
//register 'Exit upon closing' as a default close operation
setDefaultCloseOperation( EXIT_ON_CLOSE );
}
}
OUTPUT:
C:\Users\drraf>javac Ch14GridLayoutSample.java
C:\Users\drraf>java Ch14GridLayoutSample

We then place GUI components in the manner analogous to the one used for
FlowLayout. If the value provided for the number of rows is nonzero, then the
value we specify for the number of columns is actually irrelevant. The layout will
create the designated number of rows and adjust the number of columns so that
all components will fit in the designated number of rows.
For example, placing the five buttons with any one of the following three
statements will result in the same layout, namely, two rows of grids:
contentPane.setLayout(new GridLayout(2, 0));
contentPane.setLayout(new GridLayout(2, 1));
contentPane.setLayout(new GridLayout(2, 5));
Result is same for these 3 staements:
contentPane.setLayout(new GridLayout(3,5));
contentPane.setLayout(new GridLayout(3,0));
OUTPUT:

It is possible not to use any layout manager. If we do not use one, then we place
GUI objects on the frame’s content pane by explicitly specifying their position
and size. We call this approach absolute positioning.
So using absolute positioning is acceptable while learning object-oriented and
event-driven programming. However to build practical GUI-based Java programs,
we must learn how to use layout managers effectively.
To use absolute positioning, we set the layout manager of a frame’s content pane
to none by passing null to the setLayout method:
contentPane.setLayout(null);
After the layout manager is set to null, we place two buttons at the position and
in
the size we want by calling the button’s setBounds method as in
okButton.setBounds(75, 125, 80, 30);

where the first two arguments specify the position of the button and the last two
arguments specify the width and height of the button. Finally, to make a button
ap pear on the frame, we need to add it to the content pane by calling the add
method.
For example:
contentPane.add(okButton);
/* Chapter 14 Sample Program: Shows how the absolute position works
File: Ch14AbsolutePositioning.java */
import javax.swing.*;
import java.awt.*;
class Ch14AbsolutePositioning extends JFrame {
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 220;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
private static final int BUTTON_WIDTH = 80;
private static final int BUTTON_HEIGHT = 30;
private JButton cancelButton;
private JButton okButton;
public static void main(String[] args){
Ch14AbsolutePositioning frame = new Ch14AbsolutePositioning();
frame.setVisible(true);
}
public Ch14AbsolutePositioning() {
Container contentPane = getContentPane();
//set the frame properties
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setTitle("Program Ch14AbsolutePositioning");
setLocation (FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
//set the content pane properties
contentPane.setLayout(null);
contentPane.setBackground(Color.WHITE);
//create and place two buttons on the frame's content pane
okButton = new JButton("OK");
okButton.setBounds(70, 125, BUTTON_WIDTH, BUTTON_HEIGHT);
contentPane.add(okButton);
cancelButton = new JButton("CANCEL");
cancelButton.setBounds(160, 125, BUTTON_WIDTH, BUTTON_HEIGHT);
contentPane.add(cancelButton);
//register 'Exit upon closing' as a default close operation
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
OUTPUT:
C:\Users\drraf>javac Ch14AbsolutePositioning.java
C:\Users\drraf>java Ch14AbsolutePositionin
Effective Use of Nested Panels:
We can place nested panels effectively to get a desired layout of GUI
components. But it is very difficult, to place all GUI components on a single JPanel
or other types of containers.
A better approach is to use multiple panels, placing panels inside other panels.
Implement a nested panel which provides the user interface for playing HiLo.
Note that we only illustrate the visual layout using nested panels. The sample
frames do not include any code for actually playing the games.

sample frame that contains nested panels.Five JPanel objects are used in this
frame.

Example:
/* Chapter 14 Sample Program: Illustration of Nested Panels
File: Ch14NestedPanels2.java*/
import javax.swing.*;
import java.awt.*;
class Ch14NestedPanels2 extends JFrame {
private static final int FRAME_WIDTH = 250;
private static final int FRAME_HEIGHT = 270;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
private final String ENTER = "Enter";
private final String CANCEL = "Cancel";
private final String BLANK = "";
private JTextField guessEntry;
private JLabel hint;
public static void main(String[] args){
Ch14NestedPanels2 frame = new Ch14NestedPanels2();
frame.setVisible(true);
}
public Ch14NestedPanels2() {
JPanel guessPanel, hintPanel,controlPanel, buttonPanel;
JButton enterBtn, cancelBtn;
Container contentPane;
//set the frame properties
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setTitle("Program Ch14NestedPanels2");
setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
contentPane = getContentPane();
contentPane.setLayout(new GridLayout(3, 1));
guessPanel = new JPanel();
guessPanel.setBorder(BorderFactory.createTitledBorder("Your Guess"));
guessPanel.add(guessEntry = new JTextField(10));
hintPanel = new JPanel();
hintPanel.setBorder(BorderFactory.createTitledBorder("Hint"));
hintPanel.add(hint = new JLabel("Let's Play HiLo"));
controlPanel = new JPanel(new BorderLayout());
buttonPanel = new JPanel();
buttonPanel.add(enterBtn = new JButton(ENTER));
buttonPanel.add(cancelBtn = new JButton(CANCEL));
controlPanel.add(buttonPanel, BorderLayout.SOUTH);
contentPane.add(guessPanel);
contentPane.add(hintPanel);
contentPane.add(controlPanel);
}
}
OUTPUT:
C:\Users\drraf>javac Ch14NestedPanels2.java
C:\Users\drraf>java Ch14NestedPanels2
Other GUI Components:

JPanel is a light weight component so we can place JPanel in JFrame.


JPanel is a Container also so we can place JLabel, JButton, JPanel
Some other GUI Components are
JcheckBox:
The JButton class represents a type of button called a pushbutton.
Two other common types of buttons are called check-box and radio buttons.
The JCheckBox class is used to represent check-box buttons. Check-box buttons
are useful in presenting a collection of binary (yes/no, true/false) options.
The frame gives the user the option to select the programming languages he or
she can program with by clicking on the appropriate check-box button.
We deal with the JCheckBox class in a manner very similar to that for the JButton
class. To create a check-box button with a text Java, we write
JCheckBox cbBtn = new JCheckBox("Java");
we can retrieve the text associated to a check-box button by calling its getText
method. We can use the corresponding setText method to change the button
text.
/*Chapter 14 Sample Program: Illustrates the use of JCheckBox
File: Ch14JCheckBoxSample1.java*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Ch14JCheckBoxSample1 extends JFrame implements ActionListener {
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 200;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
private JCheckBox[] checkBox;
public static void main(String[] args){
Ch14JCheckBoxSample1 frame = new Ch14JCheckBoxSample1();
frame.setVisible(true);
}
public Ch14JCheckBoxSample1() {
Container contentPane;
JPanel checkPanel, okPanel;
JButton okButton;
String[] btnText = {"Java", "C++", "Smalltalk", "Ada"};
//set the frame properties
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setTitle("Program Ch14JCheckBoxSample1");
setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
contentPane = getContentPane( );
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(new BorderLayout());
//create and place four check boxes
checkPanel = new JPanel(new GridLayout(0,1));
checkPanel.setBorder(BorderFactory.createTitledBorder("Can Program In"));
checkBox = new JCheckBox[btnText.length];
for (int i = 0; i < checkBox.length; i++){
checkBox[i] = new JCheckBox(btnText[i]);
checkPanel.add(checkBox[i]);
}
//create and place the OK button
okPanel = new JPanel(new FlowLayout());
okButton = new JButton("OK");
okButton.addActionListener(this);
okPanel.add(okButton);
contentPane.add(checkPanel, BorderLayout.CENTER);
contentPane.add(okPanel, BorderLayout.SOUTH);
//register 'Exit upon closing' as a default close operation
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent event){
StringBuffer skill = new StringBuffer("You can program in\n");
for (int i = 0; i < checkBox.length; i++){
if (checkBox[i].isSelected()) {
skill.append(checkBox[i].getText() + "\n ");
}
}
JOptionPane.showMessageDialog(this, skill.toString());
}
}
OUTPUT:
C:\Users\drraf>javac Ch14JCheckBoxSample1.java
C:\Users\drraf>java Ch14JCheckBoxSample1
JCheckBox object generates action events just like other buttons. So, we can
associate an action listener to JCheckBox objects, but it is not that common to
process action events generated by JCheckBox objects. In addition to action
events JcheckBox can generate another type of event called item events.
An item event is generated when the state (selected or deselected) of a check-
box button changes. We can register an instance of a class that implements the
ItemListener interface as an item listener of a JCheckBox object. When an item
event is generated, its itemStateChanged method is called. Inside the method,
we can check the state of change by calling the getStateChange method.
/*Chapter 14 Sample Program: Illustrates the use of JCheckBox
File: Ch14JCheckBoxSample2.java */
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Ch14JCheckBoxSample2 extends JFrame implements
ActionListener,ItemListener
{
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 200;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
private JCheckBox[] checkBox;
public static void main(String[] args)
{
Ch14JCheckBoxSample2 frame = new Ch14JCheckBoxSample2();
frame.setVisible(true);
}
public Ch14JCheckBoxSample2()
{
Container contentPane;
JPanel checkPanel, okPanel;
JButton okButton;
String[] btnText = {"Java", "C++", "Smalltalk", "Ada"};
//set the frame properties
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setTitle("Program Ch14JCheckBoxSample2");
setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
contentPane = getContentPane( );
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(new BorderLayout());
//create and place four check boxes
checkPanel = new JPanel(new GridLayout(0,1));
checkPanel.setBorder(BorderFactory.createTitledBorder("Can Program In"));
checkBox = new JCheckBox[btnText.length];
for (int i = 0; i < checkBox.length; i++){
checkBox[i] = new JCheckBox(btnText[i]);
checkPanel.add(checkBox[i]);
checkBox[i].addItemListener(this);
}
//create and place the OK button
okPanel = new JPanel(new FlowLayout());
okButton = new JButton("OK");
okButton.addActionListener(this);
okPanel.add(okButton);
contentPane.add(checkPanel, BorderLayout.CENTER);
contentPane.add(okPanel, BorderLayout.SOUTH);
//register 'Exit upon closing' as a default close operation
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent event)
{
StringBuffer skill = new StringBuffer("You can program in\n");
for (int i = 0; i < checkBox.length; i++)
{
if (checkBox[i].isSelected())
{
skill.append(checkBox[i].getText() + "\n ");
}
}
JOptionPane.showMessageDialog(this, skill.toString());
}
public void itemStateChanged(ItemEvent event)
{
JCheckBox source = (JCheckBox) event.getSource();
String state;
if (event.getStateChange() == ItemEvent.SELECTED)
{
state = "is selected";
}
else {
state = "is deselected";
}
JOptionPane.showMessageDialog(this, "JCheckBox '" +source.getText() + "' " +
state);
}
}
OUTPUT:
C:\Users\drraf>javac Ch14JCheckBoxSample2.java
C:\Users\drraf>java Ch14JCheckBoxSample2
We can select only one checkbox

If we implement Checkbox by using ActionListener we can select all the check


boxes. If we implement Checkbox by using ActionListener,ItemListener we can
select only one check box at a time.

JRadioButton:
The JRadioButton class is used to represent a type of button called a radio
button.
It is similar to check-box button, you can select or deselect a radio button. But the
difference is you can select or deselect only one radio button at a time from same
group. When we select a new one from the same group then the currently
selected radio button will get deselected.
Radio buttons are useful in allowing the user to select one from a list of
possible choices.
Like JCheckBox, JRadioButton generates both action events and item events. But
the key difference is the requirement to add JRadioButton objects to a button
group, in addition to adding them to a container.
In container some portion that creates radio buttons and adds them to a group
(an instance of a ButtonGroup) and a container (an instance of a JPanel).
/* Chapter 14 Sample Program: Illustrates the use of JRadioButton
File: Ch14JRadioButtonSample.java*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Ch14JRadioButtonSample extends JFrame implements
ActionListener,ItemListener
{
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 200;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
private JRadioButton[] radioButton;
public static void main(String[] args)
{
Ch14JRadioButtonSample frame = new Ch14JRadioButtonSample();
frame.setVisible(true);
}

public Ch14JRadioButtonSample()
{
Container contentPane;
JPanel radioPanel, okPanel;
ButtonGroup languageGroup;
JButton okButton;
String[] btnText = {"Java", "C++", "Smalltalk", "Ada"};
//set the frame properties
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setTitle("Program Ch14JRadioButton");
setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
contentPane = getContentPane( );
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(new BorderLayout());
//create and place four radio buttons
radioPanel = new JPanel(new GridLayout(0,1));
radioPanel.setBorder(BorderFactory.createTitledBorder("Pick your favorite"));
languageGroup = new ButtonGroup();
radioButton = new JRadioButton[btnText.length];
for (int i = 0; i < radioButton.length; i++)
{
radioButton[i] = new JRadioButton(btnText[i]);
radioButton[i].addItemListener(this);
languageGroup.add(radioButton[i]);
radioPanel.add(radioButton[i]);
}
//selects the first choice
radioButton[0].setSelected(true);
//create and place the OK button
okPanel = new JPanel(new FlowLayout());
okButton = new JButton("OK");
okButton.addActionListener(this);
okPanel.add(okButton);
contentPane.add(radioPanel, BorderLayout.CENTER);
contentPane.add(okPanel, BorderLayout.SOUTH);
//register 'Exit upon closing' as a default close operation
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent event)
{
String favorite = null;
int i = 0;
while (favorite == null)
{
if (radioButton[i].isSelected())
{
favorite = radioButton[i].getText();
}
i++;
}
JOptionPane.showMessageDialog(this, "Your favorite language is "+ favorite);
}
public void itemStateChanged(ItemEvent event)
{
JRadioButton source = (JRadioButton) event.getSource();
String state;
if (event.getStateChange() == ItemEvent.SELECTED)
{
state = "is selected";
}
else
{
state = "is deselected";
}
JOptionPane.showMessageDialog(this, "JRadioButton '" +source.getText() +"' " +
state);
}
}
OUTPUT:
C:\Users\drraf>javac Ch14JRadioButtonSample.java
C:\Users\drraf>java Ch14JRadioButtonSample
Every time a radio button is selected, the itemStateChanged method is called
twice. The first time is for the deselection of the currently selected item, and the
second is for the selection of the new item. Also notice the statement
radioButton[0].setSelected(true);
in the constructor. If we don’t include this statement, then no item will be
selected when the frame is first opened. For radio buttons, it is more common to
start with one preselected when they first appear on the screen.
JComboBox:
The JComboBox class presents a combobox. This class is similar to the
JRadioButton class in that it also allows the user to select one item from a list of
possible choices.
The difference between these two are how the choices are presented to the
user. Another name for a combobox is a drop-downlist, which is more descriptive
of its interaction style.
The frame which consist of combobox is having with one combo box and one
pushbutton.
We can construct a new JComboBox by passing an array of String objects
String[] comboBoxItem = {"Java", "C++", "Smalltalk", "Ada"};
JComboBox comboBox = new JComboBox(comboBoxItem);
A JComboBox object generates both action events and item events. An action
event is generated every time a JComboBox is clicked (note it is not that common
to process action events of JComboBox). Every time an item different from the
currently selected item is selected, an item event is generated and the itemState
Changed method is called twice. The first time is for the deselection of the
currently selected item, and the second is for the selection of the new item.
Notice that when the same item is selected again, no item event is generated.
To find out the currently selected item, we call the getSelectedItem method of
JComboBox. Because the return type of this method is Object, we must typecast
to the correct type.
For this example, items are String objects, so we write
String selection = (String) comboBox.getSelectedItem();
we can call the getSelectedIndex method to retrieve the position of the selected
item.
/*Chapter 14 Sample Program: Illustrates the use of JComboBox
File: Ch14JComboBoxSample.java */
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Ch14JComboBoxSample extends JFrame implements
ActionListener,ItemListener
{
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 200;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
private JComboBox comboBox;
public static void main(String[] args)
{
Ch14JComboBoxSample frame = new Ch14JComboBoxSample();
frame.setVisible(true);
}
public Ch14JComboBoxSample()
{
Container contentPane;
JPanel comboPanel, okPanel;
JButton okButton;
String[] comboBoxItem = {"Java", "C++", "Smalltalk", "Ada"};
//set the frame properties
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setTitle("Program Ch14JComboBoxSample");
setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
contentPane = getContentPane( );
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(new BorderLayout());
//create and place a combo box
comboPanel = new JPanel(new FlowLayout());
comboPanel.setBorder(BorderFactory.createTitledBorder("Pick your favorite"));
comboBox = new JComboBox(comboBoxItem);
comboBox.addItemListener(this);
comboPanel.add(comboBox);
//create and place the OK button
okPanel = new JPanel(new FlowLayout());
okButton = new JButton("OK");
okButton.addActionListener(this);
okPanel.add(okButton);
contentPane.add(comboPanel, BorderLayout.CENTER);
contentPane.add(okPanel, BorderLayout.SOUTH);
//register 'Exit upon closing' as a default close operation
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent event)
{
String favorite;
int loc;
favorite = (String) comboBox.getSelectedItem();
loc = comboBox.getSelectedIndex();
JOptionPane.showMessageDialog(this, "Currently selected item '" +favorite + "' is
at index position " + loc);
}
public void itemStateChanged(ItemEvent event)
{
String state;
if (event.getStateChange() == ItemEvent.SELECTED)
{
state = "is selected ";
} else
{
state = "is deselected ";
}
JOptionPane.showMessageDialog(this, "JComboBox Item '" + event.getItem() +"'
" + state);
}
}
OUTPUT:
C:\Users\drraf>javac Ch14JComboBoxSample.java
C:\Users\drraf>java Ch14JComboBoxSample

JList:
The JList class is useful when we need to display a list of items.
Example1: List of students,List of Files.
Example2: A Frame with one JList listing animals with three-letter names and one
pushbutton.
First construct a JList object and pass to an array of String.
String[] names = {"Ape", "Bat", "Bee", "Cat", "Dog", "Eel", "Fox", "Gnu", "Hen",
"Man"};
JList list = new JList (names);
In JList, we have an option of specifying one of the three selection modes:
1.single-selection
2. single-interval
3.multiple-interval.
The single-selection mode allows the user to select only one item at a time.
The single-interval mode allows the user to select a single contiguous interval.
The multiple-interval mode allows the user to select multiple contiguous intervals
(each interval will include one or more items).
The following three statements show how to set the three selection modes:
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
The multiple-interval mode is the default mode
Because multiple items can be selected, we use getSelectedValues and
getSelectedIndices to retrieve an array of selected items and an array of the
indices of the selected items, respectively. The following code will display the
selected items and their index positions:
Object[] name;
int[] loc;
name = list.getSelectedValues();
loc = list.getSelectedIndices();
for (int i = 0; i < name.length; i++)
{
System.out.println((String)name[i] +" at position " + loc[i]);
}
The return type of getSelectedValues is an array of Object, so we typecast each
item in the name array to String before printing it on System.out. If we know the
selection mode is single selection, then we can use getSelectedValue and get
SelectedIndex instead.
Notice in the code that we are not adding a JList object directly to a panel.
Instead, we wrap it in a JScrollPane and add this JScrollPane to a panel because
JList itself does not include scroll bars.
/* Chapter 14 Sample Program: Illustrates the use of JList
File: Ch14JListSample.java */
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Ch14JListSample extends JFrame implements ActionListener
{
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 250;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
private JList list;

public static void main(String[] args){


Ch14JListSample frame = new Ch14JListSample();
frame.setVisible(true);
}
public Ch14JListSample()
{
Container contentPane;
JPanel listPanel, okPanel;
JButton okButton;
String[] names = {"Ape", "Bat", "Bee", "Cat","Dog", "Eel", "Fox", "Gnu","Hen",
"Man", "Sow", "Yak"};
//set the frame properties
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setTitle("Program Ch14JListSample2");
setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
contentPane = getContentPane( );
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(new BorderLayout());
//create and place a JList
listPanel = new JPanel(new GridLayout(0,1));
listPanel.setBorder(BorderFactory.createTitledBorder("Three-letter Animal
Names"));
list = new JList(names);
listPanel.add(new JScrollPane(list));
//list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
//list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
//this is default, so the explicit call is not necessary
//create and place the OK button
okPanel = new JPanel(new FlowLayout());
okButton = new JButton("OK");
okButton.addActionListener(this);
okPanel.add(okButton);
contentPane.add(listPanel, BorderLayout.CENTER);
contentPane.add(okPanel, BorderLayout.SOUTH);
//register 'Exit upon closing' as a default close operation
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent event)
{
Object[] name;
int[] loc;
name = list.getSelectedValues();
loc = list.getSelectedIndices();
System.out.println("Currently selected animal names are");
for (int i = 0; i < name.length; i++){
System.out.println((String)name[i] + " at position " + loc[i]);
}
}
}
OUTPUT:
C:\Users\drraf>javac Ch14JListSample.java
C:\Users\drraf>java Ch14JListSample

Currently selected animal names are


Dog at position 4

Currently selected animal names are


Dog at position 4
Currently selected animal names are
Bat at position 1
JSlider:
The JSlider class represents a slider in which the user can move a nob to a
desired position. The position of the nob on a slider determines the selected
value.
Example: A frame with 3 sliders. This is a classic example of sliders where the user
moves the three nobs to set the red, green, blue (RGB) value in selecting a color.
Values for the R, G, and B range from 0 to 255, inclusive.
Some of properties we can set for a JSlider object are the minimum and
maximum range of values, whether to display the tick marks, the spacing of
major and minor tick marks, whether to display the label for the major tick
marks, and the placement orientation (either vertical or horizontal).
The sliders in the sample program are created and initialized in the following
manner:
JSlider slider = new JSlider();
slider.setOrientation(JSlider.VERTICAL);
slider.setPaintLabels(true); //show tick mark labels
slider.setPaintTicks(true); //show tick marks
slider.setMinimum(MIN_COLOR);
slider.setMaximum(MAX_COLOR);
slider.setValue(MAX_COLOR); //initial position of a nob
slider.setMajorTickSpacing(50);
slider.setMinorTickSpacing(25);
When a nob is moved, a JSlider object generates a change event (this event
occurs when there’s a change in the event source, such as the nob is moved).
To process change events, we must register change event listeners to a JSlider
event source object.
The class that implements the ChangeListener interface must define a method
called stateChanged, whose parameter is an instance of ChangeEvent.
This program, whenever a change event is generated, we read the value from
each slider and set the background of a panel to a designated color. Here’s the
body of the stateChanged method.
int R, G, B;
R = redSlider.getValue();
G = greenSlider.getValue();
B = blueSlider.getValue();
colorPanel.setBackground(new Color (R, G, B));
/*Chapter 14 Sample Program: Illustrates the use of JSlider File:
Ch14JSliderSample.java*/
import javax.swing.event.*;
import javax.swing.*;
import java.awt.*;
class Ch14JSliderSample extends JFrame implements ChangeListener
{
private static final int FRAME_WIDTH = 450;
private static final int FRAME_HEIGHT = 250;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
private static final int MIN_COLOR = 0;
private static final int MAX_COLOR = 255;
private JSlider redSlider;
private JSlider greenSlider;
private JSlider blueSlider;
private JPanel colorPanel;
public static void main(String[] args)
{
Ch14JSliderSample frame = new Ch14JSliderSample();
frame.setVisible(true);
}
public Ch14JSliderSample( )
{
Container contentPane;
JPanel sliderPanel;
//set the frame properties
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setTitle("Program Ch14JListSample");
setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
contentPane = getContentPane();
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(new BorderLayout());
//create and place a JList
sliderPanel = new JPanel(new FlowLayout());
sliderPanel.setBorder(BorderFactory.createTitledBorder("RGB Color Selection"));
redSlider = createSlider(MAX_COLOR);
greenSlider = createSlider(MAX_COLOR);
blueSlider = createSlider(MAX_COLOR);
sliderPanel.add(redSlider);
sliderPanel.add(greenSlider);
sliderPanel.add(blueSlider);
colorPanel = new JPanel( );
colorPanel.setBackground(Color.white);
colorPanel.setBorder(BorderFactory.createLoweredBevelBorder());
contentPane.add(colorPanel, BorderLayout.CENTER);
contentPane.add(sliderPanel, BorderLayout.WEST);
//register 'Exit upon closing' as a default close operation
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void stateChanged(ChangeEvent event){
int R, G, B;
R = redSlider.getValue();
G = greenSlider.getValue();
B = blueSlider.getValue();
colorPanel.setBackground(new Color(R, G, B));
}
private JSlider createSlider(int value)
{
JSlider slider = new JSlider();
slider.setOrientation(JSlider.VERTICAL);
slider.setPaintLabels(true);
slider.setPaintTicks(true);
slider.setMinimum(MIN_COLOR);
slider.setMaximum(MAX_COLOR);
slider.setValue(value);
slider.setMajorTickSpacing(50);
slider.setMinorTickSpacing(25);
slider.addChangeListener(this);
return slider;
}
}
OUTPUT: C:\Users\drraf>javac Ch14JSliderSample.java
C:\Users\drraf>java Ch14JSliderSample

Menus:
In this section we will describe how to display menus and process menu events
by using JMenu, JMenuItem, and JMenuBar from the javax.swing package.
For example We will create two menus, File and Edit, with the following menu
items:

If the menu item Quit is selected, then we terminate the program. When a menu
item other than Quit is selected, we print a message that identifies the selected
menu item, for example, Menu item 'New' is selected.
To create a MENU following steps are required:
1. Create a JMenuBar object and attach it to a frame.
2. Create a JMenu object.
3. Create JMenuItem objects and add them to the JMenu object.
4. Attach the JMenu object to the JMenuBar object.
We will create two JMenu objects: fileMenu and editMenu. We create a file
Menu object as
fileMenu = new JMenu("File");
The argument to the JMenu constructor is the name of the menu.
After the menu is created, we add a menu item to it.
A menu item is the event source of menu selection, so we need to register an
action listener to every menu item we add to the menu.
For example:
item = new JMenuItem("New");//New
item.addActionListener(this);
fileMenu.add(item);

Menu items are placed from the top in the order they are added to the menu. We can also
include a horizontal line as a separator between menu items by calling the menu’s
addSeparator method.
fileMenu.addSeparator();
After the menus and their menu items are created, we attach them to a menu bar. In the
constructor, we create a JMenuBar object, attach it to the frame by calling the frame’s
setMenuBar method, and add these two JMenu objects to the menu bar.
JMenuBar menuBar = new JMenuBar();
setMenuBar(menuBar); //attach it to the frame
menuBar.add(fileMenu);
menuBar.add(editMenu);
To display which menu item was selected, we use a JLabel object response. We add response
to the frame by
response = new JLabel("Hello, this is your menu tester.");
response.setSize(250, 50);
contentPane.add(response);
When a menu item is selected, the registered action listener’s actionPerformed method is
called. The actionPerformed method of the Ch14JMenuFrame is defined as follows: If an
event source is a menu item, the getActionCommand method of ActionEvent returns the
menu’s text. We test if the returned text is Quit. If it is, we terminate the program.
Otherwise, we set the text of response to indicate which menu item was selected. Here’s the
method body of actionPerformed:
/*Chapter 14 Sample Program: Displays a frame with two menus
File: Ch14JMenuFrame.java*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Ch14JMenuFrame extends JFrame implements ActionListener {
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 250;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
private JLabel response;
private JMenu fileMenu;
private JMenu editMenu;
public static void main(String[] args){
Ch14JMenuFrame frame = new Ch14JMenuFrame();
frame.setVisible(true);
}
public Ch14JMenuFrame(){
Container contentPane;
//set the frame properties
setTitle("Ch14JMenuFrame");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setLocation (FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
contentPane = getContentPane( );
contentPane.setLayout(new FlowLayout());
//create two menus and their menu items
createFileMenu();
createEditMenu();
//and add them to the menu bar
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
menuBar.add(fileMenu);
menuBar.add(editMenu);
//create and position response label
response = new JLabel("Hello, this is your menu tester.");
response.setSize(250, 50);
contentPane.add(response);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent event){
String menuName;
menuName = event.getActionCommand();
if (menuName.equals("Quit")) {
System.exit(0);
} else {
response.setText("Menu Item '" + menuName + "' is selected.");
}
}
private void createFileMenu( )
{
JMenuItem item;
fileMenu = new JMenu("File");
item = new JMenuItem("New"); //New
item.addActionListener(this);
fileMenu.add(item);
item = new JMenuItem("Open"); //Open...
item.addActionListener(this);
fileMenu.add(item);
item = new JMenuItem("Save"); //Save
item.addActionListener(this);
fileMenu.add(item);
item = new JMenuItem("Save As..."); //Save As...
item.addActionListener(this);
fileMenu.add(item);
fileMenu.addSeparator(); //add a horizontal separator line
item = new JMenuItem("Quit"); //Quit
item.addActionListener(this);
fileMenu.add(item);
}
private void createEditMenu()
{
JMenuItem item;
editMenu = new JMenu("Edit");
item = new JMenuItem("Cut"); //cut
item.addActionListener(this);
editMenu.add(item);
item = new JMenuItem("Copy"); //copy
item.addActionListener(this);
editMenu.add(item);
item = new JMenuItem("Paste"); //paste
item.addActionListener(this);
editMenu.add(item);
}
}
OUTPUT:
C:\Users\drraf>javac Ch14JMenuFrame.java
C:\Users\drraf>java Ch14JMenuFrame
Handling Mouse Events:Mouse events include user interactions as moving the mouse,
dragging the mouse (i.e., moving the mouse while the mouse button is being pressed) and
clicking the mouse buttons. To implement mouse events use MouseListener interface. This
interface has five abstract methods: mouseClicked, mouseEntered, mouseExited, mouse
Pressed, and mouseReleased. The argument to all five methods is an instance of
MouseEvent. The MouseMotionListener interface is used to track the mouse dragging. It
includes two abstract methods: mouseDragged and mouseMoved. The argument to both
methods is an instance of MouseEvent.
The class declaration for to implement Mouse Events:
class Ch14TrackMouseFrame extends Frame implements MouseListener {
...
}
In the constructor set the frame properties and register this frame as a mouse event listener
of itself. The constructor is defined as
public Ch14TrackMouseFrame {
//set the frame properties
...
//register itself as its mouse event listener
addMouseListener(this);
}
When the left mouse button is clicked, the mouseClicked method of its mouse event listener
is called. By this method, we can find out the x and y coordinates of the mouse click point
and print out these values in output.
To find the x and y co-ordinate values, we use the getX and getY methods of MouseEvent.
public void mouseClicked( MouseEvent event ){
int x, y;
x = event.getX(); //return the x and y coordinates
y = event.getY(); //of a mouse click point
System.out.println("[" + x + "," + y + "]");
}
This method is called every time the left mouse button is clicked(The mouse button is
pressed down and released). For this we call mousePressed and mouseReleased methods.
public void mousePressed(MouseEvent event){
System.out.println("Down");
}
public void mouseReleased(MouseEvent event){
System.out.println("Up");
}
/*Chapter 14 Sample Program: Tracks the mouse movement
File: Ch14TrackMouseFrame.java */
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
class Ch14TrackMouseFrame extends JFrame implements MouseListener {
private static final int FRAME_WIDTH = 450;
private static final int FRAME_HEIGHT = 300;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
private static final int DOUBLE_CLICK = 2;
public static void main(String[] args){
Ch14TrackMouseFrame frame = new Ch14TrackMouseFrame();
frame.setVisible(true);
}
public Ch14TrackMouseFrame() {
//set frame properties
setTitle("TrackMouseFrame");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setLocation (FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//register self as a mouse event listener
addMouseListener(this);
}
public void mouseClicked(MouseEvent event){
if (event.getClickCount() == DOUBLE_CLICK){
System.exit(0);
} else {
int x, y;
x = event.getX(); //get the x and y coordinates of
y = event.getY(); //the mouse click point
System.out.println("[" + x + "," + y + "]");
}
}
public void mouseEntered(MouseEvent event){}
public void mouseExited(MouseEvent event){}
public void mousePressed (MouseEvent event){
System.out.println("Down");
}
public void mouseReleased(MouseEvent event){
System.out.println("Up");
}
}

Output:
Implementation of Mouse Listener:
// Mouse Listener

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

class Ex extends JFrame implements MouseListener {


Container cp;

Ex() {
cp = getContentPane();

cp.addMouseListener(this);

setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Mouse Listener");
setSize(600, 600);
setVisible(true);
}
public void mouseEntered(MouseEvent me) {
cp.setBackground(Color.cyan);
}

public void mouseExited(MouseEvent me) {


cp.setBackground(Color.white);
}

public void mousePressed(MouseEvent me) {


cp.setBackground(Color.red);
}

public void mouseReleased(MouseEvent me) {


cp.setBackground(Color.yellow);
}

public void mouseClicked(MouseEvent me) {


cp.setBackground(Color.green);
}
public static void main (String[] args) {
new Ex();
}
}
Implementation of Mouse Listener:
// Mouse Motion Listener
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class Ex extends JFrame implements MouseMotionListener {


Container cp;

Ex() {
cp = getContentPane();

cp.addMouseMotionListener(this);

setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Mouse Listener");
setSize(600, 600);
setVisible(true);
}
public void mouseMoved(MouseEvent me) {
cp.setBackground(Color.cyan);
System.out.println("x="+me.getX()+", y="+me.getY());
}

public void mouseDragged(MouseEvent me) {


cp.setBackground(Color.blue);
}

public static void main (String[] args) {


new Ex();
}
}

You might also like