6 Graphical User Interface
6 Graphical User Interface
A dialog box often referred to simply as a dialog – is a specialized type of window. The primary
difference between a dialog box and a standard window is that a dialog box is more constrained in
terms of what it can do. While a standard window usually remains on the user’s screen for quite a
while and perform many, a dialog box remains on the screen only long enough to perform one
specific task. While standard window is highly customizable, a dialog box typically is locked into one
particular format.
Another way to gather input and output results is to use a graphical user interface (GUI). Java
provides the class JOptionPane, which allows the programmer to use GUI components for I/O. This
lesson describes how to use these facilities to make I/O more efficient and the program more
attractive.
The class JOptionPane is contained in the package javax.swing. The two methods of this class that
we use are: showInputDialog and showMessageDialog. The method showInputDialog allows the
user to input a string from the keyboard; the method showMessageDialog allows the programmer to
display the results.
str = JOptionPane.showInputDialog(stringExpression);
where str is a String variable and stringExpression is an expression evaluating to a string. When
this statement executes, a dialog box containing stringExpression appears on the screen prompting
the user to enter the data. (The stringExpression usually informs the user what to enter.) The data
entered is returned as a string and assigned to the variable str.
When this statement executes, the dialog box shown in Figure 3-7 appears on the screen.
(The arrow and the words Text Field are not part of the dialog box.)
The user enters the name in the white area, called a text field, as shown in Figure 3-8.
After you enter a name and click the OK button (or press the Enter key), the dialog box disappears
and the entered name is assigned to the variable name. In this case, the string "Ashley Mann" is
assigned to name.
Now that you know how to use an input dialog box, let’s turn to the method showMessageDialog for
output.
JOptionPane.showMessageDialog(parentComponent, messageStringExpression,
boxTitleString, messageType);
The method showMessageDialog has four parameters, which are described in Table 3-3.
Table 3-4 describes the options of the class JOptionPane that can be used with the parameter
messageType. The option name is shown in bold. Examples 3-9 through 3-11 illustrate these options.
The output of the statement:
Notice the INFORMATION_MESSAGE icon to the left of Hello World! and the word Greetings in the
title bar. After you click the OK button, the dialog box disappears.
String str;
int num1 = 45;
int num2 = 56;
int sum;
str = "The two numbers are: " + num1 + " and " + num2 + "\n";
sum = num1 + num2;
str = str + "The sum of the numbers is: " + sum + "\n";
str = str + "That is all for now!";
The class JOptionPane is contained in the package javax.swing. Therefore, to use this class in a
program, the program must import it from the package javax.swing.The following statements illustrate
how to import the class JOptionPane (you can use either format):
import javax.swing.JOptionPane;
or:
import javax.swing.*;
System.exit
In order to use the input/output dialog boxes and properly terminate program execution, the program
must include the following statement:
System.exit(0);
Note that this statement is needed only for programs that have GUI components such as input/output
dialog boxes.
Example 3-12 shows a program that calculates the area and circumference of a circle and uses
input/output dialog boxes.
The following program prompts the user to enter the radius of a circle. The program then outputs the
circle’s radius, area, and circumference. The class Math defines the named constant PI (p), which is
PI ¼ 3.141592653589793. We will use this value to find the area and circumference. (Note that to
use this value, we use the expression Math.PI.)
//Program to determine the area and circumference of a circle
import javax.swing.JOptionPane;
public class AreaAndCircumferenceProgram
{
public static void main(String[ ] args)
{
double radius; //Line 1
double area; //Line 2
double circumference; //Line 3
String radiusString; //Line 4
String outputStr; //Line 5
outputStr = "Radius: " + radius + "\n" + "Area: " + area + " square units\n"
+ "Circumference: " + circumference + " units"; //Line 10
Sample Run: (Figure 3-12 shows a sample run of this program. The input screen is shown first, then
the output screen.)
The preceding program works as follows. The statements in Lines 1 through 5 declare the
appropriate variables to manipulate the data. The statement in Line 6 displays the input dialog box
with the message Enter the radius: (in Figure 3-12(a), the entered value is 12.50).
The string containing the input data is assigned to the String variable radiusString. The statement in
Line 7 converts the string containing the radius into a value of the type double and stores it in the
variable radius.
The statements in Lines 8 and 9 calculate the area and circumference of the circle and store them in
the variables area and circumference, respectively. The statement in Line 10 constructs the string
containing the radius, area, and circumference of the circle. The string is assigned to the variable
outputStr. The statement in Line 11 uses the message dialog box to display the circle’s radius, area,
and circumference, as shown in Figure 3-12(b). The statement in Line 12 terminates the program
after the user clicks the OK button in the dialog box.
Java Swing is a Graphical User Interface (GUI) toolkit that includes the GUI components. Swing
provides a rich set of widgets and packages to make sophisticated GUI components for Java
applications. Swing is a part of Java Foundation Classes(JFC), which is an API for Java programs
that provide GUI.
The Java Swing library is built on top of the Java Abstract Widget Toolkit (AWT), an older, platform
dependent GUI toolkit. You can use the Java GUI programming components like button, textbox, etc.
from the library and do not have to create the components from scratch.
All components in Java Swing are JComponent that can be added to container classes.
Container classes are classes that can have other components on it. So for creating a Java GUI, we
need at least one container object. There are three (3) types of Java Swing containers.
1. Panel: It is a pure container and is not a window in itself. The sole purpose of a Panel is to
organize the components on to a window.
2. Frame: It is a fully functioning window with its title and icons.
3. Dialog: It can be thought of like a pop-up window that pops out when a message has to be
displayed. It is not a fully functioning window like the Frame.
GUI (Graphical User Interface) in Java is an easy-to-use visual experience builder for Java
applications. It is mainly made of graphical components like buttons, labels, windows, etc. through
which the user can interact with an application. GUI plays an important role to build easy interfaces
for Java applications.
Now in this Swing Java Tutorial, let's understand GUI with Java Swing examples.
import javax.swing.*;
public class gui {
public static void main(String[] args){
JFrame frame = new JFrame("My First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button = new JButton("Press");
frame.getContentPane().add(button); // Adds Button to content pane
of frame
frame.setVisible(true);
}
Step 4) How about adding two buttons? Copy the following code into an editor.
import javax.swing.*;
public class gui {
public static void main(String[] args){
JFrame frame = new JFrame("My First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
frame.getContentPane().add(button1);
frame.getContentPane().add(button2);
frame.setVisible(true);
}
}
The Layout manager is used to layout (or arrange) the GUI java components inside a container.
There are many layout managers, but the most frequently used are:
1. Java BorderLayout
A BorderLayout places components in up to five areas: top, bottom, left, right, and center. It is
the default layout manager for every Java JFrame
2. Java FlowLayout
FlowLayout is the default layout manager for every JPanel. It simply lays out components in a
single row one after the other.
3. Java GridBagLayout
It is the most sophisticated of all layouts. It aligns components by placing them within a grid of
cells, allowing components to span more than one cell.
On this section, we will then discuss how to use additional GUI components to create a different
graphical user interface to determine the area and perimeter of a rectangle.
The interface shown in Figure 6-2 contains various Java GUI components that are labeled in Figure
6-3.
As you can see in Figure 6-3, the white areas used to get the input and show the results are called
JTextFields. The labels for these text fields, such as Enter the length:, are called JLabels; the buttons
Calculate and Exit are each called a JButton. All these components are placed in a window, called
JFrame. Creating this type of user interface is not difficult. Java has done all the work; you merely
need to learn how to use the tools provided by Java to create such an interface. For example, to
create an interface like the one shown in Figures 6-2 and 6-3 that contains labels, text fields, buttons,
and windows, you need to learn how to write the statements that create these components. The next
sections describe how to create the following GUI components:
Windows
Labels
Text fields
Buttons
In Figure 6-2, when you click the Calculate button, the program displays the area and perimeter of the
rectangle you have specified. This means that clicking the Calculate button causes the program to
execute the code to calculate the area and perimeter and then display the results. When the
Calculate button is clicked, we say that an event has occurred. The Java system is very prompt in
listening for the events generated by a program and then reacting to those events. This chapter will
describe how to write the code that needs to be executed when a particular event occurs, such as
when a button is clicked.
SOURCE CODE:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public jframe(){
lengthL = new JLabel ("Enter the length: ", SwingConstants.RIGHT);
widthL = new JLabel ("Enter the width: ", SwingConstants.RIGHT);
areaL = new JLabel ("Area: ", SwingConstants.RIGHT);
perimeterL = new JLabel ("Perimeter: ", SwingConstants.RIGHT);
pane.setLayout(new GridLayout(5,2));
pane.add(lengthL);
pane.add(lengthTF);
pane.add(widthL);
pane.add(widthTF);
pane.add(areaL);
pane.add(areaTF);
pane.add(perimeterL);
pane.add(perimeterTF);
pane.add(calculateB);
pane.add(exitB);
setSize(WIDTH,HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
length= Double.parseDouble(lengthTF.getText());
width= Double.parseDouble(widthTF.getText());
area =length * width;
perimeter = 2* (length + width);
areaTF.setText(""+area);
perimeterTF.setText(""+perimeter);
}
}
private class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
OUTPUT:
Source:
https://www.guru99.com/java-swing-gui.html#:~:text=GUI%20(Graphical%20User%20Interface)
%20in,easy%20interfaces%20for%20Java%20applications
Dean, Jean and Dean, Raymond. Introduction to Programming With Java: A Problem Solving
Approach: Second Edition. (2014) McGraw-Hill Companies, Inc.
Malik, D.S. Java Programming: From Problem Analysis to Program Design: Fifth Edition. (2012)
Cengage Learning