scott grissom, copyright 2004ch 12: swing slide 1 how do i learn gui development? use these lecture...

28
Scott Grissom, copyright 2004 Ch 12: Swing Slide 1 How do I learn GUI development? Use these lecture notes to supplement chapter 12 Refer to the online documentation available from the course web site Use the sample code available on the EOS machines ~grissom/163/Demos

Post on 22-Dec-2015

213 views

Category:

Documents


1 download

TRANSCRIPT

Scott Grissom, copyright 2004 Ch 12: Swing Slide 1

How do I learn GUI development?

• Use these lecture notes to supplement chapter 12

• Refer to the online documentation available from the course web site

• Use the sample code available on the EOS machines

~grissom/163/Demos

Scott Grissom, copyright 2004 Ch 12: Swing Slide 2

Java JFC/Swing

• Java provides strong support for building GUIs through the javax.swing package

• Platform independencesame code

same appearance

• The book covers:containers (12.2.2)

layout managers (12.2.3)

event classes (12.4)

listener classes (12.4)

GUI components (12.3)

Scott Grissom, copyright 2004 Ch 12: Swing Slide 3

Event-Driven Programming

• Events signal important user actions, like a mouse click

• Listeners contain methods that respond to specific events

• GUI components are the screen elements that a user manipulates with the mouse and keyboard

• Layout managers govern how the components appear on the screen

Scott Grissom, copyright 2004 Ch 12: Swing Slide 4

Containers (12.2.2)

• A container is a special category of GUI components that hold other components

• A Japplet is a container used for applets

• A JFrame is used for an application

• A JPanel is used to group related components together for appearances

Scott Grissom, copyright 2004 Ch 12: Swing Slide 5

Layout Managers (12.2.3)

• One approach is to explicitly place componentssetLocation(int x, int y)

wrt to upper left corner

this is discouraged!

• Java JFC layout is dynamic to allow for different screen sizes and platformsautomatically sizes and places components

• There are several layout managers to choose from:flow layout

border layout

grid layout

box layout (not in book)

• Each container has a particular layout manager as default

Scott Grissom, copyright 2004 Ch 12: Swing Slide 6

Flow Layout

• Components are placed in a row from left to right in the order in which they are added

• New rows are created as needed

• Flow layout is the default layout for JPanels and Japplets

• Components are displayed at their preferred size

• Refer to sample code ~grissom/163/Demos/flowLayout.java

Scott Grissom, copyright 2004 Ch 12: Swing Slide 7

Border Layout

• Defines five locations where a component can be addedNorth, South, East, West, and Center

• The programmer specifies the area in which a component should appearadd(BorderLayout.NORTH, comp)

• Only one component per location

• Components expand to full size

• Use a JPanel to hold more than one

• Default for JFrame

• Refer to sample code ~grissom/163/Demos/borderLayout.java

Scott Grissom, copyright 2004 Ch 12: Swing Slide 8

JPanels

• Place multiple components inside a Panel

• Set the layout manager

• Sample CodeJPanel p = new JPanel();

p.setLayout(new FlowLayout());

Jbutton b1 = new Jbutton(“one”);

Jbutton b2 = new Jbutton(“two”);

p.add (b1);

p.add (b2);

getContentPane().add(p,BorderLayout.NORTH);

• Refer to sample code ~grissom/163/Demos/panelLayout.java

Scott Grissom, copyright 2004 Ch 12: Swing Slide 9

Box Layout

• Not covered in book

• Components are placed in a row OR a column as specified

• Create space between componentsBox.createRigidArea()

Box.createHorizontalGlue()

• Sample CodeBoxLayout b;

b = new BoxLayout(this, BoxLayout.X_AXIS)

• Refer to sample code ~grissom/163/Demos/boxLayout.java

Scott Grissom, copyright 2004 Ch 12: Swing Slide 10

Grid Layout

• Components are placed in a grid with a user-specified number of columns and rows

• Each cell is the same size

• Components placed left to right and top to bottom

• GridBag layout is a more advanced managerFeel free to experiment

Scott Grissom, copyright 2004 Ch 12: Swing Slide 11

The Big GUI Picture

• Refer to the sample code on the pink handoutGUIcounter.java

Counter.java

• Copy these files, compile them and run the application

• Experiment by changing attributes and see the results

• Code available on EOS~grissom/163/Demos/GUIcounter.java

~grissom/163/Demos/Counter.java

Scott Grissom, copyright 2004 Ch 12: Swing Slide 12

Events & Listeners (12.4)

• When the user performs an action, an event is fired

• Special methods, event handlers, are called automatically by the system

• But only if the component has been registered properly

• For exampleA mother and her son at the park

Scott Grissom, copyright 2004 Ch 12: Swing Slide 13

Buttons (as an example)

• Buttons only generate one kind of event, actionEvent

• An action event requires a special method to be provided

• public void actionPerformed(ActionEvent e)String str = e.getActionCommand();

if (str.equals(“sort”)

• orJComponent = e.getSource();

if (comp == SortButton)

Scott Grissom, copyright 2004 Ch 12: Swing Slide 14

Using GUI Components

• Four Critical Steps1) define as an instance variable2) instantiate the component in the JFrame constructor3) display within a container4) register a listener

• For ExamplesortButton = new JButton (“Sort”);getContentPane().add (sortButton);sortButton.addActionListener(this);

Scott Grissom, copyright 2004 Ch 12: Swing Slide 15

Other events

• Other components generate other events

• See Table 12.5 on page 734

• Which events are fired?mouse moves over a component

window is iconified

JCheckbox is checked

Scott Grissom, copyright 2004 Ch 12: Swing Slide 16

Who is listening?

• There are several approaches to assigning listening responsibility

• Each have strengths and weaknesses

• I prefer to have the Frame listen (Figure 12.16)

Scott Grissom, copyright 2004 Ch 12: Swing Slide 17

GUI Components (12.3)

• There are several GUI components that permit specific kinds of user interaction:JTextField, JTextArea

JButton, JComboBox, JCheckBox

JLabel, JMenu

• Important Methods inherited from JComponentsetBackground(Color c)

setEnabled(boolean)

setSize(width, height)

setVisible(boolean)

Scott Grissom, copyright 2004 Ch 12: Swing Slide 18

JTextField and JTextArea

• A text field displays a single line of text in a GUI

• It can be made editable

• A text area displays multiple lines of text

• A text area automatically has scrollbars on its bottom and right sides if needed

• Sample CodeJTextField text = new JTextField (15);

place on screen

text.setText(“my name”);

String str = text.getText( );

Scott Grissom, copyright 2004 Ch 12: Swing Slide 19

JButton

• A button can be created with or without a label

• An application is usually designed such that when a button is pressed, a particular action occurs

• JButton generates action events

• Sample CodeJButton b = new JButton(“label”);

getContentPane().add(b);

b.addActionListener(this);

• Sample Action ListenerJButton current = (JButton) e.getSource();

if (current == b)

// do something

Scott Grissom, copyright 2004 Ch 12: Swing Slide 20

JComboBox

• A combo box displays a list of choices when pushed

• The user can then scroll through and choose the appropriate option

• JComboBox generates action events and item events

• Sample CodeString[] pets = {“bird”, “cat”, “dog”, “rabbit”};

JCombo petList = new JComboBox(pets);

petList.setSelectedIndex(3);

contentPane().add(petList);

petList.addItemListener(this);

• Sample Item ListenerJComboBox cb = (JComboBox) e.getSource();

String pet = (String) cb.getSelectedItem();

Scott Grissom, copyright 2004 Ch 12: Swing Slide 21

JOptionPanes

• Simple solution for common message boxes that requires little code

• Different styles are providedWARNING_MESSAGE

ERROR_MESSAGE

PLAIN_MESSAGE

• Sample CodeJOptionPane.showMessageDialog (frame, “my specific warning message”, “some

title”, JOptionPane.WARNING_MESSAGE);

JOptionPane.showMessageDialog (frame, “my specific error message”, “some title”, JOptionPane.ERROR_MESSAGE);

Scott Grissom, copyright 2004 Ch 12: Swing Slide 22

JFileChooser (not in book)

• Allows a user to select a file by navigating directories

• The selected filename including the full path are returned

• Programmer chooses between a Save or Open dialog

• Refer to the online documentation for several customized options including file filters

• Sample Codechooser = new JFileChooser( );

int choice = chooser.showOpenDialog(this);

if (choice == JFileChooser.APPROVE_OPTION){

File f = chooser.getSelectedFile( );

// do something with the file

}

Scott Grissom, copyright 2004 Ch 12: Swing Slide 23

Menus (12.4)

• Create pull down menus• They appear in the menu bar• Advanced Options

keyboard shortcuts

cascading menus

adding icons

• Sample code to create a menu// create the menu bar

menuBar = new JMenuBar();

// build a menu

fileMenu = new JMenu(“File”);

quitItem = new JMenuItem(“Quit”);

quitItem.addActionListener(this);

fileMenu.add(quitItem);

// add menu to the bar

menuBar.add(fileMenu);

Scott Grissom, copyright 2004 Ch 12: Swing Slide 24

More Menus

• Menu Items generate action events

• Sample Action Listenerif (e.getSource() == quitItem)

// do something

Scott Grissom, copyright 2004 Ch 12: Swing Slide 25

Class Play

• three GUI componentsGUI 1

GUI 2

GUI 3

• two event listenersclap

double clap

• four methods

• the user

Scott Grissom, copyright 2004 Ch 12: Swing Slide 26

Window Events

• Windows generate a number of events

• the most important for us is the close event

• Create a window adaptor to hide most of the methods

class myWindowHandler extends WindowAdapter{

public void windowClosing(WindowEvent e){

System.exit(0);}

}

• Register this listener from within the GUI constructor

addWindowListener (new myWindowHandler());

Scott Grissom, copyright 2004 Ch 12: Swing Slide 27

Model View Pattern

• Separate GUI front end from the application

• provides flexibility for future interface development

• Viewcreate frames and components

create instance of model

handle events

• Modelmanage data

respond to View requests

should not know anything about the View

• ResponsibilitiesTom and Mary have their own jobs and will be upset if

someone else does it

Scott Grissom, copyright 2004 Ch 12: Swing Slide 28

GUI Design

• Careful design of a graphical user interface is key to a viable software system

• To the user, the user interface is the system

• For each situation, consider which components are best suited and how they should best be arranged

• Group ActivityDesign a VCR display with TV screen, play, stop, ff,

rewind, volume control, channel controls