1 Event Driven Programs with a Graphical User Interface Rick Mercer.

27
1 Event Driven Programs with a Graphical User Interface Rick Mercer

description

3 A Few Graphical Components  A Graphical User Interface (GUI) presents a graphical view of an application to users.  To build a GUI application, you must: — Have a well-tested model that is independent of the view — Make graphical components visible to the user — Ensure the correct things happen for each event user clicks button, moves mouse, presses enter key,...  Let's first consider some of Java's GUI components: — windows, buttons, and text fields

Transcript of 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

Page 1: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

1

Event Driven Programs with a Graphical User Interface

Rick Mercer

Page 2: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

2

Event-Driven Programming with Graphical user Interfaces

Most applications have graphical user interfaces to respond to user desires

Page 3: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

3

A Few Graphical Components

A Graphical User Interface (GUI) presents a graphical view of an application to users.

To build a GUI application, you must:— Have a well-tested model that is independent of the view— Make graphical components visible to the user— Ensure the correct things happen for each event

• user clicks button, moves mouse, presses enter key, ...

Let's first consider some of Java's GUI components: — windows, buttons, and text fields

Page 4: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

4

Classes in the swing package

The javax.swing package has components that show in a graphical manner JFrame: window with title, border, menu, buttons JButton: A component that can "clicked" JLabel: A display area for a small amount of text JTextField: Allows editing of a single line of text

Page 5: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

5

Get a window to show itselfimport javax.swing.JFrame;

public class FirstGUI extends JFrame {

public static void main(String[] args) { // Construct an object that has all the methods of JFrame JFrame aWindow = new FirstGUI(); aWindow.setVisible(true); }

// Set up the GUI public FirstGUI() { // Make sure the program terminates when window closes this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Set the title of this instance of FirstGUI this.setTitle("Graffiti"); // … more to come … }}

Page 6: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

6

Some JFrame messages

Set the size of the window with // this not necessary if message is in // a FirstGUI method like this constructor setSize(220, 100);

— The first int is the width of the window in pixels— the second int is the height of the window in pixels

Page 7: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

7

Building components

So far we have an empty window Let us add a button, a label, and an editable line First construct three graphical components JButton clickMeButton = new JButton("Nobody is listening to me");

JLabel aLabel = new JLabel("Button above, text field below");

JTextField textEditor = new JTextField("You can edit this text "); Next, add these objects to a JFrame

Page 8: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

8

Add components to a window

Could use the default BorderLayout and add components to one of the five areas of a JFrame

add(clickMeButton, BorderLayout.NORTH); add(aLabel, BorderLayout.CENTER); add(textEditor, BorderLayout.SOUTH);

Page 9: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

9

The 5 areas of BorderLayout

By default, JFrame objects have only five places where you can add components — a 2nd add wipes out the 1st

There are many layout managersWe will use null for layout:

— Must set the size and location of each component

Page 10: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

10

Null layout manager easier to layout components

Explicitly state where each component goes// Add three graphical components using a null layoutsetLayout(null); // Controversial ... clickMeButton.setSize(200, 25);clickMeButton.setLocation(0, 0);add(clickMeButton); // Add a label not needed by other methods in this classJLabel aLabel=new JLabel("Button above, text field below");aLabel.setSize(200, 25);aLabel.setLocation(0, 25);add(aLabel); textEditor.setSize(200, 25);textEditor.setLocation(0, 50);add(textEditor);

Page 11: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

11

So what happens next?

You can layout a real pretty GUIYou can click on buttons, enter text into a

text field, move the mouse, press a key— And NOTHING happens

So let’s make something happen…

Page 12: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

12

Java's Event Model

Java lets the operating system notify graphical components of user interaction— JButton objects know when a user clicks it— JTextField objects with focus know when the

user presses the enter (return) key— Event driven programs respond to many things

• mouse clicks, mouse movements• clicks on hyperlinks or menu items• Users pressing any key, selecting a list item, moving

a slider bar, checking a radio button, …

Page 13: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

13

Example: Action Events

The buttons and text fields do not execute code — Instead JButton and JTextField objects

send actionPerformed messages to other objects that have been registered to “listen”

We write the code we want to execute in actionPerformed methods— This requires a class that implements an

interface, for example— Registering an instance of that class to listen

Page 14: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

14

Event Driven Programs with GUIs

Key elements of an event-driven GUI— Graphical components

• The screen elements that a user manipulates with the mouse and keyboard JFrame JLabel JButton JScrollbar JMenuItem JTextField JTextArea JList ...

— Layout managers• Govern how the components appear on the screen• Examples FlowLayout GridLayout null layout

— Events• Signal that a user interacted with the GUI• Examples: mouse clicks, keys pressed, hyperlink selected,

time expires on a timer, …

Page 15: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

15

Java's Event Model

JFrame

JButton

1 Layout Graphical ComponentsJFrame JButton

JTextField JMenuItem

Listener

3 You register objects that waits for messages from graphical components addActionListener

ListenerListener

4 Users interact with these graphical components

2 You write classes that implement the correct interfaceActionListener

Page 16: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

16

A Java GUI: Rick's model

We’ve begin by setting up the GUI1. FirstGUI extends JFrame It IS-A JFrame so we

inherit many methods2. main starts up the GUI (could be separate file)3. Added instance variables – graphical components that

will be needed by two or more methods (a JTextField, JButton, or JList will be needed by listeners later

4. Lay out a GUI and initialize instance variables in the constructor

Page 17: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

17

But no one is "Listening"

Okay, now we have a GUI— but when run, nothing happens

Wanted: An object to listen to the button that understands a specific message such as— actionPerformed

Also need to tell the button who it can send the actionPerfomed message to— Register the listener with this methodaddActionListener(ActionListener al)

Page 18: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

18

Handling Events

5. Add a private inner class that can listen to the event that the graphical component will generate Your class must implement a listener interface to guarantee that

it has the expected methods: First up: ActionListener6. Register the listener object to the GUI component

(JButton JTextField) so it can later send actionPerformed messages to that listener when the use clicks the button or presses enter.events occur anytime in the future--the listener is listening

(waiting for user generated events such as clicking a button or entering text into a text field)

Page 19: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

19

ActionEvent / ActionListener

When a JButton object is clicked, it constructs an ActionEvent object and sends it to the actionPerformed method of its listeners— We can usually ignore that parameter, other times we can't

To register a listener to a JButton, send an addActionListener message to button

public void addActionListener(ActionListener al)—You need an ActionListener object

• There is no ActionListener class!• What can we do?????

Page 20: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

20

Implement an interfaceThen your object can be treated as if it were an ActionListener

Polymorphism in action: We can have any number of actionPerformed methods that do whatever they are supposed to. The Button does not care what happened

Page 21: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

21

Inner class

Add an inner class — inner classes have access to the enclosing

classes' instance variablesMake it private since no one else needs to

know about itJava added inner classes for the very

purpose: to have listener objects respond to user interactions with GUI components

Page 22: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

22

And register the listener withaddActionListener

// 6. Register the instance of the listener so the // component can later send messages to that object ButtonListener aListener = new ButtonListener(); clickMeButton.addActionListener(aListener); } // End constructor

// 5. inner class to listen to events private class ButtonListener implements ActionListener { // No constructor needed here. // Must have this method to implement ActionListener public void actionPerformed(ActionEvent anActionEvent) { System.out.println("Button was clicked."); } }

Caution: this is easy to forget. It is an error no one will tell you about

Page 23: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

23

Another benefit of interfaces

Can have many ActionListener objects— Any class that implements ActionListener— may need a different class for every button and

text field in the GUI• But they all can be treated as ActionListener objects• They can be passed as arguments to this method

public void addActionListener(ActionListener aL) Adds an action listener to receive action events from JButtons, TextFields, ... aL - an instance of a class that implements the ActionListener interface

Page 24: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

24

Assignment Compatible

Can pass instances of classes implementing an interface to the interface type parameter

addActionListener(ActionListener anyListener)

addActionListener(new ButtonListener());

addActionListener(new TextFieldListener()); ButtonListener and TextFieldListener

must implement interface ActionListener

Page 25: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

25

Listen to JTextField

Add to the current GUI — Have the button click toggle the JTextField

form upper to lower case• Need methods getText and setText

Page 26: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

26

JList and DefaultListModel

Code demo:— Show a JList GUI component with a

DefaultListModel set as the model • will contain a list of strings

Respond to selections by showing the selected string in a dialog box

Page 27: 1 Event Driven Programs with a Graphical User Interface Rick Mercer.

27

public class ShowJListListModel extends JFrame { public static void main(String[] args) { JFrame window = new ShowJListListModel(); window.setVisible(true); }

private JList guiList;

private DefaultListModel allStrings;

public ShowJListListModel() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(250, 300); setLocation(100, 100); setLayout(null);

initializeAllStrings(); guiList = new JList(allStrings); guiList.setSelectedIndex(allStrings.getSize() - 1); guiList.setSize(150, 250); guiList.setLocation(20, 10); guiList.setFont(new Font("Arial", Font.BOLD + Font.ITALIC, 14)); add(guiList);

registerListeners(); }

private void registerListeners() { ListSelectionListener listener = new GuiListListListener(); guiList.addListSelectionListener(listener); }

private class GuiListListListener implements ListSelectionListener { public void valueChanged(ListSelectionEvent arg0) { String str = allStrings.get(guiList.getSelectedIndex()).toString(); System.out.println(str + " selected"); } }

private void initializeAllStrings() { allStrings = new DefaultListModel(); allStrings.addElement("Riley"); allStrings.addElement("Dakota"); allStrings.addElement("Casey"); allStrings.addElement("Angel"); allStrings.addElement("Reese");

}