Post on 15-Jan-2016
description
CSC 308 2.0
System Development with Java
Budditha Hettige
Department of Statistics and Computer Science
Introduction to JAVA GUI Programming
Graphical User Interface
• Many Java application use a graphical user interface or GUI
• A GUI is a graphical window or windows that provide interaction with the user.
• GUI‟s accept input from:
– the keyboard
– a mouse.
• A window in a GUI consists of components that:
– present data to the user
– allow interaction with the application.
2 Budditha Hettige
Introduction
• Some common GUI components are:
– buttons, labels, text fields, check boxes, radio buttons, combo boxes, and sliders.
3 Budditha Hettige
GUI Programming
• GUI programs are event-driven
• Basic types of GUI Programs
– Stand-alone applications
– Applets
• Stranded GUI library
– AWT
– SWINIG
4 Budditha Hettige
Abstract Windowing Toolkit(AWT)
• IS a Original Java GUI API
• Very limited in capability
– Few components
– API not well structured, particularly event
handling for user actions
– Not entirely portable (used native widgets)
5 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)
• What does Swing include?
– 100% Java
– Swing components (more, and more sophisticated)
– Pluggable Look and Feel Support
– Accessibility API
– Better graphics support (Java 2D)
– Drag and Drop
6 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
• Important to use Swing and not AWT
– Swing is the recommended way to build Java GUIs
7 Budditha Hettige
Design Stages of the GUI
1. Design the user interface
– Organising pre-built GUI components to build windows, dialogs
– E.g buttons, tables, menus, etc
2. Writing the application logic
– What does the application do?
3. Writing event-handling code to tie the GUI components to the application logic
8 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
• On top of this are layered (Component) – Components, e.g. buttons, text fields
– or intermediate containers, e.g. panels
• Arrangement of components in a contained is handled by a layout manager – Its job is to instruct components on how to arrange
themselves so the GUI is drawn correctly.
9 Budditha Hettige
The containment hierarchy
• This layered GUI can be viewed as a hierarchy
of components
– NOT an inheritance hierarchy,
– It just describes how components are nested one
within another
10 Budditha Hettige
GUI Application
Jframe
11 Budditha Hettige
The containment hierarchy
JFrame
JButton JButton JPanel
JLabel JTextField
12 Budditha Hettige
Swing Top level containers
• JWindow
– Basic no frills window, just a square on the screen
• 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
13 Budditha Hettige
New containers (Netbeans)
14 Budditha Hettige
SWING containers
• Panel
• Scroll Pane
• Tool Bar etc
15 Budditha Hettige
Working with JFrames
• Many different possibilities, but the basics
include:
– Setting window title
– Setting location on screen
– Setting size of window
– Restricting resizes
– Set close operation (exit the program), as by
default it does nothing.
16 Budditha Hettige
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);
}
});
}
}
17 Budditha Hettige
Example
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Test Window");
setAlwaysOnTop(true);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 251, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 189, Short.MAX_VALUE)
);
}
18
close operation
Set size of the window
Set title of the window
Budditha Hettige
Adding Components to a Frame
• A JFrame has several areas
– Window decorations
– (Optional) Menu bar
– Content pane
• Content pane is where components are added.
– Content pane is a Container object
– Obtain reference to the content pane, and then add another component to it
JFrame frame = new JFrame(“Example”);
JButton button = new JButton(“Click me!”);
frame.getContentPane().add( button );
19 Budditha Hettige
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
• Slightly different to Visual Basic where one tends to
just use the basic components
20 Budditha Hettige
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
21 Budditha Hettige
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.
• Center is the default if not specified.
• Adding two components to the same zone means they get added one on top of the other – Instead add the components to a JPanel, and then add that
instead.
22 Budditha Hettige
Border Layout
X
NORTH
SOUTH
CENTER WEST EAST
23 Budditha Hettige
Grid Layout
• Divides the container into a rectangular grid
– Configurable number rows/columns
• Each grid location is of equal size, one
component assigned to each.
• Automatically assigns components to next
available location
24 Budditha Hettige
Other layout managers
• Flow Layout (default for JPanel)
– Arranges components left-to-right
– Used to arrange buttons on a panel
• Card Layout
– Arranges components like a deck of cards
– Only one card visible at a time
• Box Layout, Grid Bag Layout
– Very sophisticated managers, used by GUI builders for very precise GUI designs.
– Not recommended for hand use!
25 Budditha Hettige
Menus
• A Jframe can have only a single menu bar
– Instance of the Jmenu object
• A menu bar can have several menus on it
– Instances of the Jmenu object
• A menu can have several items on it
– Instances of the JmenuItem object
• Example
26 Budditha Hettige
Controls
27 Budditha Hettige
Swing Controls - Label
• Use to display text
• Codes private javax.swing.JLabel jLabel1;
jLabel1 = new javax.swing.JLabel(); // create object
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12)); // Set fonts jLabel1.setText("jLabel1"); // Set lables
// place the control in to the pane
layout.setVerticalGroup( .....
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
layout.setHorizontalGroup( .....
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
28 Budditha Hettige
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))
29 Budditha Hettige
Text field data access
• Set text
jTextField1.setText(“text");
• Get text form the text field
String data;
data = jTextField1.getText();
30 Budditha Hettige
Buttons
• Place the button
• Rename the button
• Add action event
• Modify the function private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
31 Budditha Hettige
Combo box
• Select a item from a list
• Codes
private javax.swing.JComboBox jComboBox1;
jComboBox1 = new javax.swing.JComboBox();
jComboBox1.setModel(new
javax.swing.DefaultComboBoxModel(new String[]
{ "Item 1", "Item 2", "Item 3", "Item 4" }));
32 Budditha Hettige
Data Access
• Get selected item from the combo box
String ss;
ss = (String)jComboBox1.getSelectedItem();
Type casting
33 Budditha Hettige
Event Handling
34 Budditha Hettige
Handling Basics
• Swing Events Examples
– Actions
– Mouse Events
– Window Events
35 Budditha Hettige
Event Handling Conventions
• Event object typically extend java.awt.Event
– Some of the „newer‟ ones don‟t
• Events share some common attributes
– a timestamp, source object, etc
36 Budditha Hettige
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
37 Budditha Hettige
Code
Use
Action Listener java.awt.event.ActionListener
Action Event java.awt.event.ActionEvent
Code
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
38 Budditha Hettige
Event Handling Conventions
39 Budditha Hettige
Mouse Events
• Natural for Swing to expose mouse-related events
– It‟s how the user interacts with the GUI
• MouseListener interface describes the basic
events
• Each method accepts a MouseEvent object
parameter
• java.awt.Component has add/remove listener
methods
40 Budditha Hettige
Mouse Events
41 Budditha Hettige
Mouse Events
• So, capturing basic mouse events involves:
– Creating an implementation of MouseListener
– Calling addMouseListener on one or more
Components to register it
42 Budditha Hettige
Window Events
• Swing allows the capturing of window related events
– Activate, deactivate, minimise, open, close etc
• setDefaultCloseOperation is only useful if you don‟t want to do anything complex
• Basic classes/methods
– WindowEvent – identifies Window
– WindowListener – range of methods
– addWindowListener, removeWindowListener methods on JFrame, JWindow, JDialog
43 Budditha Hettige
Other Swing Events
• More Mouse events – Mouse motion, mouse wheels
• Item events – Selecting/deselecting items in lists, checkboxes, etc
• Key Events – Raw keyboard input
• Tree Events – Opening/closing nodes in a tree component
• Drag and drop
• …and many more. See javax.swing.event and java.awt.event packages.
44 Budditha Hettige
Mouse events
Use
Mouse Event java.awt.event.MouseEvent
Mouse Listener 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:
}
45 Budditha Hettige
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:
}
46 Budditha Hettige
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.
47 Budditha Hettige
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");
• The first argument can be a reference to a graphical
component.
– The dialog box is displayed inside that component.
– If null is passed as the first argument, which causes the dialog
box to be displayed in the center of the screen.
• The second argument is the message that is to be
displayed.
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);
• The third option is the title bar text.
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 user‟s
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.");
• The argument passed to the method is the message to display.
• If the user clicks on the OK button, name references the string entered by the user.
• If the user clicks on the Cancel button, name references null.
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?");
• By default the confirm dialog box displays: – “Select an Option” in its title bar,
– Yes, No, and Cancel buttons.
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 method‟s 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);
• One of the following constants can be used for the fourth parameter: – JOptionPane.YES_NO_OPTION
– JOptionPane.YES_NO_CANCEL_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
63 Budditha Hettige