Top Banner
CSC 308 2.0 System Development with Java Budditha Hettige Department of Statistics and Computer Science Introduction to JAVA GUI Programming
63
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Gui

CSC 308 2.0

System Development with Java

Budditha Hettige

Department of Statistics and Computer Science

Introduction to JAVA GUI Programming

Page 2: Gui

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

Page 3: Gui

Introduction

• Some common GUI components are:

– buttons, labels, text fields, check boxes, radio buttons, combo boxes, and sliders.

3 Budditha Hettige

Page 4: Gui

GUI Programming

• GUI programs are event-driven

• Basic types of GUI Programs

– Stand-alone applications

– Applets

• Stranded GUI library

– AWT

– SWINIG

4 Budditha Hettige

Page 5: Gui

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

Page 6: Gui

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

Page 7: Gui

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

Page 8: Gui

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

Page 9: Gui

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

Page 10: Gui

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

Page 11: Gui

GUI Application

Jframe

11 Budditha Hettige

Page 12: Gui

The containment hierarchy

JFrame

JButton JButton JPanel

JLabel JTextField

12 Budditha Hettige

Page 13: Gui

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

Page 14: Gui

New containers (Netbeans)

14 Budditha Hettige

Page 15: Gui

SWING containers

• Panel

• Scroll Pane

• Tool Bar etc

15 Budditha Hettige

Page 16: Gui

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

Page 17: Gui

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

Page 18: Gui

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

Page 19: Gui

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

Page 20: Gui

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

Page 21: Gui

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

Page 22: Gui

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

Page 23: Gui

Border Layout

X

NORTH

SOUTH

CENTER WEST EAST

23 Budditha Hettige

Page 24: Gui

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

Page 25: Gui

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

Page 26: Gui

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

Page 27: Gui

Controls

27 Budditha Hettige

Page 28: Gui

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

Page 29: Gui

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

Page 30: Gui

Text field data access

• Set text

jTextField1.setText(“text");

• Get text form the text field

String data;

data = jTextField1.getText();

30 Budditha Hettige

Page 31: Gui

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

Page 32: Gui

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

Page 33: Gui

Data Access

• Get selected item from the combo box

String ss;

ss = (String)jComboBox1.getSelectedItem();

Type casting

33 Budditha Hettige

Page 34: Gui

Event Handling

34 Budditha Hettige

Page 35: Gui

Handling Basics

• Swing Events Examples

– Actions

– Mouse Events

– Window Events

35 Budditha Hettige

Page 36: Gui

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

Page 37: Gui

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

Page 38: Gui

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

Page 39: Gui

Event Handling Conventions

39 Budditha Hettige

Page 40: Gui

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

Page 41: Gui

Mouse Events

41 Budditha Hettige

Page 42: Gui

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

Page 43: Gui

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

Page 44: Gui

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

Page 45: Gui

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

Page 46: Gui

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

Page 47: Gui

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

Page 48: Gui

Dialog Boxes

The JOptionPane class provides static

methods to display each type of dialog box.

Budditha Hettige 48

Page 49: Gui

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

Page 50: Gui

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

Page 51: Gui

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

Page 52: Gui

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

Page 53: Gui

Message Dialogs

Budditha Hettige 53

Page 54: Gui

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

Page 55: Gui

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

Page 56: Gui

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

Page 57: Gui

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

Page 58: Gui

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

Page 59: Gui

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

Page 60: Gui

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

Page 61: Gui

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

Page 62: Gui

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

Page 63: Gui

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