13 gui development

47
OOSSE - Java Lecture 12 1 Jun 26, 2022 GUI Development OOSSE - Programming with Java Lecture 12

description

 

Transcript of 13 gui development

Page 1: 13 gui development

OOSSE - Java Lecture 12 1Apr 10, 2023

GUI Development

OOSSE - Programming with JavaLecture 12

Page 2: 13 gui development

OOSSE - Java Lecture 12 2Apr 10, 2023

Objectives

In this lecture, we will• Introduce the Abstract Window Toolkit • Introduce the Java Foundation Classes• Discuss containers and layout managers• Introduce events and event handling• Introduce menus • Introduce dialogs• Discuss mouse events

Page 3: 13 gui development

OOSSE - Java Lecture 12 3Apr 10, 2023

The Abstract Windowing Toolkit AWT

• The Abstract Windowing Toolkit provides a set of GUI components in the package java.awt

• The AWT supports the most common user interface idioms

• The AWT makes use of the GUI components of the underlying platform– Has the look and feel of the native windowing toolkit– The same AWT GUI may have a different appearance

on different platforms

• With J2SE came Swing components that allow a uniform look and feel to be specified across different platforms– Most Swing components are pure Java components

Page 4: 13 gui development

OOSSE - Java Lecture 12 4Apr 10, 2023

The Java Foundation Classes JFC

• The Java Foundation Classes form a set of classes for cross platform GUI development

• The Swing GUI components are part of JFC– They exist in the package javax.swing– Swing makes use of some of the classes found in

AWT

• Swing provides alternatives to most of the GUI components found in AWT– For examples JButton is a Swing alternative to Button

found in AWT– Swing GUI components are more portable and

flexible than the original AWT GUI components and generally preferred

Page 5: 13 gui development

OOSSE - Java Lecture 12 5Apr 10, 2023

Composite Design Pattern

• GUI components need to be displayed somewhere– A container manages a set of components

• Java makes use of the Composite Design Pattern– A component is the super class– A container IS A component but HAS A collection of

components

Page 6: 13 gui development

OOSSE - Java Lecture 12 6Apr 10, 2023

Layout Manager

• How are the components positioned within a container?

• How do you want them to be positioned?• Java allows the positioning to be decoupled from

the container– The container HAS A Layout Manager– A suitable layout can be plugged in

Page 7: 13 gui development

OOSSE - Java Lecture 12 7Apr 10, 2023

JFrame – A Swing Container

• JFrame is an example of a top level swing container– As are JDialog, JWindow and JApplet

• A top level swing container contains an instance of JRootPane

• JRootPane extends JComponent and contains:– A Component called the Glass Pane– A JLayeredPane

• A JlayeredPane contains:– A Container called the ContentPane and accessible

via the getContentPane method of the top level swing container

– An optional JMenuBar

Page 8: 13 gui development

OOSSE - Java Lecture 12 8Apr 10, 2023

Using JFrame

JFrame theFrame = new JFrame("Testing JFrame");theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

;theFrame.setSize(300,100);theFrame.setVisible(true);

Page 9: 13 gui development

OOSSE - Java Lecture 12 9Apr 10, 2023

Extending the JFrame class

• Normally JFrame is used as a starting point:

import java.awt.*;import javax.swing.*;

public class PeteFrame extends JFrame{

private JButton b1;private JLabel l1;

public PeteFrame (String sTitle){

super (sTitle);Container contentPane;contentPane = getContentPane();contentPane.setLayout(new FlowLayout());

Page 10: 13 gui development

OOSSE - Java Lecture 12 10Apr 10, 2023

Extending the JFrame class (continued)

b1 = new JButton("A button");l1 = new JLabel("this is a label");

contentPane.add(l1);contentPane.add(b1);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setSize(300,100);this.setVisible(true);

}}

Page 11: 13 gui development

OOSSE - Java Lecture 12 11Apr 10, 2023

Closing JFrames

• It is possible to choose what happens when a JFame is closed

• The setDefaultCloseOperation is used• It takes a single argument and suitable constants

are defined in JFrame:– DO_NOTHING_ON_CLOSE– HIDE_ON_CLOSE– DISPOSE_ON_CLOSE– EXIT_ON_CLOSE

• For example form the previous slide:– this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Page 12: 13 gui development

OOSSE - Java Lecture 12 12Apr 10, 2023

Layout Manager

• The positions of the components added to a container is determined by a layout manager

• In the previous example a flow layout manager was used– contentPane.setLayout(new FlowLayout());

• Some examples of existing layout managers are:– FlowLayout – left to right and horizontally centred– BorderLayout – NORTH, SOUTH, EAST, WEST and CENTER– GridLayout - evenly spaced rows and columns

– GridBagLayout– CardLayout

Page 13: 13 gui development

OOSSE - Java Lecture 12 13Apr 10, 2023

BorderLayout Example

import java.awt.*;import javax.swing.*;

public class BorderFrame extends JFrame{

private JButton n,s,e,w,c;public BorderFrame (String sTitle){

super (sTitle);Container contentPane;contentPane = getContentPane();contentPane.setLayout(new BorderLayout());n = new JButton("North");s = new JButton("South");e = new JButton("East");w = new JButton("West");c = new JButton("Centre");

Page 14: 13 gui development

OOSSE - Java Lecture 12 14Apr 10, 2023

BorderLayout Example (continued)

contentPane.add(n,BorderLayout.NORTH);contentPane.add(s,BorderLayout.SOUTH);contentPane.add(e,BorderLayout.EAST);contentPane.add(w,BorderLayout.WEST);contentPane.add(c,BorderLayout.CENTER);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setSize(300,300);this.setVisible(true);

}}

Page 15: 13 gui development

OOSSE - Java Lecture 12 15Apr 10, 2023

GridLayout Example

• Code fragment:

contentPane.setLayout(new GridLayout(4,3,2,2));buttons = new JButton [12] ;for (int i = 1; i < 10; ++i){

buttons[i] = new JButton (Integer.toString(i));contentPane.add(buttons[i]);

}buttons[10] = new JButton("*");contentPane.add(buttons[10]);buttons[0] = new JButton("0");contentPane.add(buttons[0]);buttons[11] = new JButton("#");contentPane.add(buttons[11]);

Page 16: 13 gui development

OOSSE - Java Lecture 12 16Apr 10, 2023

JPanel

• The easiest way to achieve more complicated layouts is to make use of JPanel

• JPanel is a simple container; a rectangular region– An instance of JPanel can use a specific layout

manager– Components can be added to the panel

• How could you build this GUI?

Page 17: 13 gui development

OOSSE - Java Lecture 12 17Apr 10, 2023

Using JPanel – Code Fragment

• First set up the JPanel and add components using the GridLayout:

numPanel = new JPanel();numPanel.setLayout(new GridLayout(4,3,2,2));buttons = new JButton [12] ;for (int i = 1; i < 10; ++i){

buttons[i] = new JButton (Integer.toString(i));numPanel.add(buttons[i]);

}buttons[10] = new JButton("*");numPanel.add(buttons[10]);buttons[0] = new JButton("0");numPanel.add(buttons[0]);buttons[11] = new JButton("#");numPanel.add(buttons[11]);

Page 18: 13 gui development

OOSSE - Java Lecture 12 18Apr 10, 2023

Using JPanel – Code Fragment

• Now add the panel, a text field and a label to a frame using the Border Layout manager:

Container contentPane;contentPane = getContentPane();contentPane.setLayout(new BorderLayout());

number = new JTextField();statusLabel = new JLabel("Ready for number");

contentPane.add(number,BorderLayout.NORTH);contentPane.add(statusLabel,BorderLayout.SOUTH);contentPane.add(numPanel,BorderLayout.CENTER);

Page 19: 13 gui development

OOSSE - Java Lecture 12 19Apr 10, 2023

Event Handling

Page 20: 13 gui development

OOSSE - Java Lecture 12 20Apr 10, 2023

Events

• We know how to add GUI components but at the moment there is little or no user interaction

• Java GUIs are event driven– Any user interaction with a GUI component

generates an event– An application handles the events

• An application must explicitly listen for events• For example a JButton generates an event when it

is clicked• A JButton can have an ActionListener added• The ActionListener has a method called

actionPerformed that is invoked when the button is clicked

Page 21: 13 gui development

OOSSE - Java Lecture 12 21Apr 10, 2023

JButton and the ActionListener Interface• Java makes use of the following design pattern to

allow application specific code to be added to handle an event

Page 22: 13 gui development

OOSSE - Java Lecture 12 22Apr 10, 2023

Adding an ActionListener

import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class MyFrame extends JFrame{private JButton stopButton;

…public MyFrame (String sTitle){ …

stopButton = new JButton("Stop");

stopButton.addActionListener( new StopButtonListener());

contentPane.add(stopButton); …

Page 23: 13 gui development

OOSSE - Java Lecture 12 23Apr 10, 2023

Building the ActionListener

• The ActionListener interface specifies one method that must be implemented to realize the interface

class StopButtonListener implements ActionListener{

public void actionPerformed(ActionEvent e){

System.exit(0);}

}

• Note the ActionEvent that is passed to the method– This describes the event in more detail

• In this example the application exits when the button is clicked

Page 24: 13 gui development

OOSSE - Java Lecture 12 24Apr 10, 2023

Events

• The ActionEvent e passed into the actionPerformed method contains information about the event

• One piece of information is the component that generated the event– This is obtained using the getSource method– e.getSource( )

• This is useful when the same event handler is used for more than one component :if (e.getSource() == buttonOne){ … }else if (e.getSource() == buttonTwo){ … }

Page 25: 13 gui development

OOSSE - Java Lecture 12 25Apr 10, 2023

Using Inner Classes

• If the event handler needs to access member variables and member methods of a class then it is convenient to make it an inner class– An inner class has access to the enclosing class

Page 26: 13 gui development

OOSSE - Java Lecture 12 26Apr 10, 2023

Using an Inner Class

public class PresenterFrame extends JFrame {String [] list; final int max; int pos = 0;JLabel title; JButton next; JButton prev;

public PresenterFrame(String sTitle, String [] theList) {super(sTitle);…

}class DirectionListener implements ActionListener{

public void actionPerformed(ActionEvent e){if (e.getSource() == next) { if (pos < max) +

+pos; }else if (e.getSource() == prev) {if (pos >0) --pos;

}title.setText(list[pos]);

}}

}

Page 27: 13 gui development

OOSSE - Java Lecture 12 27Apr 10, 2023

JTextField

• JTextField can be used for simple text input• JTextField has the following constructors:

– JTextField()– JTextField(“Initial text”)– JTextField(10)– JTextField(“name”, 30)

• Two of the most useful methods are:– void setText(String)– String getText()

• The alignment of text within the component is set using:– setHorizontalAlignment (int)– JTextField.LEADING, JTextField.CENTER, and

JTextField.TRAILING

Page 28: 13 gui development

OOSSE - Java Lecture 12 28Apr 10, 2023

JTextField and ActionListeners

• A JTextField component handles much of the user interaction

• When the user hits enter the component generates an event– an ActionEvent

• An inner class is normally written to implement the ActionListener interface– The actionPerformed method handles the event

Page 29: 13 gui development

OOSSE - Java Lecture 12 29Apr 10, 2023

JRadio

• JRadioButtons raise ActionEvents and can be listened for just like JButtons

• JRadioButtons can be added to a group so that only one of the buttons can be selected at a time

• Text can be associated with a JRadioButton– r1.setActionCommand("radio one");– and retrieved form an ActionEvent– e.getActionCommand()

• How would you generate:

Page 30: 13 gui development

OOSSE - Java Lecture 12 30Apr 10, 2023

JRadio – Sample Code

r1 = new JRadioButton("one");r2 = new JRadioButton("two");

…r1.setActionCommand("radio one");r2.setActionCommand("radio two");…ButtonGroup group = new ButtonGroup();group.add(r1); group.add(r2);

…r1.setSelected(true);JPanel radioPanel = new JPanel(new GridLayout(0, 1));radioPanel.add(r1);radioPanel.add(r2);…

Page 31: 13 gui development

OOSSE - Java Lecture 12 31Apr 10, 2023

JRadio – Sample Code

RadioListener rad = new RadioListener();r1.addActionListener(rad);r2.addActionListener(rad);…contentPane.add(radioPanel,BorderLayout.WEST);contentPane.add(radioStation,BorderLayout.EAST);…

}class RadioListener implements ActionListener{

public void actionPerformed(ActionEvent e){

radioStation.setText(e.getActionCommand());}

}

Page 32: 13 gui development

OOSSE - Java Lecture 12 32Apr 10, 2023

Menus

• A menu can be added to the top of a JFrame using a JMenuBar object

• Alternatively a pop up menu can be created using JPopupMenu

• In either case two related classes are useful– JMenu and JMenuItem

• Again the composite design pattern is used:– a JMenu IS A JMenuItem but – a JMenu also HAS A collection of JMenuItems

• A JMenuBar HAS A collection of JMenus• A JPopupMenu HAS A collection of JMenuItems

Page 33: 13 gui development

OOSSE - Java Lecture 12 33Apr 10, 2023

Creating a Menu

• First create an instance of JMenuBar• Then create one or more JMenu objects

– These will be added to the JMenuBar

• For each JMenu create the required JMenuItems and add them to the JMenu

• Add the JMenu objects to the JMenuBar• Add the JMenuBar to the JFrame using the

setJMenuBar method

• Creating a pop is very similar but the JMenu items are not required

Page 34: 13 gui development

OOSSE - Java Lecture 12 34Apr 10, 2023

Menus and Events

• Menus raise events when they are selected– ActionEvents

• The events can be listened for using an ActionListener in a similar way to JButton events

Page 35: 13 gui development

OOSSE - Java Lecture 12 35Apr 10, 2023

Dialogs

• A dialog is typically used for data entry– a dialog pops up, – the user enters data, – the dialog disappears, – the application uses the data

• A dialog provides context for data entry and closure when used in a modal way

• Dialogs can be modal or modeless• Java provides the class JDialog as the starting point

for building dialogs• An application shows an instance of a dialog

– Delegation methods are used to retrieve data from the dialog

Page 36: 13 gui development

OOSSE - Java Lecture 12 36Apr 10, 2023

Sample JDialog Code

• Extending the dialog class:public class MyNameDialog extends JDialog {

JTextField name ;MyNameDialog(String sTitle, JFrame owner){

super (owner, sTitle, true);name = new JTextField(20) ;

…}public String getName(){

return name.getText() ;}public void actionPerformed(ActionEvent e){

dispose();}

}

Page 37: 13 gui development

OOSSE - Java Lecture 12 37Apr 10, 2023

Sample JDialog Code

• Constructiong the dialog:

dlg = new MyNameDialog("Name Dialog", PeteFrame.this);

• Invoking the dialog in an inner ActionListener class within the PeteFrame extension of JFrame

public void actionPerformed(ActionEvent e){

dlg.setVisible(true);l1.setText(dlg.getName() );

}

Page 38: 13 gui development

OOSSE - Java Lecture 12 38Apr 10, 2023

JOptionPane

• JOptionPane provides support for several simple and easy to use pre-defined dialogs

• The dialogs can be displayed without instantiating the class

• JOptionPane has many static methods such as:– showMessageDialog– showConfirmDialog– showInputDialogOptionDialog

• Some, such as the confirm dialog, have a return value that can be checked with a simple if others do not

• There are numerous overloaded versions of the methods– See the sun documentation for further details

Page 39: 13 gui development

OOSSE - Java Lecture 12 39Apr 10, 2023

JOptionPane – Code Sample

• Using JOptionPane to confirm an action:

public void actionPerformed(ActionEvent e){

if (JOptionPane.showConfirmDialog(null,"Do you want to stop?", "Stopping the Application",

J OptionPane.OK_CANCEL_OPTION )

== JOptionPane.OK_OPTION ){

System.exit(0);}

}

Page 40: 13 gui development

OOSSE - Java Lecture 12 40Apr 10, 2023

Mouse Events

• When a JButton is pressed only one event occurs– an ActionEvent– the ActionListener interface only specified 1 method

• A mouse is capable of generating several different types of event– Mouse click, mouse press, mouse release, mouse move

• The mouse moves very frequently and responding to each event associated with movement may be too expensive for many applications

• Java provides:– A MouseListener that is associated with mouse actions– A MouseMotionListener that is associated with

movement

Page 41: 13 gui development

OOSSE - Java Lecture 12 41Apr 10, 2023

The MouseListener Interface

• The MouseListener interface caters for possible actions associated with a mouse:public interface MouseListener{

void mouseClicked(MouseEvent event);void mousePressed(MouseEvent event);void mouseReleased(MouseEvent event);void mouseEntered(MouseEvent event);void mouseExited(MouseEvent event);

}

• Not all of these may be of interest in an application– BUT to implement an interface all methods must be

implemented– Java introduces the MouseAdapter class to make life easier

Page 42: 13 gui development

OOSSE - Java Lecture 12 42Apr 10, 2023

The MouseAdapter Class

• The MouseAdapter class implements all the methods in the MouseListener interface with do nothing methods

• This class can be used as the base of mouse event handler classes that then only need to override the methods of interestpublic class MouseAdapter implements MouseListener{

public void mouseClicked(MouseEvent event) { }public void mousePressed(MouseEvent event) { }public void mouseReleased(MouseEvent event) { }public void mouseEntered(MouseEvent event) { }public void mouseExited(MouseEvent event) { }

}

Page 43: 13 gui development

OOSSE - Java Lecture 12 43Apr 10, 2023

The MouseMotionAdapter Class

• The MouseMotionAdapter class implements all the methods in the MouseMotionListener interface with do nothing methods

• This class can be used as the base of mouse event handler classes that then only need to override the methods of interestpublic class MouseMotionAdapter implements

MouseMotionListener{

public void mouseMoved(MouseEvent event) { }public void mouseDragged(MouseEvent event) { }

}

Page 44: 13 gui development

OOSSE - Java Lecture 12 44Apr 10, 2023

An Anonymous MouseListener

• Mouse events can be handled using an anonymous class– The anonymous class extends the MouseAdapter class rather

than implementing the MouseListener interface directly

public class MyPanel extends JPanel{

public MyPanel ( ){ … addMouseListener ( new MouseAdapter ( )

{ public void mousePressed (MouseEvent e) { … }

} )

}}

Page 45: 13 gui development

OOSSE - Java Lecture 12 45Apr 10, 2023

Using an Anonymous MouseListener

Page 46: 13 gui development

OOSSE - Java Lecture 12 46Apr 10, 2023

Summary

In this lecture we have:• Introduced the Abstract Window Toolkit • Introduced the Java Foundation Classes• Discussed containers and layout managers• Introduced events and event handling• Introduced menus • Introduced dialogs• Discussed mouse events

Page 47: 13 gui development

OOSSE - Java Lecture 12 47Apr 10, 2023

Useful Websites

http://java.sun.com/docs/books/tutorial/uiswing/components/componentlist.html