0% found this document useful (0 votes)
88 views

6 Graphical User Interface

This document discusses graphical user interfaces (GUIs) in Java programming. It specifically covers: 1. Dialog boxes in Java, which are windows that remain on screen briefly to perform a specific task, unlike standard windows. The JOptionPane class allows creating dialog boxes for input and output. 2. The Java Swing library provides GUI components like buttons and text boxes. Key classes include JFrame for windows, JPanel for organization, and JComponent as the base class. 3. An example program uses JOptionPane to prompt for radius input and display the calculated area and circumference of a circle, demonstrating basic GUI functionality in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
88 views

6 Graphical User Interface

This document discusses graphical user interfaces (GUIs) in Java programming. It specifically covers: 1. Dialog boxes in Java, which are windows that remain on screen briefly to perform a specific task, unlike standard windows. The JOptionPane class allows creating dialog boxes for input and output. 2. The Java Swing library provides GUI components like buttons and text boxes. Key classes include JFrame for windows, JPanel for organization, and JComponent as the base class. 3. An example program uses JOptionPane to prompt for radius input and display the calculated area and circumference of a circle, demonstrating basic GUI functionality in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

JAVA PROGRAMMING FUNDAMENTALS

GRAPHICAL USER INTERFACE (DIALOG BOXES AND JAVA SWING LIBRARY)

DIALOG BOX AND JOptionPane CLASS

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.

The syntax to use the method showInputDialog is:

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.

Consider the following statement (suppose that name is a String variable):

name = JOptionPane.showInputDialog("Enter your name and press OK");

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.

The syntax to use the method showMessageDialog is:

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:

JOptionPane.showMessageDialog(null, "Hello World!",


"Greetings",JOptionPane.INFORMATION_MESSAGE);

is shown in Figure 3-9.

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.

Figure 3-10 shows the output of the following statement:

JOptionPane.showMessageDialog(null, "Amount Due = $" + 500.45, "Invoice",


JOptionPane.PLAIN_MESSAGE);
In the message dialog box in Figure 3-10, no icon appears to the left of the
messageStringExpression. This is because the messageType is JOptionPane.PLAIN_MESSAGE.

Consider the following statements:

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!";

Figure 3-11 shows the output of the statement:

JOptionPane.showMessageDialog(null, str, "Summing


Numbers",JOptionPane.ERROR_MESSAGE);

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

radiusString = JOptionPane.showInputDialog("Enter the radius: "); //Line 6


radius = Double.parseDouble(radiusString); //Line 7
area = Math.PI * radius * radius; //Line 8
circumference = 2 * Math.PI * radius; //Line 9

outputStr = "Radius: " + radius + "\n" + "Area: " + area + " square units\n"
+ "Circumference: " + circumference + " units"; //Line 10

JOptionPane.showMessageDialog(null, outputStr, "Circle",


JOptionPane.INFORMATION_MESSAGE); //Line 11
System.exit(0); //Line 12
}
}

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 TOOLKIT/LIBRARY

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.

Java Swing class Hierarchy Diagram

Java Swing Class


Hierarchy Diagram

All components in Java Swing are JComponent that can be added to container classes.

WHAT IS A CONTAINER CLASS?

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.

What is GUI in Java?

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.

Java GUI Example

Now in this Swing Java Tutorial, let's understand GUI with Java Swing examples.

Example: To learn Java GUI programming in this Java GUI tutorial


Step 1) 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 button = new JButton("Press");
frame.getContentPane().add(button); // Adds Button to content pane
of frame
frame.setVisible(true);
}

Step 2) Save, Compile, and Run the code.


Step 3) Output: You will get a big button that occupies the entire frame(JFrame)

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);
}
}

Step 5) Save, Compile, and Run the program.


Step 6) Output: button1 and button2 overlapped resulting to the output shown in the image below. To
be able to arrange the components in a frame, knowledge in Java Layout Manager should be applied.
Java Layout Manager will be discussed on the next section.
JAVA LAYOUT MANAGER

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.

Step 7) How about creating a chat frame like below?


//Usually you will require both swing and awt packages
import javax.swing.*;
import java.awt.*;

public class gui2 {


public static void main(String[] args){
//Creating the Frame
JFrame frame = new JFrame("Chat Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);

//Creating the MenuBar and adding components


JMenuBar mb = new JMenuBar();
JMenu m1 = new JMenu("FILE");
JMenu m2 = new JMenu("Help");
mb.add(m1);
mb.add(m2);
JMenuItem m11 = new JMenuItem("Open");
JMenuItem m22 = new JMenuItem("Save as");
m1.add(m11);
m1.add(m22);

//Creating the panel at bottom and adding components


JPanel panel = new JPanel(); // the panel is not visible in output
JLabel label = new JLabel("Enter Text");
JTextField tf = new JTextField(10); // accepts upto 10 characters
JButton send = new JButton("Send");
JButton reset = new JButton("Reset");
panel.add(label); // Components Added using Flow Layout
panel.add(tf);
panel.add(send);
panel.add(reset);

// Text Area at the Center


JTextArea ta = new JTextArea();

//Adding Components to the frame.


frame.getContentPane().add(BorderLayout.SOUTH, panel);
frame.getContentPane().add(BorderLayout.NORTH, mb);
frame.getContentPane().add(BorderLayout.CENTER, ta);
frame.setVisible(true);
}
}

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.

Figure 6-2 GUI to find the area and perimeter of a rectangle


In Java terminology, such a dialog box is called a graphical user interface (GUI), or simply a user
interface. In this GUI, the user enters the length and width in the top two white boxes. When the user
clicks the Calculate button, the program displays the area and the perimeter in their respective
locations. When the user clicks the Exit button, the program terminates.

In this interface, the user can:


 See the entire input and output simultaneously
 Input values for length and width, in any order of preference
 Input values that can be corrected after entering them and before clicking the Calculate button
 Enter another set of input values and click the Calculate button to obtain the area and
perimeter of another rectangle

The interface shown in Figure 6-2 contains various Java GUI components that are labeled in Figure
6-3.

Figure 6-3 Java GUI components

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 class jframe extends JFrame{


private JLabel lengthL, widthL, areaL, perimeterL;
private JTextField lengthTF, widthTF, areaTF, perimeterTF;
private JButton calculateB, exitB;

private CalculateButtonHandler cbHandler;


private ExitButtonHandler ebHandler;

private static final int WIDTH =400;


private static final int HEIGHT =300;

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);

lengthTF = new JTextField(10);


widthTF = new JTextField(10);
areaTF = new JTextField(10);
perimeterTF = new JTextField(10);

calculateB = new JButton("Calculate");


cbHandler = new CalculateButtonHandler();
calculateB.addActionListener (cbHandler);

exitB = new JButton("Exit");


ebHandler = new ExitButtonHandler();
exitB.addActionListener (ebHandler);

setTitle("Area and Perimeter of a Rectangle");

Container pane = getContentPane();

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);

private class CalculateButtonHandler implements ActionListener


{
public void actionPerformed(ActionEvent e)
{
double width,length,area,perimeter;

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);
}
}

public static void main (String[] args)


{
jframe rectObject = new jframe();
}
}

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

You might also like