51
Chapter 9 - Graphical User Interfaces and Applets 1 Introduction to Java Chapter 9 Graphical User Interfaces and Applets

Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Embed Size (px)

Citation preview

Page 1: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 1

Introduction to Java

Chapter 9

Graphical User Interfaces and Applets

Page 2: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 2

Introduction to Java

Java GUIs• The Java SDK contains to different Graphical

User Interfaces (GUIs)– The Abstract Windowing Toolkit (AWT), which

contained the original Java GUI

– The Swing package, which is a newer, more flexible Java GUI

• Only the Swing GUI is taught in this text

Page 3: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 3

Introduction to Java

How GUIs Work• GUIs provide a user with a familiar environment in

which to work, with push buttons, menus, drop-down lists, text fields, etc.

• GUI-based programs are harder to program, since they must be ready for mouse clicks or keyboard input to any component at any time

• Mouse clicks or keyboard inputs are known as events, and GUI-based programs are event-driven

Page 4: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 4

Introduction to Java

How GUIs Work (2)• A GUI consists of:

– GUI Components, which represent elements on the screen such as push buttons, text fields, etc.

– A Container to hold the components. The containers in this chapter are JPanel and JFrame.

– A Layout Manager to control the placement of GUI components within the container.

– Event handlers to respond to mouse clicks or keyboard inputs on any component or container in the GUI

Page 5: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 5

Introduction to Java

Creating and Displaying a GUI• To create a GUI:

– Create a container class to hold the GUI components

– Select and create a layout manager for the container

– Create components and add them to the container

– Create “listener” objects to detect and respond to the events expected by each GUI component

– Register the listeners with appropriate components

– Create a JFrame object, and place the completed container in the center of content pane associated with the frame.

Page 6: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 6

Introduction to Java

4 import java.awt.*; 5 import java.awt.event.*; 6 import javax.swing.*; 7 public class FirstGUI extends JPanel { 8 9 // Instance variables10 private int count = 0; // Number of pushes11 private JButton pushButton; // Push button12 private JLabel label; // Label1314 // Initialization method15 public void init() {1617 // Set the layout manager18 setLayout( new BorderLayout() );1920 // Create a label to hold push count21 label = new JLabel("Push Count: 0");22 add( label, BorderLayout.NORTH );23 label.setHorizontalAlignment( label.CENTER );2425 // Create a button26 pushButton = new JButton("Test Button");27 pushButton.addActionListener( new ButtonHandler(this) );28 add( pushButton, BorderLayout.SOUTH );29 }3031 // Method to update push count32 public void updateLabel() {33 label.setText( "Push Count: " + (++count) );34 }35 }

Creating and Displaying a GUI (2)

Required packages

Set layout manager

Create GUI in init method

Create GUI components

Method (s) to implement actions

Add listener for button

Page 7: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 7

Introduction to Java

38 public static void main(String s[]) {3940 // Create a frame to hold the application41 JFrame fr = new JFrame("FirstGUI ...");42 fr.setSize(200,100);4344 // Create a Window Listener to handle "close" events45 WindowHandler l = new WindowHandler();46 fr.addWindowListener(l);4748 // Create and initialize a FirstGUI object49 FirstGUI fg = new FirstGUI();50 fg.init();5152 // Add the object to the center of the frame53 fr.getContentPane().add(fg, BorderLayout.CENTER);5455 // Display the frame56 fr.setVisible( true );57 }5859 class ButtonHandler implements ActionListener {60 private FirstGUI fg;6162 // Constructor63 public ButtonHandler ( FirstGUI fg1 ) {64 fg = fg1;65 }6667 // Execute when an event occurs68 public void actionPerformed( ActionEvent e ) {69 fg.updateLabel();70 }71 }

Creating and Displaying a GUI (3)Create JFrame

Add GUI to JFrame

Create and add window listener

Define listener class for pushbutton

main method, so the program starts here

Method init called here, so GUI created here

Page 8: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 8

Introduction to Java

Creating and Displaying a GUI (4)

• Result after three mouse clicks on the button:

Page 9: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 9

Introduction to Java

Events and Event Handling• An event is an object that is created by some external

action (mouse click, key press, etc.)• When an event such as a mouse click occurs, Java

automatically sends that event to the GUI object that was clicked on.

• When the event is received by the GUI object, the object checks to see if any listener object has registered with it to receive the event, and it forwards the event to the actionPerformed method of that object.

Page 10: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 10

Introduction to Java

Events and Event Handling (2)• The actionPerformed method is known as an event

handler because it performs whatever steps are required to process the event.

• In many cases, the event handler makes a call to a callback method in the object that created the GUI, since such methods can update instance variables within the object directly– In the previous example, class ButtonHandler was a

listener, its method actionPerformed was an event handler, and method updateLabel was a callback method

Page 11: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 11

Introduction to Java

Events and Event Handling (3)• In the previous example:

– A mouse click on the button creates an event

– The event is sent to the JButton object

– The JButton object sends the event to the action-Performed method of the ButtonHandler object

– That method calls the method updateLabel (callback)

– updateLabel updates the label

JButton o b ject

Constructors

Methods

Inherited

Method(s)

Instancevariables

Methods

Constructors

Methods

Inherited

Method(s)

Instancevariables

Methods

Constructors

Methods

Inherited

Method(s)

Instancevariables

Methods

ButtonHandler o b ject

FirstGUI o b ject

Constructors

Methods

Inherited

Method(s)

Instancevariables

Methods

JLabel o b ject

actionPerformed

(ActionEvent e)

update

Label(

)

setText("Push Count: "

+ (++count))

O r ig in a l e v e n t:M o use c l ick o n b utto n

M ou se even t sen t to JButton

Page 12: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 12

Introduction to Java

The JLabel Class• A label is an object that displays a single line of read-only

text and/or an image.– It does not respond to mouse clicks or keyboard input.

• Constructors:public JLabel();

public JLabel(String s);

public JLabel(String s, int horizontalAlignment);

public JLabel(Icon image);

public JLabel(Icon image, int horizontalAlignment);

public JLabel(String s, Icon image, int horizontalAlignment);

• These constructors create a label containing text s, image image, or both

Page 13: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 13

Introduction to Java

The JLabel Class (2)• Methods:

Method Description

public Icon getIcon() Returns the image from a JLabel.

public String getText() Returns the text from a JLabel.

public void setIcon(Icon image) Sets the JLabel image.

public void setText(String s) Sets the JLabel text.

public void setHorizontalAlignment( int alignment)

Sets the horizontal alignment of the JLabeltext and image. Legal values are LEFT,CENTER, and RIGHT.

public void setHorizontalTextPosition( int textPosition)

Sets the position of the text relative to theimage. Legal values are LEFT, CENTER, andRIGHT.

public void setVerticalAlignment( int alignment)

Sets the vertical alignment of the JLabeltext and images. Legal values are TOP,CENTER, and BOTTOM.

public void setVerticalTextPosition( int textPosition)

Sets the position of the text relative to theimage. Legal values are TOP, CENTER, andBOTTOM.

Page 14: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 14

Introduction to Java

Example: The JLabel Class // Get the images to display ImageIcon right = new ImageIcon("BlueRightArrow.gif"); ImageIcon left = new ImageIcon("BlueLeftArrow.gif");

// Create a label with icon and text l1 = new JLabel("Label 1", right, JLabel.LEFT); add( l1, BorderLayout.NORTH );

// Create a label with text and icon l2 = new JLabel("Label 2", left, JLabel.RIGHT); add( l2, BorderLayout.CENTER ); l2.setHorizontalTextPosition( JLabel.LEFT );

// Create a label with text only l3 = new JLabel("Label 3 (Text only)", JLabel.CENTER); add( l3, BorderLayout.SOUTH ); }

Page 15: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 15

Introduction to Java

The JButton Class• The JButton class creates a pushbutton.

– When a mouse clicks on a button, an ActionEvent is generated and passed to any registered listeners.

• Constructors:public JButton();

public JButton(String s);

public JButton(Icon image);

public JButton(String s, Icon image);

• These constructors create a pushbutton containing text s, image image, or both

Page 16: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 16

Introduction to Java

Example: Creating Buttons // Create buttons b1 = new JButton("Enable",right); b1.addActionListener( this ); b1.setMnemonic('e'); b1.setToolTipText("Enable middle button"); add(b1);

String s = "Count = " + c; b2 = new JButton(s,green); b2.addActionListener( this ); b2.setMnemonic('c'); b2.setEnabled(false); b2.setToolTipText("Press to increment count"); b2.setPressedIcon(yellow); b2.setDisabledIcon(red); add(b2);

b3 = new JButton("Disable",left); b3.addActionListener( this ); b3.setMnemonic('d'); b3.setEnabled(false); b3.setToolTipText("Disable middle button"); add(b3); }

Page 17: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 17

Introduction to Java

ActionEvent Events

• JButtons generate ActionEvent objects when an event (mouse click) occurs on them.

• A listener class for these events must implement the ActionListener interface, and have an action-Performed method.

• An listener object must be registered to listen for ActionEvents on each button.

• When a mouse click occurs, the actionPerformed method of the corresponding listener object will be called to handle the event

Page 18: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 18

Introduction to Java

The JTextField Class• The JTextField class creates a text field.

– When a user types text and presses the ENTER key, an ActionEvent is generated and passed to any registered listeners.

• Constructors:public JTextField();

public JTextField(int cols);

public JTextField(String s);

public JTextField(String s, int cols);

• These constructors create a text field containing a blank space large enough for cols characters, the text string s, or both

Page 19: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 19

Introduction to Java

The JPasswordField Class• The JPasswordField class is identical to the JPasswordField class, except the text typed into the field is not visible. Instead, a string of asterisks are shown to represent the characters typed.

• Constructors:public JPasswordField();

public JPasswordField(int cols);

public JPasswordField(String s);

public JPasswordField(String s, int cols);

Page 20: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 20

Introduction to Java

Example: Creating Text Fields

// Create first Text Field l1 = new JLabel("Visible text here:",JLabel.RIGHT); add( l1 ); t1 = new JTextField("Enter Text Here",25); t1.addActionListener( handler ); add( t1 );

// Create Password Field l2 = new JLabel("Hidden text here:",JLabel.RIGHT); add( l2 ); t2 = new JPasswordField("Enter Text Here",25); t2.addActionListener( handler ); add( t2 );

// Create third Text Field l3 = new JLabel("Results:",JLabel.RIGHT); add( l3 ); t3 = new JTextField(25); t3.setEditable( false ); add( t3 );

Page 21: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 21

Introduction to Java

The JComboBox Class• The JComboBox class field in which a user can either type

text or select a choice from a drop down list of options.

• Constructors:public JComboBox();

public JComboBox( Object[] );

public JComboBox( Vector );

• These constructors create a combo containing list of choices from the Object or Vector

• A user can be forced to select from the drop down list only using the method setEditable(false)

Page 22: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 22

Introduction to Java

Example: Creating Combo Boxes

// Create the JComboBox String[] s = {"Serif","SansSerif","Monospaced", "Dialog"}; c1 = new JComboBox(s); c1.addActionListener( handler ); add( c1 );

// Create the text field with default font Font font = new Font(c1.getItemAt(0).toString(), Font.PLAIN, 14); t1 = new JTextField("Test string",30); t1.setEditable( false ); t1.setFont( font ); add( t1 );

Page 23: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 23

Introduction to Java

The JCheckBox Class• The JCheckBox class creates a special type of button that

toggles between “on” and “off” each time it is clicked.

• It looks like a small box with a check mark, but it is really a full-fledged button

• Selected Constructors:public JCheckBox( String s, boolean state );

public JCheckBox( Icon image, boolean state );

public JCheckBox( String s, Icon image, boolean state );

• These constructors create a check box containing text s, image image, or both, in initial state state

Page 24: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 24

Introduction to Java

// Create the JComboBox for font names String[] s = {"Serif","SansSerif","Monospaced", "Dialog"}; c1 = new JComboBox(s); c1.addActionListener( h1 ); add( c1 );

// Create the text field with default font Font font = new Font( c1.getItemAt(0).toString(), Font.PLAIN, 14); t1 = new JTextField("Test string",20); t1.setEditable( false ); t1.setFont( font ); add( t1 );

// Create check boxes for bold and italic cb1 = new JCheckBox("Bold"); cb1.addActionListener( h1 ); cb1.setMnemonic('b'); add( cb1 ); cb2 = new JCheckBox("Italic"); cb2.addActionListener( h1 ); cb2.setMnemonic('i'); add( cb2 );

Example: Creating Check Boxes

Page 25: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 25

Introduction to Java

The JRadioButton Class• The JRadioButton class creates a radio button, a

small circle with a dot in the center when “on”.• Selected Constructors:

public JRadioButton( String s, boolean state );

public JRadioButton( Icon image, boolean state );

public JRadioButton( String s, Icon image, boolean state );

• These constructors create a radio button containing text s, image image, or both, in initial state state

Page 26: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 26

Introduction to Java

Button Groups• Radio buttons are grouped together into groups

known as button groups. • Only one button within a group may be on at any

time. If one is turned on, the other radio buttons in the group will be forced off

• Constructor:public ButtonGroup();

• Methods:public void add(AbstractButton b); // Add button to group

public void remove(AbstractButton b); // Remove from group

Page 27: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 27

Introduction to Java

// Create radio buttons b1 = new JRadioButton("Plain", true ); b1.addActionListener( h1 ); add( b1 ); b2 = new JRadioButton("Bold", false ); b2.addActionListener( h1 ); add( b2 ); b3 = new JRadioButton("Italic", false ); b3.addActionListener( h1 ); add( b3 ); b4 = new JRadioButton("Bold Italic", false ); b4.addActionListener( h1 ); add( b4 );

// Create button group, and add radio buttons bg = new ButtonGroup(); bg.add( b1 ); bg.add( b2 ); bg.add( b3 ); bg.add( b4 );

Example: Creating Radio Buttons

ButtonGroup ensures that the 4 radio buttons are mutually exclusive

Page 28: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 28

Introduction to Java

Layout Managers• Layout managers are classes that control the

location of components within a containerStandard Layout Managers

Element DescriptionBorderLayout A layout manager that lays out elements in a central region and

four surrounding borders. This is the default layout manager for aJFrame.

BoxLayout A layout manager that lays out elements in a row horizontally orvertically. Unlike FlowLayout, the elements in a BoxLayout donot wrap around. This is the default layout manager for a Box.

CardLayout A layout manager that stacks components like a deck of cards, onlythe top one of which is visible.

FlowLayout A layout manager that lays out elements left-to-right and top-to-bottom within a container. This is the default layout manager for aJPanel.

GridBagLayout A layout manager that lays out elements in a flexible grid, wherethe size of each element can vary.

GridLayout A layout manager that lays out elements in a rigid grid.

Page 29: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 29

Introduction to Java

BorderLayout Layout Manager• The BorderLayout layout manager arranges components in

five regions, known as North, South, East, West, and Center• Constructors:

public BorderLayout();

public BorderLayout(int horizontalGap, int verticalGap);

• A layout manager is associated with a container using the container’s setLayout method:setLayout( new BorderLayout() );

• Components are added to specific regions with a special option of the container’s add method: add(new Button("North"), BorderLayout.NORTH);

• Default layout manager for JFrame

Page 30: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 30

Introduction to Java

setLayout(new BorderLayout());add(new Button("North"), BorderLayout.NORTH);add(new Button("South"), BorderLayout.SOUTH);add(new Button("East"), BorderLayout.EAST);add(new Button("West"), BorderLayout.WEST);add(new Button("Center"), BorderLayout.CENTER);

Example: Creating a BorderLayout

Page 31: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 31

Introduction to Java

FlowLayout Layout Manager• The FlowLayout layout manager arranges com-

ponents in order from left to right and top to bottom across a container

• Constructors:public FlowLayout();

public FlowLayout(int align);

public FlowLayout(int align, int horizontalGap,

int verticalGap);

• The alignment can be LEFT, RIGHT, or CENTER• Default layout manager for JPanel

Page 32: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 32

Introduction to Java

Example: Creating a FlowLayout

setLayout(new FlowLayout(FlowLayout.CENTER,5,0));add(new JButton("Button 1"));add(new JButton("Button 2"));add(new JButton("Long Button 3"));add(new JButton("B4"));add(new JButton("Button 5"));

Page 33: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 33

Introduction to Java

GridLayout Layout Manager

• The GridLayout layout manager arranges components in a rigid rectangular grid structure.

• Constructors:public GridLayout(int rows, int cols);

public GridLayout(int rows, int cols, int horizGap,

int vertGap);

• Components are added to the grid in order from left to right and top to bottom

Page 34: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 34

Introduction to Java

Example: Creating a GridLayoutsetLayout(new GridLayout(3,2));add(new JButton("1"));add(new JButton("2"));add(new JButton("3"));add(new JButton("4"));add(new JButton("5"));add(new JButton("6"));

Page 35: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 35

Introduction to Java

BoxLayout Layout Manager

• The BoxLayout layout manager arranges components within a container in a single row or a single column.

• The spacing and alignment of each element on each row or column can be individually controlled.

• Containers using BoxLayout managers can be nested inside each other to produce complex layouts

• Constructor:public BoxLayout(Container c, int direction);

• The direction can be X_AXIS or Y_AXIS• Rigid areas and glue regions can be used to space out

components within a BoxLayout

Page 36: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 36

Introduction to Java

Example: Creating a BoxLayout// Create a new panelJPanel p = new JPanel();

// Set the layout managerp.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));

// Add buttonsp.add( new JButton("Button 1") );p.add( Box.createRigidArea(new Dimension(0,20)) );p.add( new JButton("Button 2") );p.add( Box.createRigidArea(new Dimension(0,5)) );p.add( new JButton("Button 3") );

// Add the new panel to the existing containeradd( p );

Page 37: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 37

Introduction to Java

Combining Layout Managers to Produce a Result

• To create just the look you want, it is sometimes useful to create multiple containers inside each other, each with its own layout manager

• For example, a top-level panel might use a horizontal box layout, and that panel may contain two or more panels using vertical box layouts

• The result is complete control of component spacing in both dimensions

Page 38: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 38

Introduction to Java

// Create a new high-level panelJPanel pHoriz = new JPanel();pHoriz.setLayout(new BoxLayout(pHoriz, BoxLayout.X_AXIS));add( pHoriz );

// Create two subordinate panelsJPanel pVertL = new JPanel();JPanel pVertR = new JPanel();pVertL.setLayout(new BoxLayout(pVertL, BoxLayout.Y_AXIS));pVertR.setLayout(new BoxLayout(pVertR, BoxLayout.Y_AXIS));

// Add to pHoriz with a horizontal space between panelspHoriz.add( pVertL );pHoriz.add( Box.createRigidArea(new Dimension(20,0)) );pHoriz.add( pVertR );

// Create degrees Celsius fieldl1 = new JLabel("deg C:", JLabel.RIGHT);pVertL.add( l1 );t1 = new JTextField("0.0",15);t1.addActionListener( cHnd );pVertR.add( t1 );

// Create degrees Fahrenheight fieldl2 = new JLabel("deg F:", JLabel.RIGHT);pVertL.add( l2 );t2 = new JTextField("32.0",15);t2.addActionListener( fHnd );pVertR.add( t2 );

Example: Nested Containers and Layouts

pHoriz

pVertL pVertR

l1

l2

t1

t2

Structure:

Result:

Page 39: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 39

Introduction to Java

Applets• An applet is a special kind of Java program that is

designed to run inside a Web browser– It is a subclass of javax.swing.JApplet

– The JApplet class is similar to JFrame, in that components must be attached to its content pane

– The JApplet class is similar to JPanel, in that the default layout is FlowLayout

• Applets are usually restricted from accessing computer resources (files, etc.) on the local computer for security reasons

Page 40: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 40

Introduction to Java

Applet Methods

• Every applet has 5 standard methods:– init — called by the browser when the applet is first

loaded into memory– start — called by the browser to start animations running

when the applet is made visible– stop — called by the browser to stop animations running

when the applet is covered or minimized– destroy — called by the browser just before the applet is

destroyed– paintComponent — called when the applet is drawn or re-

drawn

Page 41: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 41

Introduction to Java

Applet Methods

• Applet methods will always be called in the order init, start, stop, destroy

• start and stop may be called many times during the life of an applet

• All 5 methods are implemented as dummy methods in class JApplet, and the dummy methods are inherited by all applets

• Applets override only the methods that they need to perform their function

Page 42: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 42

Introduction to Java

Creating an Applet• To create an applet:

– Create a subclass of JApplet to hold GUI components– Select a layout manager for the container, if the default

layout manager (FlowLayout) is not acceptable– Create components and add them to the content pane of the JApplet container.

– Create “listener” objects to detect and respond to the events expected by each GUI component, and assign the listeners to appropriate components.

– Create an HTML text file to specify to the browser which Java applet should be loaded and executed

Page 43: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 43

Introduction to Java

Example: Creating an Applet 4 import java.awt.*; 5 import java.awt.event.*; 6 import javax.swing.*; 7 public class FirstApplet extends JApplet { 8 9 // Instance variables10 private int count = 0; // Number of pushes11 private JButton pushButton; // Push button12 private JLabel label; // Label1314 // Initialization method15 public void init() {1617 // Set the layout manager18 getContentPane().setLayout( new BorderLayout() );1920 // Create a label to hold push count21 label = new JLabel("Push Count: 0");22 getContentPane().add( label, BorderLayout.NORTH );23 label.setHorizontalAlignment( label.CENTER );2425 // Create a button26 pushButton = new JButton("Test Button");27 pushButton.addActionListener( new ButtonHandler(this) );28 getContentPane().add( pushButton, BorderLayout.SOUTH );29 }3031 // Method to update push count32 public void updateLabel() {33 label.setText( "Push Count: " + (++count) );34 }35 }

This simple applet implements init and inherits all other methods as dummies

Note that all components are added to the ContentPane of the JApplet

Page 44: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 44

Introduction to Java

Example: Creating an Applet (2)

Listener class for button on applet

37 class ButtonHandler implements ActionListener {38 private FirstApplet fa;3740 // Constructor41 public ButtonHandler ( FirstApplet fa1 ) {42 fa = fa1;43 }4445 // Execute when an event occurs46 public void actionPerformed( ActionEvent e ) {47 fa.updateLabel();48 }49 }

1 <html> 2 <applet code="FirstApplet.class" width=200 height=100> 3 </applet> 4 </html>

HTML code to start applet in browser

Page 45: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 45

Introduction to Java

Location of Class Files for Applets

• If an applet uses a class that is not built into a package, that class must be present in the same directory as the HTML file used to start the applet– This directory could be

local or remote—it doesn’t matter

– Class files can be transferred over the net, so they should be small

some directory

HTML f ile class f ile (s )

Page 46: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 46

Introduction to Java

Using Packages with Applets

• If an applet uses non-standard package, then the package must appear in the appropriate subdirec-tory of the directory containing the HTML file.– This directory could be local

or remote—it doesn’t matter– CLASSPATH is ignored by

applets!

some directory

HTML f ile class f ile (s ) chapman

io

Fmt c las s

Location of class chapman.io.Fmt within package chapman.io

Page 47: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 47

Introduction to Java

Creating Dual Application / Applets

• If an application does not need to perform I/O or other restricted tasks, it can be structured to run both as an applet and an application– Design the program as an applet– Add a main method with calls to init and start

– Add calls to stop and destroy in the windowClosing method of the Window handler

• Such program can be more versatile

Page 48: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 48

Introduction to Java

Dual Application / Appletimport java.awt.*;import java.awt.event.*;import javax.swing.*;import chapman.io.*;public class TempConversionApplet extends JApplet {

// Instance variables private JLabel l1, l2; // Labels private JTextField t1, t2; // Text Fields private DegCHandler cHnd; // ActionEvent handler private DegFHandler fHnd; // ActionEvent handler

// Initialization method public void init() {

... }

init method in applet

Page 49: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 49

Introduction to Java

Dual Application / Applet (2)

// Main method to create frame public static void main(String s[]) {

// Create a frame to hold the application JFrame fr = new JFrame("TempConversionApplet ..."); fr.setSize(250,100);

// Create and initialize a TempConversionApplet object TempConversionApplet tf = new TempConversionApplet(); tf.init(); tf.start();

// Create a Window Listener to handle "close" events AppletWindowHandler l = new AppletWindowHandler(tf); fr.addWindowListener(l);

// Add the object to the center of the frame fr.getContentPane().add(tf, BorderLayout.CENTER);

// Display the frame fr.setVisible( true ); }}

main method calls init and start

Page 50: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 50

Introduction to Java

Dual Application / Applet (3)

public class AppletWindowHandler extends WindowAdapter { JApplet ap;

// Constructor public AppletWindowHandler ( JApplet a ) { ap = a; }

// This method implements a listener that detects // the "window closing event", shuts down the applet, // and stops the program. public void windowClosing(WindowEvent e) { ap.stop(); ap.destroy(); System.exit(0); };}

windowClosing method calls stop and destroy

Page 51: Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets

Chapter 9 - Graphical User Interfaces and Applets 51

Introduction to Java

Dual Application / Applet (4)

Running as application Running as applet