Introduction To: JAVA GUI Programming
Introduction To: JAVA GUI Programming
Introduction to
JAVA GUI Programming
Budditha Hettige
Department of Statistics and Computer Science
Introduction
Some common GUI components are:
buttons, labels, text fields, check boxes, radio buttons,
combo boxes, and sliders.
Budditha Hettige
GUI Programming
GUI programs are event-driven
Basic types of GUI Programs
Stand-alone applications
Applets
Budditha Hettige
Budditha Hettige
JFC/Swing
Java Foundation Classes (or Swing)
Replacement for AWT (although does share some classes)
Also provide basis for developing new GUI features (which
are being continually added)
100% Java
Swing components (more, and more sophisticated)
Pluggable Look and Feel Support
Accessibility API
Better graphics support (Java 2D)
Drag and Drop
Budditha Hettige
JFC/Swing cont
Disadvantages
Can be slow (resource hungry)
Large complex API (big learning curve)
Many features best suited for GUI builders, IDEs
Budditha Hettige
Budditha Hettige
User interface
A GUI is built in layers.
Bottom most layer is the window (Container)
Contains all other components
Can provide basic features like maximise/minimise buttons,
title bar, menu bar, etc
Budditha Hettige
10
GUI Application
Jframe
Budditha Hettige
11
JButton
JButton
JLabel
Budditha Hettige
JPanel
JTextField
12
JFrame
The basic Swing window. Offers basic window controls,
resizable
JDialog
For building dialog boxes, e.g. File open/save
JApplet
For building applets, embedded into a web page
Budditha Hettige
13
Budditha Hettige
14
SWING containers
Panel
Scroll Pane
Tool Bar etc
Budditha Hettige
15
16
Example
public class NewJFrame extends javax.swing.JFrame {
public NewJFrame() {
initComponents();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
}
Budditha Hettige
17
Example
close operation
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Test Window");
setAlwaysOnTop(true);
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 189, Short.MAX_VALUE)
);
}
Budditha Hettige
18
Budditha Hettige
19
Adding Components
Very common to extend the Swing components,
particularly JFrame
Create your own specialised versions
May include a fixed set of components
Provide extra methods for working with those components,
etc.
Encapsulates how the GUI is constructed
Budditha Hettige
20
Layout Managers
Responsible for layout out (arranging)
components in a Container
Several different types with different uses
None of them provide for precise x-y
alignment, unlike VB forms
Budditha Hettige
21
Border Layout
This is the default layout for JFrame
Divides the content pane into 5 areas (north, south,
east, west, center)
Areas are expanded/contracted as needed, along with
their contents.
Therefore ignores preferred size of the components.
22
Border Layout
X
NORTH
WEST
CENTER
EAST
SOUTH
Budditha Hettige
23
Grid Layout
Divides the container into a rectangular grid
Configurable number rows/columns
Budditha Hettige
24
Card Layout
Arranges components like a deck of cards
Only one card visible at a time
Budditha Hettige
25
Menus
A Jframe can have only a single menu bar
Instance of the Jmenu object
Example
Budditha Hettige
26
Controls
Budditha Hettige
27
// Set fonts
28
Text field
Use to input/output a text
Sample Codes
private javax.swing.JTextField jTextField1;
jTextField1 = new javax.swing.JTextField();
jTextField1.setText("jTextField1");
layout.setVerticalGroup( .....
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE,
190, javax.swing.GroupLayout.PREFERRED_SIZE)
layout.setHorizontalGroup( .....
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
Budditha Hettige
29
Budditha Hettige
30
Buttons
Budditha Hettige
31
Combo box
Select a item from a list
Codes
private javax.swing.JComboBox jComboBox1;
Budditha Hettige
32
Data Access
Get selected item from the combo box
String ss;
ss = (String)jComboBox1.getSelectedItem();
Type casting
Budditha Hettige
33
Event Handling
Budditha Hettige
34
Handling Basics
Swing Events Examples
Actions
Mouse Events
Window Events
Budditha Hettige
35
Budditha Hettige
36
Action Events
Very tedious implementation if all activities were dealt
with as individual clicks
Swing provides higher level action event
Meaning of event depends on component
E.g. button click, menu selection, etc
Basic classes:
ActionEvent identifies action, key modifiers, etc
ActionListener single actionPerformed method
addActionListener, removeActionListener
methods on Component
Budditha Hettige
37
Code
Use
Budditha Hettige
38
Budditha Hettige
39
Mouse Events
Natural for Swing to expose mouse-related events
Its how the user interacts with the GUI
Budditha Hettige
40
Mouse Events
Budditha Hettige
41
Mouse Events
So, capturing basic mouse events involves:
Creating an implementation of MouseListener
Calling addMouseListener on one or more
Components to register it
Budditha Hettige
42
Window Events
Swing allows the capturing of window related events
Activate, deactivate, minimise, open, close etc
Budditha Hettige
43
Item events
Selecting/deselecting items in lists, checkboxes, etc
Key Events
Raw keyboard input
Tree Events
Opening/closing nodes in a tree component
44
Mouse events
Use
Mouse Event
Mouse Listener
java.awt.event.MouseEvent
java.awt.event.MouseAdapter
Code
jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
jButton2MouseEntered(evt);
}
});
private void jButton2MouseEntered(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
Budditha Hettige
45
Key events
Use
java.awt.event.KeyEvent
Code
jButton2.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jButton2KeyPressed(evt);
}
});
private void jButton2KeyPressed(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
}
Budditha Hettige
46
Dialog Boxes
A dialog box is a small graphical window that
displays a message to the user or requests
input.
A variety of dialog boxes can be displayed
using the JOptionPane class.
Message Dialog - a dialog box that displays a
message.
Input Dialog - a dialog box that prompts the user
for input.
Confirm Dialog This is a dialog box that asks the
user a Yes/No question.
Budditha Hettige
47
Dialog Boxes
The JOptionPane class provides static
methods to display each type of dialog box.
Budditha Hettige
48
Message Dialogs
JOptionPane.showMessageDialog method
is used to display a message dialog.
There are several overloaded versions of
this method.
showMessageDialog(Component parent,
Object message)
showMessageDialog(Component parent,
Object message,
String title,
int messageType)
Budditha Hettige
49
Message Dialogs
JOptionPane.showMessageDialog(null, "Hello World");
Budditha Hettige
50
Message Dialogs
By default the dialog box has:
the string Message displayed in its title bar, and
an information icon (showing the letter i) is displayed.
JOptionPane.showMessageDialog(null,
"Invalid Data",
"My Message Box",
JOptionPane.ERROR_MESSAGE);
Budditha Hettige
51
Message Dialogs
These constants can be use to control the icon
that is displayed.
JOptionPane.ERROR_MESSAGE
JOptionPane.INFORMATION_MESSAGE
JOptionPane.WARNING_MESSAGE
JOptionPane.QUESTION_MESSAGE
JOptionPane.PLAIN_MESSAGE
Budditha Hettige
52
Message Dialogs
Budditha Hettige
53
Input Dialogs
An input dialog is a quick and simple way to
ask the user to enter data.
The dialog displays a text field, an Ok button
and a Cancel button.
If Ok is pressed, the dialog returns the users
input.
If Cancel is pressed, the dialog returns null.
Budditha Hettige
54
Input Dialogs
The JOptionPane has several
overloaded versions of the static
showInputDialog method.
Here are two of them:
showInputDialog(Object message)
showInputDialog(Component parent,
Object message,
String title,
int messageType)
Budditha Hettige
55
Input Dialogs
String name;
name = JOptionPane.showInputDialog("Enter your
name.");
Budditha Hettige
56
Input Dialogs
By default the input dialog box:
has the string Input in its title bar, and
displays a question icon.
String value;
value = JOptionPane.showInputDialog(null,
"Enter the value again.",
"Enter Carefully!",
JOptionPane.WARNING_MESSAGE);
Budditha Hettige
57
Confirm Dialog
A confirm dialog box typically asks the user a yes or no
question.
By default Yes, No, and Cancel buttons are displayed.
The showConfirmDialog method is used to
display a confirm dialog box.
There are several overloaded versions of this method.
int showConfirmDialog(Component parent,
Object message)
int showConfirmDialog(Component parent,
Object message,
String title,
int optionType)
Budditha Hettige
58
Confirm Dialog
int value;
value = JOptionPane.showConfirmDialog(null,
"Are you sure?");
Budditha Hettige
59
Confirm Dialog
The showConfirmDialog method returns
an integer that represents the button clicked
by the user.
The button that was clicked is determined by
comparing the methods return value to one of
the following constants:
JOptionPane.YES_OPTION
JOptionPane.NO_OPTION
JOptionPane.CANCEL_OPTION
Budditha Hettige
60
Confirm Dialog
int value;
value = JOptionPane.showConfirmDialog(null,
"Are you sure?");
if (value == JOptionPane.YES_OPTION){
//If the user clicked Yes, this code is executed.
}
else if (value == JOptionPane.NO_OPTION){
//If the user clicked no, this code is executed.
}
else if (value == JOptionPane.CANCEL_OPTION){
//If the user clicked Cancel, this code is executed.
}
Budditha Hettige
61
Confirm Dialog
int value;
value = JOptionPane.showConfirmDialog(null,
"Are you sure?",
"Please Confirm", JOptionPane.YES_NO_OPTION);
Example:
TestAverageDialog.java
Budditha Hettige
62
Example - Calculator
Create a calculator application to calculate the
numbers and print the result
Supported Operators
+ - / * ^ and squrt
Supported action C , < (Back)
Display total with number of numbers
used for calculation
Budditha Hettige
63