EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing.

Slides:



Advertisements
Similar presentations
Event handling and listeners What is an event? user actions and context event sources and listeners Why should my programs be event- driven? User interaction.
Advertisements

1 Event Listeners Some Events and Their Associated Event Listeners Act that Results in the EventListener Type User clicks a button, presses Enter while.
Introduction to Java 2 Programming
CS18000: Problem Solving and Object-Oriented Programming.
Graphic User Interfaces Layout Managers Event Handling.
TCU CoSc Programming with Java Handling Events.
Managing Input Events in Swing Week 5 Workshop Lyn Bartram.
Event Handling Events and Listeners Timers and Animation.
Graphical User Interfaces (GUIs) GUI: An application that uses graphical objects to interact with users GUI applications consist of: –Events: A user or.
Unit 12 Object-oriented programming: Event-driven programming for GUI Jin Sa.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 14 GUI and Event-Driven Programming.
1 GUI Elements in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
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.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
GUI Programming in Java
Java Software Solutions Lewis and Loftus Chapter 10 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Graphical User Interfaces --
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 13 Creating User.
Introduction to GUI in Java 1. Graphical User Interface Java is equipped with many powerful,easy to use GUI component such as input and output dialog.
Java GUI CSCE 190 – Java Instructor: Joel Gompert Mon, July 26, 2004.
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.
Java GUI’s are event driven, meaning they generate events when the user interacts with the program. Typical events are moving the mouse, clicking a mouse.
Graphical User Interface Components: Part 1 Chapter 11.
 2002 Prentice Hall, Inc. All rights reserved Introduction Graphical User Interface (GUI) –Gives program distinctive “look” and “feel” –Provides.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
Layout Managers Arranges and lays out the GUI components on a container.
Java Applets: GUI Components, Events, Etc. Ralph Westfall June, 2010.
GUI Programming using NetBeans. RHS – SOC 2 GUI construction We have previously talked about elements in a (simple) GUI –Frames, Panes and Dialogs –Text.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
CS324e - Elements of Graphics and Visualization Java GUIs - Event Handling.
Lec.10 (Chapter 8 & 9) GUI Jiang (Jen) ZHENG June 27 th, 2005.
UID – Event Handling and Listeners Boriana Koleva
Event Handling. 2 GUIs are event driven –Generate events when user interacts with GUI e.g., moving mouse, pressing button, typing in text field, etc.
Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action.
CS-1020 Dr. Mark L. Hornick 1 Event-Driven Programming.
Object Oriented Programming.  Interface  Event Handling.
EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing.
Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets.
GUI DYNAMICS Lecture 11 CS2110 – Fall GUI Statics and GUI Dynamics  Statics: what’s drawn on the screen  Components buttons, labels, lists, sliders,
Java layout managers. import java.awt.*; import java.awt.event.*; import javax.swing.*; class ButtonPanel extends JPanel implements ActionListener { public.
Creating a Window. A basic window in Java is represented by an object of the class Window in the package java.awt.
Computer Science [3] Java Programming II - Laboratory Course Lab 4 -1 : Introduction to Graphical user interface GUI Components Faculty of Engineering.
1 Event Handling – Lecture 4 Prepared by: Ahmad Ramin Rahimee Assistant Professor ICTI.
What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event.
Mouse Events GUI. Types of Events  Below, are some of the many kinds of events, swing components generate. Act causing EventListener Type User clicks.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
1 Lecture 8: User Interface Components with Swing.
View  view  presents the user with a sensory (visual, audio, haptic) representation of the model state  a user interface element (the user interface.
CIS 270—Application Development II Chapter 11—GUI Components: Part I.
Java Programming Fifth Edition Chapter 13 Introduction to Swing Components.
Dept. of CSIE, National University of Tainan 10/21/2012 Responding to User Input.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
Chapter 9: Graphical User Interfaces
Lecture 8 Object Oriented Programming Using Java
A First Look at GUI Applications
Advanced User Interfaces
Java GUI.
GUI Programming III: Events
Chap 7. Building Java Graphical User Interfaces
Graphical User Interfaces -- Introduction
Event-driven programming for GUI
Web Design & Development Lecture 12
Chapter 7-3 (Book Chapter 14)
Graphical User Interface
Presentation transcript:

EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

Contents Introduction Introduction Java’s event delegation model – event sources and event listeners Java’s event delegation model – event sources and event listeners Event classes Event classes Example – a mouse tracker Example – a mouse tracker Building GUI’s Building GUI’s Layout within a GUI – layout managers Layout within a GUI – layout managers Example Example And finally……..how do we build our own GUI’s? And finally……..how do we build our own GUI’s?

Introduction Most modern applications come with a sophisticated user interface comprising Most modern applications come with a sophisticated user interface comprising  Push buttons  Selection boxes  Dialog boxes  Pull down menus  etc GUI’s gives an application a distinctive “look” and “feel” GUI’s gives an application a distinctive “look” and “feel”  Provides users with basic level of familiarity  Built from GUI components (controls, widgets, etc.)  User interacts with GUI component via mouse, keyboard, etc

Introduction Scroll bar Textbox Menu itemCombo box Button Label Frame Menu bar

Java’s event delegation model – event sources and event listeners Interacting with a user interface component generates an event which must be handled by the application program Interacting with a user interface component generates an event which must be handled by the application program Therefore, in order to be able to create our own user interfaces, we must understand the Java event model Therefore, in order to be able to create our own user interfaces, we must understand the Java event model Java allows objects to be designated event listeners which can listen for specific types of events (for example a mouse button click) Java allows objects to be designated event listeners which can listen for specific types of events (for example a mouse button click)  Event listeners are registered with the particular event sources whose events they handle  One object can be a listener for several sources

Mouse button Push button clickListener object 1 Listener object 2 click push Listener object 3 push Event source

In terms of Java objects and methods, event handling works as follows : In terms of Java objects and methods, event handling works as follows :  An event source registers all listener objects  The event source sends out event objects to all registered listener objects  Each listener object uses information encapsulated in the event object to call the appropriate listener method

8 Three Parts of a GUI Application 1. Components that make up the Graphical User Interface 2. Listeners that receive the events and respond to them 3. Application code that does useful work for the user

The following example shows a simple user interface to select the background colour The following example shows a simple user interface to select the background colour  This has been implemented as an applet so that it can be run with a web browser  The normal JFrame class has been replaced with a JApplet class  Other small changes required  uff/ButtonTestApplet/ButtonTestApplet.html uff/ButtonTestApplet/ButtonTestApplet.html uff/ButtonTestApplet/ButtonTestApplet.html  Class ButtonPanel is the panel containing the push buttons and the event handling (key parts emboldened)

class ButtonPanel extends JPanel implements ActionListener { public ButtonPanel() { // Create buttons and add listeners } public void actionPerformed(ActionEvent evt) { // Handle button press events } private JButton yellowButton; private JButton blueButton; private JButton redButton; }

public ButtonPanel() { yellowButton = new JButton("Yellow"); blueButton = new JButton("Blue"); redButton = new JButton("Red"); add(yellowButton); add(blueButton); add(redButton); yellowButton.addActionListener(this); blueButton.addActionListener(this); redButton.addActionListener(this); }

public void actionPerformed(ActionEvent evt) { Object source = evt.getSource(); Color color = getBackground(); if (source == yellowButton) color = Color.yellow; else if (source == blueButton) color = Color.blue; else if (source == redButton) color = Color.red; setBackground(color); repaint(); }

Blue Red Yellow yellowButton.addActionListener(this) ButtonPanel

Event classes Event classes are arranged in an inheritance tree with the base class being EventObject Event classes are arranged in an inheritance tree with the base class being EventObject Event classes are in the package java.awt.event Event classes are in the package java.awt.event Event objects encapsulate information about the event such as the event source Event objects encapsulate information about the event such as the event source Each event class has a corresponding event listener class Each event class has a corresponding event listener class

We have already seen two examples of events and corresponding listeners We have already seen two examples of events and corresponding listeners  ActionEvent with listener ActionListener generated by (amongst other things) a button press  WindowEvent with listener WindowListener generated when a user tries to close a window Events are also generated by keyboard presses and mouse drags and clicks which are handled by appropriate listeners Events are also generated by keyboard presses and mouse drags and clicks which are handled by appropriate listeners Some events (such as a PaintEvent) are generated automatically when a window is moved/resized so that it is repainted Some events (such as a PaintEvent) are generated automatically when a window is moved/resized so that it is repainted

16 Events Generated by Swing Components Act that results in the eventListener type User clicks a button, presses Return while typing in a text field, or chooses a menu item ActionListener User closes a frame (main window) WindowListener User presses a mouse button while the cursor is over a component MouseListener User moves the mouse over a component MouseMotionListener Component becomes visible ComponentListener Component gets the keyboard focus FocusListener Table or list selection changes ListSelectionListener

Example – a mouse tracker A mouse tracker program keeps track of the motion of the mouse and mouse clicks A mouse tracker program keeps track of the motion of the mouse and mouse clicks Uses event listeners Uses event listeners  MouseListener  Listens for mouse button clicks  MouseMotionListener  Listens for mouse moves and drags We need to implement the following methods in the listener interfaces We need to implement the following methods in the listener interfaces

MouseListener interface MouseListener interface  Methods :  mousePressed  mouseReleased  mouseEntered  mouseExited  mouseClicked MouseMotionListener MouseMotionListener  Methods :  mouseDragged  mouseMoved

0Stuff/MouseTrackerApplet/MouseTracker Applet.html 0Stuff/MouseTrackerApplet/MouseTracker Applet.html 0Stuff/MouseTrackerApplet/MouseTracker Applet.html 0Stuff/MouseTrackerApplet/MouseTracker Applet.html

The program has been implemented as an applet The program has been implemented as an applet The implementation of the event handlers is straighforward The implementation of the event handlers is straighforward  Uses event.getX() and event.getY() to determine the mouse position  mouseEntered()puts up a dialogbox so that the user can select when ready to track  mouseEntered() puts up a dialog box so that the user can select when ready to track

public class MouseTrackerApplet extends JApplet implements MouseListener, MouseMotionListener { public MouseTrackerApplet() { getContentPane().add(new Jlabel(), BorderLayout.SOUTH); addMouseListener(this); addMouseMotionListener(this); } public void mouseClicked(MouseEvent event) {..} public void mousePressed(MouseEvent event) {..} public void mouseReleased(MouseEvent event) {..} public void mouseEntered(MouseEvent event) {..} public void mouseExited(MouseEvent event) {..} public void mouseDragged(MouseEvent event) {..} public void mouseMoved(MouseEvent event) {..}. }

public void mouseClicked(MouseEvent event) { statusBar.setText("Clicked at [" + event.getX() + ", " + event.getY() + "]"); } public void mouseEntered(MouseEvent event) { if (!entered) { JOptionPane.showMessageDialog(null,"Mouse in window"); entered=true; }

Building GUI’s Swing has a large number of classes for GUI components Swing has a large number of classes for GUI components  Text input  JTextField  Labels  JLabel  Buttons  JButton  Check boxes (for choosing options)  JCheckBox

 Radio buttons (for choosing 1 from several options)  JRadioButton  Lists  JList  Drop down boxes (combo boxes)  JComboBox  Scroll bars  JScrollBar

 Menus ( a bit more involved)  JMenuBar, JMenu, JMenuItem  Diaog boxes (quite a bit more involved!)  JOptionPane  File chooser dialog box (very useful!)  JFileChooser

26 Dialog Boxes Used by applications to interact with the user Used by applications to interact with the user Provided by Java’s JOptionPane class Provided by Java’s JOptionPane class  Contains input dialogs and message dialogs

27 Dialog Boxes Note icon Note icon Other icons available Other icons available

You can see all of these components in action (plus a few more) at You can see all of these components in action (plus a few more) at  uff/SwingSetApplet/SwingSetApplet.html uff/SwingSetApplet/SwingSetApplet.html uff/SwingSetApplet/SwingSetApplet.html Before we start building simple GUI’s, it is important to know about layout management (how GUI components are spatially arranged) Before we start building simple GUI’s, it is important to know about layout management (how GUI components are spatially arranged)

Layout within a GUI – layout managers Layout managers control how GUI components are spatially arranged within a container Layout managers control how GUI components are spatially arranged within a container Its important to understand the basics of layout even though many development environments come with ‘pick and place’ type layout tools Its important to understand the basics of layout even though many development environments come with ‘pick and place’ type layout tools

Flow layout We have seen how we created a simple GUI by adding buttons to a panel We have seen how we created a simple GUI by adding buttons to a panel The default layout manager for panels is a flow layout manager The default layout manager for panels is a flow layout manager  Components (such as buttons) are arranged left to right – top to bottom  When the panel is re-sized, the buttons are ‘re- flowed’ to fill the space  More buttons are added to the right of the existing row and a new row of buttons is started if there is no more space for the current row

Border layout This is the default layout manager for the JFrame class This is the default layout manager for the JFrame class Partitions the available space Partitions the available space Unless we specify, components are added to the centre partition Unless we specify, components are added to the centre partition Normal to add buttons etc. to panels in flow layout and then add the panels to the outer frame Normal to add buttons etc. to panels in flow layout and then add the panels to the outer frame

More sophisticated layout managers We can specify more precise positioning of GUI components We can specify more precise positioning of GUI components  Grid layout  Components arranged in rows and columns (for example, calculator buttons)  Grid Bag layout  Flexible grid layout where rows columns can have variable sizes  Box layout  Layout comprises a single row (column) for a horizontal (vertical) box

Here are several common Java layout managers: Here are several common Java layout managers: Layout managers

35 Complex layouts How would you create a complex window like this, using the layout managers shown? How would you create a complex window like this, using the layout managers shown?

create panels within panels create panels within panels each panel has a different layout, and by combining the layouts, more complex / powerful layout can be achieved each panel has a different layout, and by combining the layouts, more complex / powerful layout can be achieved example: example:  how many panels?  what layout in each? Solution: composite layout

Example A GUI to select the font size and style of a label string A GUI to select the font size and style of a label string Uses a check box to select bold/italic Uses a check box to select bold/italic Uses a combo box to select font size Uses a combo box to select font size 0Stuff/FontChangeApplet/FontChangeAppl et.html 0Stuff/FontChangeApplet/FontChangeAppl et.html 0Stuff/FontChangeApplet/FontChangeAppl et.html 0Stuff/FontChangeApplet/FontChangeAppl et.html

The following code adds the check box and combo box to a panel The following code adds the check box and combo box to a panel JPanel p = new JPanel(); JCheckBox bold = new JCheckBox("Bold"); bold.addActionListener(this); p.add(bold); JCheckBox italic= new JCheckBox(“Italic"); italic.addActionListener(this); p.add(italic); JComboBox fontsize = new JComboBox(); fontsize.setEditable(true); fontsize.addItem("10"); fontsize.addItem("16"); fontsize.addItem("20"); fontsize.addActionListener(this); p.add(fontsize);

A second FontChangePanel contains the string A second FontChangePanel contains the string  Every time the font is changed, repaint() is called to repaint the string in the panel The two panels are added to the centre and south portion of the frame The two panels are added to the centre and south portion of the frame getContentPane().add(p, "South"); panel = new FontChangePanel(); getContentPane().add(panel, "Center"); I want to be … Bold Italic 10

The following is the code for the actionPerformed() method of the outer JFrame (or JApplet) class The following is the code for the actionPerformed() method of the outer JFrame (or JApplet) class JComboBox.getSelectedItem() returns the item selected (it is of type Object so has to be cast to a string) JComboBox.getSelectedItem() returns the item selected (it is of type Object so has to be cast to a string) JCheckBox.isSelected() returns the state of the checkbox (true for selected, false otherwise) JCheckBox.isSelected() returns the state of the checkbox (true for selected, false otherwise) font and size are fields of the outer JFrame (or JApplet) which hold the current font and fontsize of the string font and size are fields of the outer JFrame (or JApplet) which hold the current font and fontsize of the string

public void actionPerformed(ActionEvent evt) { Object source=evt.getSource(); if (source==fontsize) { String fsize=(String) (JComboBox)source).getSelectedItem(); size=Integer.valueOf(fsize).intValue(); panel.setFont(font, size); } else { font=(bold.isSelected() ? Font.BOLD : 0) + (italic.isSelected() ? Font.ITALIC : 0); panel.setFont(font,size); }

And finally……..how do we build our own GUI’s? There has been a lot of detail in this lecture There has been a lot of detail in this lecture There are dozens of GUI component classes and hundreds of methods which we can’t possibly hope to memorise There are dozens of GUI component classes and hundreds of methods which we can’t possibly hope to memorise How do we build our own GUI’s? How do we build our own GUI’s?  ‘Drag and drop’ GUI builders are becoming commonplace  ‘Visual’ programming  The programmer simply adds the event handlers

The swing component set web page is a useful ‘online’ help for finding out about GUI classes and methods The swing component set web page is a useful ‘online’ help for finding out about GUI classes and methods  Swing tutorial Swing tutorial Swing tutorial