5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.

Slides:



Advertisements
Similar presentations
Algorithmic Programming II
Advertisements

Graphic User Interfaces Layout Managers Event Handling.
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
Event Driven Programming and GUIs Part 3 CS221 – 4/15/09.
Java GUI Libraries Swing Programming. Swing Components Swing is a collection of libraries that contains primitive widgets or controls used for designing.
Events ● Anything that happens in a GUI is an event. For example: – User clicks a button, presses return when typing text, or chooses a menu item ( ActionEvent.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
Scott Grissom, copyright 2006Ch 11: GUI Slide 1 Graphical User Interfaces (Ch 11) Careful design of a graphical user interface is key to a viable software.
GUI and Event-Driven Programming Part 2. Event Handling An action involving a GUI object, such as clicking a button, is called an event. The mechanism.
Java Programming Chapter 10 Graphical User Interfaces.
Chapter 9: Applets Jim Burns Fall Outline Learn about applets Learn about applets Write an HTML doc to host an applet Write an HTML doc to host.
Introduction to GUI Java offers a great number of pre-defined classes to support the development of graphical user interfaces –These are broken down into.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Java Programming: From Problem Analysis to Program Design, Second Edition1  Learn about basic GUI components.  Explore how the GUI components JFrame,
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
CSE 219 Computer Science III Graphical User Interface.
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
MIT AITI 2003 Lecture 17. Swing - Part II. The Java Event Model Up until now, we have focused on GUI's to present information (with one exception) Up.
GUI programming Graphical user interface-based programming.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
Java GUI building with Swing. 2 AWT (Abstract Window Toolkit) Present in all Java implementations Described in (almost) every Java textbook Adequate for.
Introduction to Swing Components Chapter 14.  Part of the Java Foundation Classes (JFC)  Provides a rich set of GUI components  Used to create a Java.
GUI Components and Design Here we add one more component to our programs, JButtons –JButtons can only be inserted into JPanels (or JApplets) –Clicking.
CS Lecture 01 Frames and Components and events Lynda Thomas
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
Ch 3-4: GUI Basics Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: GUI Components.
Timer class and inner classes. Processing timer events Timer is part of javax.swing helps manage activity over time Use it to set up a timer to generate.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Graphical User Interfaces (Part 2) 1. View  view  presents the user with a sensory (visual, audio, haptic) representation of the model state  a user.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
Java Programming Applets. Topics Write an HTML document to host an applet Understand simple applets Use Labels with simple AWT applets Write a simple.
Creating a GUI with JFC/Swing. What are the JFC and Swing? JFC –Java Foundation Classes –a group of features to help people build graphical user interfaces.
CS-1020 Dr. Mark L. Hornick 1 Event-Driven Programming.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Introduction to GUI in 1 Graphical User Interface 2 Nouf Almunyif.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
A simple swing example GETTING STARTED WITH WIND CHILL.
1 GUI programming Graphical user interface-based programming Chapter G1 (pages )
Graphical User Interfaces A Graphical User Interface (GUI) in Java is created with at least three kinds of objects: –components, events, and listeners.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
Chapter 14: Introduction to Swing Components. Objectives Understand Swing components Use the JFrame class Use the JLabel class Use a layout manager Extend.
Creating a GUI Class An example of class design using inheritance and interfaces.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Lesson 28: More on the GUI button, frame and actions.
Graphical User Interface (GUI)
View  view  presents the user with a sensory (visual, audio, haptic) representation of the model state  a user interface element (the user interface.
MIT AITI 2004 Swing Event Model Lecture 17. The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the.
1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
Java Programming Fifth Edition Chapter 13 Introduction to Swing Components.
Java Visual Applications CSIS 3701: Advanced Object Oriented Programming.
GUI.1 Graphical User Interfaces GUIs. GUI.2 The Plan Components Flat Layouts Hierarchical Layouts Designing a GUI Coding a GUI.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 7 Event-Driven Programming and Basic GUI Objects.
A Quick Java Swing Tutorial
GUIs and Events Rick Mercer.
Introduction Many Java application use a graphical user interface or GUI (pronounced “gooey”). A GUI is a graphical window or windows that provide interaction.
CSC 205 Programming II Lecture 5 AWT - I.
CompSci 230 S Programming Techniques
A First Look at GUI Applications
Graphical User Interface (pronounced "gooey")
A Quick Java Swing Tutorial
Ellen Walker Hiram College
A Quick Java Swing Tutorial
Presentation transcript:

5-1 GUIs and Events Rick Mercer

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

5-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

5-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

5-5 Get a window to show itself  Code to tell a JFrame to show itself: // Construct window with a title JFrame aWindow = new JFrame("Graffiti"); // Make sure the program terminates when window closes aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); aWindow.setVisible(true);

5-6 Some JFrame messages  Set the size of the window with aWindow.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

5-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 window object

5-8 Add components to a window  Add the previously constructed components to one of the five areas of a JFrame aWindow.add(clickMeButton, BorderLayout.NORTH); aWindow.add(aLabel, BorderLayout.CENTER); aWindow.add(textEditor, BorderLayout.SOUTH);

5-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 1 st  There are many layout managerslayout managers  We will use null for layout: — Must set the size and location of each component

5-10 Null layout manager easier to layout components  We will explicitly state where each component goes on a Container, which can be a JFrame or JPanel  Code Demo: Add these components to a GUI — JLabel, JButton, JTextField

5-11 So what happens next?  You can layout a real pretty GUI  You 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…

5-12 Java's Event Model  Java can let the operating system notify graphical components of user interaction — JButton objects notified when user clicks it — JTextField objects with focus knows when the user enters text and your program can respond — A menu item know that a user has selected it — Event driven programs respond to many things mouse clicks, mouse movements clicks on hyperlinks, buttons, menu items Users pressing any key, selecting a list item, moving a slider bar, …

5-13 Example: Action Events  The buttons, text fields, and menu items do not perform the actions — Instead JButton, JTextField, JMenuItem objects send actionPerformed messages to other objects, for example  We write code to respond to the above events in actionPerformed methods — This requires a class that implements the ActionListener interface, for example

5-14 Event Driven Program 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, …

5-15 Java's Event Model JFrame JButton 1 Layout Graphical Components JFrame JButton JTextField JMenuItem Listener 3 You register objects that waits for messages from graphical components addActionListener Listener 4 Users interact with these graphical components 2 You write classes that implement the correct interface ActionListener

5-16 A Java GUI: Rick's model  Preview for writing a GUI with events 1. Have a class that extends JFrame so your class IS-A JFrame. so you inherit many methods already working! 2. Add main to start up the GUI (could be separate file) 3. Add instance variables – include graphical components that will be needed by two or more methods (a JTextField, Timer, or JList will be needed by listeners later 4. Lay out a GUI and initialize instance variables in the constructor

5-17 The first 4 steps import java.awt.*; import javax.swing.*; public class SomeEvents extends JFrame { public static void main(String[] args) { public static void main(String[] args) { // Construct an instance of this class and show it // Construct an instance of this class and show it SomeEvents window = new SomeEvents(); SomeEvents window = new SomeEvents(); window.setVisible(true); window.setVisible(true); } // A graphical component to be "listened" to // A graphical component to be "listened" to private JButton aButton; private JButton aButton; public SomeEvents() { public SomeEvents() { layoutGUI(); layoutGUI(); } private void layoutGUI(); private void layoutGUI(); // Lay out the GUI, initialize instance variables // Lay out the GUI, initialize instance variables // Have this object send some messages to itself // Have this object send some messages to itself this.setSize(200, 100); this.setSize(200, 100); this.setTitle("Listen to button"); this.setTitle("Listen to button");

5-18 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 method addActionListener(ActionListener al)

5-19 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: ActionListener 6. 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)

5-20 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 But there is no ActionListener class! What can we do?????

5-21 Implement an interface Then 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

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

5-23 Have a class that implements ActionListener // 5. inner class to listen to events // 5. inner class to listen to events private class ButtonListener implements ActionListener { private class ButtonListener implements ActionListener { // No constructor needed here // No constructor needed here // Must have this method to implement ActionListener // Must have this method to implement ActionListener public void actionPerformed(ActionEvent anActionEvent){ public void actionPerformed(ActionEvent anActionEvent){ System.out.println("Button was clicked."); System.out.println("Button was clicked."); } // 6. Register the instance of the listener so the // 6. Register the instance of the listener so the // component can later send messages to that object // component can later send messages to that object ButtonListener aListener = new ButtonListener(); ButtonListener aListener = new ButtonListener(); aButton.addActionListener(aListener); aButton.addActionListener(aListener); Caution: this is easy to forget. It is an error no one will tell you about

5-24 Polymorphism through 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 the specified action listener to receive action events from JButtons, TextFields,... Parameter: aL - an instance of a class that implements the ActionListener interface

5-25 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

5-26 Listen to JTextField  Add to the current GUI — Add a JTextField so when the user enters a String, show it in Upper case Need JTextArea methods getText and setText

5-27 JList  Code demo: — Show a JList GUI component with a ListModel set as the model  List to clicks on the elements in the JList  Begin with code on the next slide

5-28 public class ShowJListListModel extends JFrame { public static void main(String[] args) { JFrame window = new ShowJListListModel(); window.setVisible(true); } private JList guiList; private ListModel allStrings; public ShowJListListModel() { setSize(380, 200); setLocation(100, 100); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // List must implement ListModel so it can be shown in a JList allStrings = new MyLittleList(); guiList = new JList(allStrings); guiList.setFont(new Font("Arial", Font.BOLD, 13)); this.getContentPane().add(guiList, BorderLayout.CENTER); }

5-29 Demo javax.swing.Timer  Count down to 10  A timer is constructed and begun like this timer = new Timer(1000, new TimerListener()); timer.start();  Timers need an ActionListener argument private class TimerListener implements ActionListener { public void actionPerformed(ActionEvent ae) { // Do whatever is here when the timer sends // this listener an actionPerformed message }