Event Driven Programs with a Graphical User Interface


























![public class Show. JList. Model extends JFrame { public static void main(String[] args) { public class Show. JList. Model extends JFrame { public static void main(String[] args) {](https://slidetodoc.com/presentation_image_h2/7165400b95ce518f15869c4831c6ac85/image-27.jpg)
- Slides: 27

Event Driven Programs with a Graphical User Interface Rick Mercer 1

Event-Driven Programming with Graphical user Interfaces w Most applications have graphical user interfaces to respond to user desires 2

A Few Graphical Components w A Graphical User Interface (GUI) presents a graphical view of an application to users. w 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, . . . w Let's first consider some of Java's GUI components: — windows, buttons, and text fields 3

Classes in the swing package w 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 JText. Field: Allows editing of a single line of text 4

Get a window to show itself import javax. swing. JFrame; public class First. GUI extends JFrame { public static void main(String[] args) { // Construct an object that has all the methods of JFrame a. Window = new First. GUI(); a. Window. set. Visible(true); } // Set up the GUI public First. GUI() { // Make sure the program terminates when window closes this. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); // Set the title of this instance of First. GUI this. set. Title("Graffiti"); // … more to come … } } 5

Some JFrame messages w Set the size of the window with // this not necessary if message is in // a First. GUI method like this constructor set. Size(220, 100); — — The first int is the width of the window in pixels the second int is the height of the window in pixels 6

Building components w So far we have an empty window w Let us add a button, a label, and an editable line w First construct three graphical components JButton click. Me. Button = new JButton("Nobody is listening to me"); JLabel a. Label = new JLabel("Button above, text field below"); JText. Field text. Editor = new JText. Field("You can edit this text "); w Next, add these objects to a JFrame 7

Add components to a window w Could use the default Border. Layout and add components to one of the five areas of a JFrame add(click. Me. Button, Border. Layout. NORTH); add(a. Label, Border. Layout. CENTER); add(text. Editor, Border. Layout. SOUTH); 8

The 5 areas of Border. Layout w By default, JFrame objects have only five places where you can add components — a 2 nd add wipes out the 1 st w There are many layout managers w We will use null for layout: — Must set the size and location of each component 9

Null layout manager easier to layout components w Explicitly state where each component goes // Add three graphical components using a null layout set. Layout(null); // Controversial. . . click. Me. Button. set. Size(200, 25); click. Me. Button. set. Location(0, 0); add(click. Me. Button); // Add a label not needed by other methods in this class JLabel a. Label=new JLabel("Button above, text field below"); a. Label. set. Size(200, 25); a. Label. set. Location(0, 25); add(a. Label); text. Editor. set. Size(200, 25); text. Editor. set. Location(0, 50); add(text. Editor); 10

So what happens next? w You can layout a real pretty GUI w You can click on buttons, enter text into a text field, move the mouse, press a key — And NOTHING happens w So let’s make something happen… 11

Java's Event Model w Java lets the operating system notify graphical components of user interaction JButton objects know when a user clicks it — JText. Field 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, … 12

Example: Action Events w The buttons and text fields do not execute code — Instead JButton and JText. Field objects send action. Performed messages to other objects that have been registered to “listen” w We write the code we want to execute in action. Performed methods This requires a class that implements an interface, for example — Registering an instance of that class to listen — 13

Event Driven Programs with GUIs w 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 JMenu. Item JText. Field JText. Area JList. . . — Layout managers • Govern how the components appear on the screen • Examples Flow. Layout Grid. Layout null layout — Events • Signal that a user interacted with the GUI • Examples: mouse clicks, keys pressed, hyperlink selected, time expires on a timer, … 14

Java's Event Model 1 Layout Graphical Components JFrame JButton JText. Field JMenu. Item 4 Users interact with these graphical components 3 You register objects that waits for messages from graphical components add. Action. Listener 2 You write classes that implement the correct interface Action. Listener 15

A Java GUI: Rick's model w We’ve begin by setting up the GUI 1. First. GUI extends JFrame It IS-A JFrame so we inherit many methods 2. 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 JText. Field, JButton, or JList will be needed by listeners later 4. Lay out a GUI and initialize instance variables in the constructor 16

But no one is "Listening" w Okay, now we have a GUI — but when run, nothing happens w Wanted: An object to listen to the button that understands a specific message such as — action. Performed w Also need to tell the button who it can send the action. Perfomed message to Register the listener with this method add. Action. Listener(Action. Listener al) — 17

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: Action. Listener 6. Register the listener object to the GUI component (JButton JText. Field) so it can later send action. Performed 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) 18

Action. Event / Action. Listener w When a JButton object is clicked, it constructs an Action. Event object and sends it to the action. Performed method of its listeners We can usually ignore that parameter, other times we can't w To register a listener to a JButton, send an add. Action. Listener message to button — public void add. Action. Listener(Action. Listener al) — You need an Action. Listener object • There is no Action. Listener class! • What can we do? ? ? 19

Implement an interface Then your object can be treated as if it were an Action. Listener Polymorphism in action: We can have any number of action. Performed methods that do whatever they are supposed to. The Button does not care what happened 20

Inner class w Add an inner class — inner classes have access to the enclosing classes' instance variables w Make it private since no one else needs to know about it w Java added inner classes for the very purpose: to have listener objects respond to user interactions with GUI components 21

And register the listener with add. Action. Listener // 6. Register the instance of the listener so the // component can later send messages to that object Button. Listener a. Listener = new Button. Listener(); click. Me. Button. add. Action. Listener(a. Listener); } // End constructor Caution: this is easy to forget. It is an error no one will tell you about // 5. inner class to listen to events private class Button. Listener implements Action. Listener { // No constructor needed here. // Must have this method to implement Action. Listener public void action. Performed(Action. Event an. Action. Event) { System. out. println("Button was clicked. "); } } 22

Another benefit of interfaces w Can have many Action. Listener objects Any class that implements Action. Listener — may need a different class for every button and text field in the GUI — • But they all can be treated as Action. Listener objects • They can be passed as arguments to this method public void add. Action. Listener(Action. Listener a. L) Adds an action listener to receive action events from JButtons, Text. Fields, . . . a. L - an instance of a class that implements the Action. Listener interface 23

Assignment Compatible w Can pass instances of classes implementing an interface to the interface type parameter add. Action. Listener(Action. Listener any. Listener) add. Action. Listener(new Button. Listener()); add. Action. Listener(new Text. Field. Listener()); w Button. Listener and Text. Field. Listener must implement interface Action. Listener 24

Listen to JText. Field w Add to the current GUI — Have the button click toggle the JText. Field form upper to lower case • Need methods get. Text and set. Text 25

JList and Default. List. Model w Code demo: — Show a JList GUI component with a Default. List. Model set as the model • will contain a list of strings w Respond to selections by showing the selected string in a dialog box 26
![public class Show JList Model extends JFrame public static void mainString args public class Show. JList. Model extends JFrame { public static void main(String[] args) {](https://slidetodoc.com/presentation_image_h2/7165400b95ce518f15869c4831c6ac85/image-27.jpg)
public class Show. JList. Model extends JFrame { public static void main(String[] args) { JFrame window = new Show. JList. Model(); window. set. Visible(true); } private JList gui. List; private Default. List. Model all. Strings; public Show. JList. Model() { set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); set. Size(250, 300); set. Location(100, 100); set. Layout(null); initialize. All. Strings(); gui. List = new JList(all. Strings); gui. List. set. Selected. Index(all. Strings. get. Size() - 1); gui. List. set. Size(150, 250); gui. List. set. Location(20, 10); gui. List. set. Font(new Font("Arial", Font. BOLD + Font. ITALIC, 14)); add(gui. List); register. Listeners(); } private void register. Listeners() { List. Selection. Listener listener = new Gui. Listener(); gui. List. add. List. Selection. Listener(listener); } private class Gui. Listener implements List. Selection. Listener { public void value. Changed(List. Selection. Event arg 0) { String str = all. Strings. get(gui. List. get. Selected. Index()). to. String(); System. out. println(str + " selected"); } } private void initialize. All. Strings() { all. Strings = new Default. List. Model(); all. Strings. add. Element("Riley"); all. Strings. add. Element("Dakota"); all. Strings. add. Element("Casey"); all. Strings. add. Element("Angel"); all. Strings. add. Element("Reese"); 27