CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display.

Slides:



Advertisements
Similar presentations
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
Advertisements

Event-Driven Programming Thus far, our programs have been executed one statement after the other However, many programs depend on user actions to dictate.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Nine: Interfaces and Polymorphism.
Carnegie Mellon University, MISM1 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann Thread.
Object Oriented Programming Java 1 GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann GUI Programming.
Intermediate Java1 An example that uses inner classes Week Four Continued.
Graphical User Interfaces
EVENTS CSC 171 FALL 2004 LECTURE 16. “Traditional” Input In console applications, user input is under control of the program The program asks the user.
1 Class 8. 2 Chapter Objectives Use Swing components to build the GUI for a Swing program Implement an ActionListener to handle events Add interface components.
Chapter 6: Graphical User Interface (GUI) and Object-Oriented Design (OOD) J ava P rogramming: Program Design Including Data Structures Program Design.
Lesson 35: Review of the Java GUI. The JFrame, Container and JButton.
GUIs Mimi Opkins CECS277.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Layout Management Containers can arrange their components. Our container is a JPanel, and it can set the way it’s components will be laid out : mypanel.setLayout.
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.
Java GUI CSCE 190 – Java Instructor: Joel Gompert Mon, July 26, 2004.
Chapter 12 Event Handling. Chapter Goals To understand the Java event model To install action and mouse event listeners To accept input from buttons,
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.
CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
Previous programs used a JLabel for OUTPUT. Another Swing component that can be used for both user input and output is the JTextfield. Suppose we want.
Fall 2006Adapded from Java Concepts Companion Slides1 Event Handling Advanced Programming ICOM 4015 Lecture 13 Reading: Java Concepts Chapter 12.
Copyright © 2013 by John Wiley & Sons. All rights reserved. GRAPHICAL USER INTERFACES CHAPTER Slides by Donald W. Smith TechNeTrain.com Final Draft 10/30/11.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Nine and Ten Graphics.
Java Programming Week 4: Inheritance (Chapter 10).
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.
Swing GUI Components You can create graphics components to place on your applet using classes available in the Swing package ( javax.swing ) Class names.
COMP 321 Week 2. Outline Event-Driven Programming Events, Event Sources, Event Listeners Button and Timer Events Mouse Events, Adapters.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
Java Applet. Introductions Applet is java program that can be embedded into HTML pages Java applets runs on the java enables web browsers such as mozila.
For (int i = 1; i
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 15 Creating User.
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)
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 10: Event Handling 1 Event Handling.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7-2 ( Book Chapter 14) GUI and Event-Driven Programming.
ICOM 4015 Fall 2008 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. ICOM 4015: Advanced Programming Lecture 9 Chapter.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 10: Event Handling 1 Chapter 10 Event Handling.
Graphical User Interfaces A Graphical User Interface (GUI) in Java is created with at least three kinds of objects: –components, events, and listeners.
GUI Components CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Event-Driven Programming CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
1/18H212Mouse and Timer Events H212 Introduction to Software Systems Honors Lecture #16: Mouse and Timer Events October 26, 2015.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Event Handling and GUI Components.
Mouse Events GUI. Types of Events  Below, are some of the many kinds of events, swing components generate. Act causing EventListener Type User clicks.
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.
Frame Windows Application program, not applet Construct and show frame JFrame frame = new JFrame(); *** frame.show(); *** Set default close operation..
GUI Tutorial Day 4. More GUI action  adding a Mouse Listener  SimpleDots  Simple mouse listener  Draw an oval where the mouse is clicked  Box example.
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:
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Chapter 4 Interface Types and Polymorphism Part 2.
Multiple buttons and action calls
Java Applet What is a Java Applet? How is applet compiled?
A First Look at GUI Applications
Graphical User Interface (pronounced "gooey")
Chapter 4 Interface Types and Polymorphism Part 2
A Quick Java Swing Tutorial
Ellen Walker Hiram College
Event-driven programming for GUI
Chapter 12 Event Handling
Chapter 7-2 (Book Chapter 14)
A Quick Java Swing Tutorial
Chapter 7-2 (Book Chapter 14)
Presentation transcript:

CHAPTER 10 EVENT HANDLING

CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display frame windows To show text output in a text area with a scroll bar

Event Classes Event source: Generates events and manages listeners Example: applet Listener: Notified when event happens Example: MouseListener Event class: Describes event Example: MouseEvent

The MouseListener Interface public interface MouseListener { void mousePressed(MouseEvent event); //Called when a mouse button has been pressed on a component void mouseReleased(MouseEvent event); //Called when a mouse button has been released on a component void mouseClicked(MouseEvent event); //Called when the mouse has been clicked on a component void mouseEntered(MouseEvent event); //Called when the mouse enters a component void mouseExited(MouseEvent event); //Called when the mouse exits a component }

File MouseSpy.java 1 import java.awt.event.MouseEvent; 2 import java.awt.event.MouseListener; 3 4 /** 5 This listener simply prints out the listener method name 6 and the x- and y-coordinate of the mouse position. 7 */ 8 public class MouseSpy implements MouseListener 9 { 10 public void mousePressed(MouseEvent event) 11 { 12 System.out.println("Mouse pressed. x = " 13 + event.getX() + " y = " + event.getY()); 14 } public void mouseReleased(MouseEvent event) 17 { 18 System.out.println("Mouse released. x = "

19 + event.getX() + " y = " + event.getY()); 20 } public void mouseClicked(MouseEvent event) 23 { 24 System.out.println("Mouse clicked. x = " 25 + event.getX() + " y = " + event.getY()); 26 } public void mouseEntered(MouseEvent event) 29 { 30 System.out.println("Mouse entered. x = " 31 + event.getX() + " y = " + event.getY()); 32 } public void mouseExited(MouseEvent event) 35 { 36 System.out.println("Mouse exited. x = " 37 + event.getX() + " y = " + event.getY()); 38 } 39 }

File MouseSpyApplet.java 1 import java.applet.Applet; 2 3 /** 4 This applet installs a mouse spy. Try generating the 5 five mouse event types by moving and clicking the mouse. 6 */ 7 public class MouseSpyApplet extends Applet 8 { 9 public MouseSpyApplet() 10 { 11 MouseSpy listener = new MouseSpy(); 12 addMouseListener(listener); 13 } 14 } 15

Spying on Mouse Events

Mouse Listener that Moves a Rectangle public MouseApplet() {... //add mouse press listener class MousePressListener implements MouseListener { public void mousePressed(MouseEvent event) { int x = event.getX(); int y = event.getY(); box.setLocation(x,y); repaint(); }

//do-nothing methods public void mouseReleased(MouseEvent event){} public void mouseClicked(MouseEvent event){} public void mouseEntered(MouseEvent event){} public void mouseExited(MouseEvent event){} } MouseListener listener = new MousePressListener(); addMouseListener(listener); }

Mouse Listener that Moves a Rectangle Gets mouse position from event object Accesses box instance field of outer class Invokes repaint method on outer class repaint triggers paint method You should always call repaint to trigger painting Don't call paint directly

The Mouse Applet

An Applet with a Control Panel

Control Panel Components Use Swing package javax.swing Class names start with J JTextField xField = new JTextField(width); JLabel xLabel = new JLabel("x = "); Icon buttonIcon = new ImageIcon("hand.gif"); moveButton = new JButton("Move",buttonIcon);

Button Listener Moves rectangle when button is clicked Reads xField, yField variables from enclosing scope public ButtonApplet() {... class MoveButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { int x =Integer.parseInt(xField.getText()); int y =Integer.parseInt(yField.getText()); box.setLocation(x,y); repaint(); } }; ActionListener listener = new MoveButtonListener(); moveButton.addActionListener(listener);... }

Placing Components in a Panel JPanel is container for components Add components to panel JPanel panel = new JPanel(); panel.add(xLabel); panel.add(xField);... Place panel inside frame JFrame frame = new JFrame(); frame.setContentPane(panel); Pack frame: size it to just contain the components frame.pack(); frame.show();

File ButtonApplet.java 1 import java.applet.Applet; 2 import java.awt.Graphics; 3 import java.awt.Graphics2D; 4 import java.awt.Rectangle; 5 import java.awt.event.ActionEvent; 6 import java.awt.event.ActionListener; 7 import javax.swing.ImageIcon; 8 import javax.swing.JButton; 9 import javax.swing.JFrame; 10 import javax.swing.JLabel; 11 import javax.swing.JPanel; 12 import javax.swing.JTextField; /** 15 This applet lets the user move a rectangle by specifying 16 the x- and y-position of the top left corner. 17 */

18 public class ButtonApplet extends Applet 19 { 20 public ButtonApplet() 21 { 22 // the rectangle that the paint method draws 23 box = new Rectangle(BOX_X, BOX_Y, 24 BOX_WIDTH, BOX_HEIGHT); // the text fields for entering the x- and y-coordinates 27 final JTextField xField = new JTextField(5); 28 final JTextField yField = new JTextField(5);; // the button to move the rectangle 31 JButton moveButton = new JButton("Move", 32 new ImageIcon("hand.gif")); class MoveButtonListener implements ActionListener 35 { 36 public void actionPerformed(ActionEvent event) 37 {

38 int x = Integer.parseInt(xField.getText()); 39 int y = Integer.parseInt(yField.getText()); 40 box.setLocation(x, y); 41 repaint(); 42 } 43 }; ActionListener listener = new MoveButtonListener(); 46 moveButton.addActionListener(listener); // the labels for labeling the text fields 49 JLabel xLabel = new JLabel("x = "); 50 JLabel yLabel = new JLabel("y = "); // the panel for holding the user interface components 53 JPanel panel = new JPanel(); panel.add(xLabel); 56 panel.add(xField); 57 panel.add(yLabel); 58 panel.add(yField);

59 panel.add(moveButton); // the frame for holding the component panel 62 JFrame frame = new JFrame(); 63 frame.setContentPane(panel); 64 frame.pack(); 65 frame.show(); 66 } public void paint(Graphics g) 69 { 70 Graphics2D g2 = (Graphics2D)g; 71 g2.draw(box); 72 } private Rectangle box; 75 private static final int BOX_X = 100; 76 private static final int BOX_Y = 100; 77 private static final int BOX_WIDTH = 20; 78 private static final int BOX_HEIGHT = 30; 79 }

Multiple Buttons with Similar Behavior Don't want to write separate code for similar listeners Remedy: Write method that attaches the listener Make variable parts into final method parameters Local listener class can access final parameters

An Applet with Multiple Buttons

Method for Attaching Listener public JButton makeButton(String label, final int dx,final int dy) { JButton button = new JButton(label); class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { box.translate(dx, dy); repaint(); } }; ButtonListener listener = new ButtonListener(); button.addActionListener(listener); return button; }

Method for Attaching Listener Call multiple times panel.add(makeButton("Left",-BOX_WIDTH,0)); panel.add(makeButton("Right",BOX_WIDTH,0)); panel.add(makeButton("Up",0,-BOX_HEIGHT)); panel.add(makeButton("Down",0,BOX_HEIGHT));

File ButtonApplet.java 1 import java.applet.Applet; 2 import java.awt.Graphics; 3 import java.awt.Graphics2D; 4 import java.awt.Rectangle; 5 import java.awt.event.ActionEvent; 6 import java.awt.event.ActionListener; 7 import javax.swing.JButton; 8 import javax.swing.JFrame; 9 import javax.swing.JPanel; /** 12 This applet lets the user move a rectangle by clicking 13 on buttons labeled "Left", "Right", "Up", and "Down". 14 */ 15 public class ButtonApplet extends Applet 16 { 17 public ButtonApplet()

18 { 19 // the rectangle that the paint method draws 20 box = new Rectangle(BOX_X, BOX_Y, 21 BOX_WIDTH, BOX_HEIGHT); // the panel for holding the user interface components 24 JPanel panel = new JPanel(); panel.add(makeButton("Left", -BOX_WIDTH, 0)); 27 panel.add(makeButton("Right", BOX_WIDTH, 0)); 28 panel.add(makeButton("Up", 0, -BOX_HEIGHT)); 29 panel.add(makeButton("Down", 0, BOX_HEIGHT)); // the frame for holding the component panel 32 JFrame frame = new JFrame(); 33 frame.setContentPane(panel); 34 frame.pack(); 35 frame.show(); 36 } 37

38 public void paint(Graphics g) 39 { 40 Graphics2D g2 = (Graphics2D)g; 41 g2.draw(box); 42 } /** 45 Makes a button that moves the box. label the label to show on the button dx the amount by which to move the box in x-direction 48 when the button is clicked dy the amount by which to move the box in y-direction 50 when the button is clicked the button 52 */ 53 public JButton makeButton(String label, final int dx, 54 final int dy) 55 { 56 JButton button = new JButton(label); 57

58 class ButtonListener implements ActionListener 59 { 60 public void actionPerformed(ActionEvent event) 61 { 62 box.translate(dx, dy); 63 repaint(); 64 } 65 }; ButtonListener listener = new ButtonListener(); 68 button.addActionListener(listener); 69 return button; 70 } private Rectangle box; 73 private static final int BOX_X = 100; 74 private static final int BOX_Y = 100; 75 private static final int BOX_WIDTH = 20; 76 private static final int BOX_HEIGHT = 30; 77 }

Frame Windows Application program, not applet Construct and show frame JFrame frame = new JFrame();... frame.show(); Set the default close operation frame.setDefaultCloseOperation(EXIT_ON_CLOSE); Add components to a panel, then set the panel as content pane JPanel panel = new JPanel(); panel.add(...); panel.add(...) frame.setContentPane(panel);

A Frame with Two Labels

File FrameTest.java 1 import javax.swing.ImageIcon; 2 import javax.swing.JFrame; 3 import javax.swing.JLabel; 4 import javax.swing.JPanel; 5 6 /** 7 This program displays a frame with an image and a text label. 8 */ 9 public class FrameTest 10 { 11 public static void main(String[] args) 12 { 13 JFrame frame = new JFrame(); 14 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel iconLabel = new JLabel(new ImageIcon("world.gif")); 17 JLabel textLabel = new JLabel("Hello, World!");

18 19 JPanel panel = new JPanel(); 20 panel.add(iconLabel); 21 panel.add(textLabel); 22 frame.setContentPane(panel); frame.pack(); 25 frame.show(); 26 } 27 }

Text Components JTextField holds a single line of text JTextArea holds multiple lines Construct with new JTextArea(rows, columns) textArea.append(aString) appends text Use textArea.setEditable(false) to use for display only To add scroll bars, use JScrollPane scrollPane = new JScrollPane(textArea); textArea.setContentPane(scrollPane);

A Text Area with Scroll Bars

The Control Panel for Adding Interest

File TextAreaTest.java 1 import java.awt.event.ActionEvent; 2 import java.awt.event.ActionListener; 3 import javax.swing.JButton; 4 import javax.swing.JFrame; 5 import javax.swing.JLabel; 6 import javax.swing.JPanel; 7 import javax.swing.JScrollPane; 8 import javax.swing.JTextArea; 9 import javax.swing.JTextField; /** 12 This program shows a frame with a text area that displays 13 the growth of an investment. A second frame holds a text 14 field to specify the interest rate. 15 */ 16 public class TextAreaTest 17 {

18 public static void main(String[] args) 19 { 20 // the application adds interest to this bank account 21 final BankAccount account = new BankAccount(INITIAL_BALANCE); 22 // the text area for displaying the results 23 final JTextArea textArea = new JTextArea(10, 30); 24 textArea.setEditable(false); 25 JScrollPane scrollPane = new JScrollPane(textArea); // construct the frame for displaying the text area 28 JFrame frame = new JFrame(); 29 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 30 frame.setContentPane(scrollPane); 31 frame.pack(); 32 frame.show(); // the label and text field for entering the interest rate 35 JLabel rateLabel = new JLabel("Interest Rate: "); final JTextField rateField = new JTextField(10);

38 rateField.setText("" + DEFAULT_RATE); // the button to trigger the calculation 41 JButton calculateButton = new JButton("Add Interest"); class CalculateListener implements ActionListener 44 { 45 public void actionPerformed(ActionEvent event) 46 { 47 double rate = Double.parseDouble( 48 rateField.getText()); 49 double interest = account.getBalance() 50 * rate / 100; 51 account.deposit(interest); 52 textArea.append(account.getBalance() + "\n"); 53 } 54 } ActionListener listener = new CalculateListener(); 57 calculateButton.addActionListener(listener);

58 59 // the control panel that holds the input components 60 JPanel controlPanel = new JPanel(); 61 controlPanel.add(rateLabel); 62 controlPanel.add(rateField); 63 controlPanel.add(calculateButton); // the frame to hold the control panel 66 JFrame controlFrame = new JFrame(); 67 controlFrame.setContentPane(controlPanel); 68 controlFrame.pack(); 69 controlFrame.show(); 70 } private static final double DEFAULT_RATE = 10; 73 private static final double INITIAL_BALANCE = 1000; 74 }