ch1 - GUI & Event-Driven Programming
ch1 - GUI & Event-Driven Programming
ch1 - GUI & Event-Driven Programming
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) {
}
}
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.
/*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.
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:
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:
OUTPUT:
C:>javac Ch14JFrameSubclass2.java
C:>java Ch14JFrameSubclass2
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
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
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
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:
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;
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.*;
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);
}
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());
}