241-211 OOP (Java): GUI II/13 1 241-211. OOP Objectives – –describe some more GUI features: JPanel, and mouse listeners/adapters Semester 2, 2013-2014.

Slides:



Advertisements
Similar presentations
2D Graphics Drawing Things. Graphics In your GUI, you might want to draw graphics E.g. draw lines, circles, shapes, draw strings etc The Graphics class.
Advertisements

 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
Mouse Listeners We continue our examination of GUIs by looking at how to interact with the mouse –Just as Java creates Events when the user interacts with.
Managing Input Events in Swing Week 5 Workshop Lyn Bartram.
Computer Science 209 Graphics and GUIs. Working with Color The class java.awt.Color includes constants for typical color values and also supports the.
Event-Driven Programming Thus far, our programs have been executed one statement after the other However, many programs depend on user actions to dictate.
Event Handling Events and Listeners Timers and Animation.
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.
GUI. Swing Class Hierarchy Swing Components Swing Conatiners  JFrame – top-level window to store components.
Lecture 18 Review the difference between abstract classes and interfaces The Cloneable interface Shallow and deep copies The ActionListener interface,
CPSC150 Week 12 Graphical User Interfaces Chapter 11.
1 Object-Oriented Programming (Java), Unit 22 Kirk Scott.
Mouse Events. Handling Mouse Events Java provides two listener interfaces to handle mouse events: MouseListener;  MouseListener;  MouseMotionListener.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
Chapter 11 Java AWT Part I: Mouse Events (Optional) Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin,
Adding Graphics to a Frame Application Applets: Can generate drawings by overriding paint Frame: Do not draw directly on a frame. Draw graphics on a JPanel.
More Event Handling Adapters Anonymous Listeners Pop menus Validating User Input.
Cs884(Prasad)java12AWT1 Abstract Windowing Toolkit Support for Graphical User Interface (Event-driven programming)
CS 11 java track: lecture 4 This week: arrays interfaces listener classes inner classes GUI callbacks.
CSE 219 Patterns in Programming More Design Patterns.
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.
(c) University of Washington07b-1 CSC 143 Java Events, Event Handlers, and Threads Reading: Ch. 17.
CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.
SD2071 Games Programming Abstraction, inheritance and interfaces Exceptions Two dimensional arrays Java collections framework Files Aaron Kans.
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.
Lesson 34: Layering Images with Java GUI. The FlowLayout RECAP.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
FEN IntroJava2006 AAU1 GUI: Graphical User Interface AWT/SWING: Components Drag and Drop in NetBeans Events Listeners.
Copyright © 2002, Systems and Computer Engineering, Carleton University b-Gui2.ppt * Object-Oriented Software Development Part 18-b Building.
MSc Workshop - © S. Kamin, U.Reddy Lect 4 - Events - 1 Lecture 4 – Event Handling r Painting r Event types r Catching different event types.
Java's Graphical User Interface Toolkit
COMP 321 Week 2. Outline Event-Driven Programming Events, Event Sources, Event Listeners Button and Timer Events Mouse Events, Adapters.
CSE 219 Computer Science III Image Manipulation. HW 1 Has been posted on Blackboard Making a Game of Life with limited.
OOP (Java): GUI Intro/ OOP Objectives – –use an image viewer application to introduce Java's GUI features Semester 2,
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
UID – Event Handling and Listeners Boriana Koleva
CS1054: Lecture 21 - Graphical User Interface. Graphical User Interfaces vs. Text User Interface.
Object Oriented Programming.  Interface  Event Handling.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 10: Event Handling 1 Event Handling.
CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
GUI DYNAMICS Lecture 11 CS2110 – Fall GUI Statics and GUI Dynamics  Statics: what’s drawn on the screen  Components buttons, labels, lists, sliders,
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 10: Event Handling 1 Chapter 10 Event Handling.
Mouse Listeners Moving the mouse will also generate events like the Timer –To have your program respond, you must implement either or both of MouseListener.
Object-Oriented Software Engineering Using Threads and simple Animation.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 27.1 Test-Driving the Drawing Shapes Application.
Nested Classes and Event Handling Chapter 10. Overview We explain how to write Java code that responds to events. The Timer class can be used to respond.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 10.
1/18H212Mouse and Timer Events H212 Introduction to Software Systems Honors Lecture #16: Mouse and Timer Events October 26, 2015.
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.
Event Handling H_Func(Event) { } Event Receiver Object Source Object Registration.
Mouse Events GUI. Types of Events  Below, are some of the many kinds of events, swing components generate. Act causing EventListener Type User clicks.
Lesson 33: Layout management and drawing – Java GUI.
Sep 181 Example Program DemoTranslateEnglishGUI.java.
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.
TENTH LECTURE Event and listener. Events and Listeners An event can be defined as a type of signal to the program that something has happened. The event.
1 DemoBasic_v3, DemoBasic_v4 JButton JLabel. 2 Registering an ActionListener Register by invoking the following from within constructor DemoBasicFrame.
Mouse, Keyboard, Sounds, and Images JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin,
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
Events and Event Handling
Lecture 8 Object Oriented Programming Using Java
Object-Oriented Programming (Java), Unit 22
Advanced User Interfaces
Computer Science 209 Graphics and GUIs.
GUI III IS
Web Design & Development Lecture 12
1 Graphical User Interfaces
Events, Event Handlers, and Threads
Presentation transcript:

OOP (Java): GUI II/ OOP Objectives – –describe some more GUI features: JPanel, and mouse listeners/adapters Semester 2, GUI Examples II

OOP (Java): GUI II/13 2 Contents 1.Reminder on the 3-step GUI 2.Painting with JPanel 3.The Final ImageViewer 4.Listener Interfaces 5.Mouse Example: Doodle 6.Adapter Classes continued

OOP (Java): GUI II/ The SwingSet Examples 8.More Information

OOP (Java): GUI II/ Reminder of the 3-Step GUI The three steps in writing GUIs: – –1. Declare the GUI components; – –2. Implement the event handlers for the components; – –3. Position the components on the screen by using layout managers and/or containers.

OOP (Java): GUI II/ Painting with JPanel One of the uses of JPanel is as a 'canvas' (painting surface). One of the uses of JPanel is as a 'canvas' (painting surface). Its paintComponent() method can be overridden, and then draw/paint operations can be added to it. Its paintComponent() method can be overridden, and then draw/paint operations can be added to it.

OOP (Java): GUI II/13 6 Whenever the JPanel is redrawn, paintComponent() is called to draw the panel. Whenever the JPanel is redrawn, paintComponent() is called to draw the panel. The paintComponent() declaration is: The paintComponent() declaration is: –public void paintComponent(Graphics g) –g is the graphics context for the panel

OOP (Java): GUI II/13 7 g links to the panel's drawing area on screen. The Graphics Context application JPanel drawing area g void paintComponent(Graphics g) { // drawing operations, e.g. g.drawImage(...); : }

OOP (Java): GUI II/ The Final ImageViewer The image is drawn onto a JPanel, which is in the content area of the JFrame. (ImageViewer) a JFrame (ImagePanel) a JPanel

OOP (Java): GUI II/13 9 Other Features The "open" menu item now calls JFileChooser to let the user choose an image file to load and display. The "open" menu item now calls JFileChooser to let the user choose an image file to load and display. JFileChooser continued

OOP (Java): GUI II/13 10 The menu items now have keyboard shortcuts: The menu items now have keyboard shortcuts: –"open"==> -o –"quit"==> -q

OOP (Java): GUI II/13 11 Class Diagrams uses extends

OOP (Java): GUI II/13 12 The ImageViewer Class public class ImageViewer extends JFrame { private JFileChooser fileChooser; private ImagePanel imagePanel; public ImageViewer() { super("ImageViewer Final"); fileChooser = new JFileChooser( System.getProperty("user.dir") ); makeMenuBar(); Container c = getContentPane(); imagePanel = new ImagePanel(); c.add(imagePanel); : // as before } // end of ImageViewer()

OOP (Java): GUI II/13 13 private void makeMenuBar() // Create menu bar; add shortcuts. { int shortcut_mask = Toolkit.getDefaultToolkit(). getMenuShortcutKeyMask(); JMenuBar menubar = new JMenuBar(); setJMenuBar(menubar); // create the File menu JMenu fileMenu = new JMenu("File"); menubar.add(fileMenu); :

OOP (Java): GUI II/13 14 JMenuItem openItem = new JMenuItem("Open"); openItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_O, shortcut_mask)); // ctrl-o openItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { File f = chooseImage(); if (f != null) imagePanel.displayImage(f); pack(); // triggers resizing to fit image } }); fileMenu.add(openItem); : choose, display image

OOP (Java): GUI II/13 15 JMenuItem quitItem = new JMenuItem("Quit"); quitItem.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_Q, shortcut_mask)); // ctrl-q quitItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); fileMenu.add(quitItem); } // end of makeMenuBar() exit

OOP (Java): GUI II/13 16 private File chooseImage() // open file chooser and let the user select // an image file { int returnVal = fileChooser.showOpenDialog(null); if (returnVal != JFileChooser.APPROVE_OPTION) return null; // cancelled return fileChooser.getSelectedFile(); } // end of chooseImage()

OOP (Java): GUI II/13 17 public static void main(String[] args) { new ImageViewer(); } } // end of ImageViewer class

OOP (Java): GUI II/13 18 The ImagePanel Class public class ImagePanel extends JPanel { private int width, height; // of this panel private BufferedImage panelImage; public ImagePanel() { width = 360; // size for empty panel height = 240; panelImage = null; setBackground(Color.WHITE); } // end of ImagePanel()

OOP (Java): GUI II/13 19 public void displayImage(File f) // load and set the image for this panel { BufferedImage image = loadImage(f); if (image != null) { width = image.getWidth(); height = image.getHeight(); panelImage = image; invalidate(); repaint(); // triggers a panel redrawing // with the new image } } // end of displayImage()

OOP (Java): GUI II/13 20 private BufferedImage loadImage(File imageFile) // load an image file and returns it as a // BufferedImage. { try { BufferedImage image = ImageIO.read(imageFile); if (image == null ||(image.getWidth() < 0)) // probably bad file format return null; return image; } catch (IOException e) { return null; } } // end of loadImage()

OOP (Java): GUI II/13 21 Redefined Methods from JPanel public Dimension getPreferredSize() /* Say how big we would like this panel to be. This method gets called by the layout manager when placing and sizing this panel in the JFrame. */ { return new Dimension(width, height); }

OOP (Java): GUI II/13 22 public void paintComponent(Graphics g) /* Draw the image onto the panel. This method gets called by the JVM every time it want to display (or redisplay) this panel. */ { super.paintComponent(g); // repaint standard stuff first Dimension size = getSize(); g.clearRect(0, 0, size.width, size.height); if (panelImage != null) g.drawImage(panelImage, 0, 0, null); } // end of paintComponent() } // end of ImagePanel class

OOP (Java): GUI II/ Listener Interfaces I'm looking at four listener interfaces that can handle events from different GUI components – –ActionListener – –ItemListener – –MouseListener – –MouseMotionListener There are several other listener interfaces. in the last part, part 12 this part

OOP (Java): GUI II/ MouseListener It deals with mouse clicks over GUI components. Its interface has 5 methods: – –public void mouseClicked(MouseEvent e) – –public void mousePressed(MouseEvent e) – –public void mouseReleased(MouseEvent e) – –public void mouseEntered(MouseEvent e) – –public void mouseExited(MouseEvent e)

OOP (Java): GUI II/13 25 Using the Listener The GUI control must be linked to code which implements the method in the listener. GUI Window the link which sends an event e public class Foo3 implements MouseListener { public void mouseClicked( MouseEvent e ) { // do something with e System.out.println("Bing"); } : // all the other methods }

OOP (Java): GUI II/ MouseMotionListener For efficiency reasons, mouse movement events are dealt with by a separate listener. Its interface has 2 methods: – –public void mouseDragged(MouseEvent e) – –public void mouseMoved(MouseEvent e)

OOP (Java): GUI II/13 27 Using the Listener The GUI control must be linked to code which implements the method in the listener. GUI Window the link which sends an event e public class Foo4 implements MouseMotionListener { public void mouseDragged( MouseEvent e ) { // do something with e System.out.println("Boo"); } : // the other method }

OOP (Java): GUI II/ Mouse Example: Doodle Doodle is a simple paint program for drawing onto a JPanel placed inside a JFrame.

OOP (Java): GUI II/13 29 Features As the mouse is dragged, a series of black dots (circles) are drawn onto the JPanel. As the mouse is dragged, a series of black dots (circles) are drawn onto the JPanel. –this requires a MouseMotionListener When the mouse is pressed down, and released, the coordinates of the cursor are printed to stdout When the mouse is pressed down, and released, the coordinates of the cursor are printed to stdout –this requires a MouseListener

OOP (Java): GUI II/13 30 Class Diagrams uses multiple inheritance: 1 class, 2 interfaces lots of methods

OOP (Java): GUI II/13 31 The Doodle Class public class Doodle extends JFrame { public Doodle() { super("Doodle"); Container c = getContentPane(); c.add( new DoodlePanel() ); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setLocationRelativeTo(null); // center the window setVisible(true); } // end of Doodle() public static void main(String args[]) { new Doodle(); } } // end of Doodle

OOP (Java): GUI II/13 32 The DoodlePanel Class public class DoodlePanel extends JPanel implements MouseMotionListener, MouseListener { private static final int MAXPOINTS = 5000; // for storing the paintable points private Point[] points = new Point[MAXPOINTS]; private int nPoints = 0; : (x0,y0)(x1,y1)(x2,y2)(x3,y3).. points[] Version 1

OOP (Java): GUI II/13 33 public DoodlePanel() { setBackground(Color.white); addMouseMotionListener(this); addMouseListener(this); } // end of DoodlePanel() constructor public Dimension getPreferredSize() // Say how big we would like this panel to be { return new Dimension(500, 300); }

OOP (Java): GUI II/13 34 public void paintComponent(Graphics g) // repaint panel by redrawing stored points { super.paintComponent(g); for (int i = 0; i < nPoints; i++) g.fillOval( points[i].x, points[i].y, 4, 4); // the pen is a 4x4 black circle }

OOP (Java): GUI II/13 35 // methods for MouseMotionListener ---- public void mouseDragged( MouseEvent e) // record cursor position, then request a repaint { if (nPoints < MAXPOINTS) points[nPoints++] = new Point(e.getX(), e.getY()); repaint(); // the repaint will call paintComponent() } public void mouseMoved(MouseEvent e) {} // not needed

OOP (Java): GUI II/13 36 // methods for MouseListener public void mousePressed( MouseEvent e) { System.out.println( "Mouse pressed at (" + e.getX() + "," + e.getY() + ")" ); } public void mouseReleased( MouseEvent e) { System.out.println( "Mouse released at (" + e.getX() + "," + e.getY() + ")" ); } public void mouseClicked(MouseEvent e) {} // not needed public void mouseEntered(MouseEvent e) {} // not needed public void mouseExited(MouseEvent e) {} // not needed } // end of DoodlePanel class

OOP (Java): GUI II/ Adapter Classes When we implement an interface (a listener class), we must implement all of the methods inside it. Even if we only want to use one method, we still have to give empty implementations for all the other methods – –a lot of boring work for some listener classes e.g. MouseListener continued

OOP (Java): GUI II/13 38 Java supplies predefined classes which implement the bigger listener classes – –called adapter classes These adapter classes contain empty methods for all the event handlers – –the programmer can extend an adapter class, and only needs to override the methods needed.

OOP (Java): GUI II/13 39 Java's Adapter Classes MouseAdapter and MouseMotionAdapter WindowAdapter FocusAdapter ContainerAdapter ComponentAdapter KeyAdapter Beginners often use only the first three.

OOP (Java): GUI II/13 40 MouseAdapter.java public abstract class MouseAdapter implements MouseListener { public void mousePressed( MouseEvent e) {} public void mouseReleased( MouseEvent e) {} public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} } This class is already present in Java. You do not write this. empty methods a user cannot create MouseAdapter objects

OOP (Java): GUI II/13 41 Extending MouseAdapter class MouseHandler extends MouseAdapter { public void mousePressed( MouseEvent e) { System.out.println( "Mouse pressed at (" + e.getX() + "," + e.getY() + ")" ); } public void mouseReleased( MouseEvent e) { System.out.println( "Mouse released at (" + e.getX() + "," + e.getY() + ")" ); } } // end of MouseHandler class You write this class. only override the methods needed; the others stay empty

OOP (Java): GUI II/13 42 MouseMotionAdapter.java public abstract class MouseMotionAdapter implements MouseMotionListener { public void mouseDragged( MouseEvent e) {} public void mouseMoved( MouseEvent e) {} } This class is already present in Java. You do not write this. empty methods

OOP (Java): GUI II/13 43 Extending MouseMotionAdapter class MouseMotionHandler extends MouseMotionAdapter { public void mouseDragged( MouseEvent e) { if (nPoints < MAXPOINTS) points[nPoints++] = new Point(e.getX(), e.getY()); repaint(); } You write this class. only override the method needed; the other stays empty

OOP (Java): GUI II/13 44 Using the Handlers My MouseHandler and MouseMotionHandler classes should be declared as inner classes of DoodlePanel so that they can access its points[] array. My MouseHandler and MouseMotionHandler classes should be declared as inner classes of DoodlePanel so that they can access its points[] array.

OOP (Java): GUI II/13 45 DoodlePanel.java Version 2 public class DoodlePanel extends JPanel { // fields (as before) public DoodlePanel() { setBackground(Color.white); addMouseMotionListener( new MouseMotionHandler() ); addMouseListener( new MouseHandler() ); } // end of DoodlePanel() // getPreferredSize() and paintComponent() methods // (as in first DoodlePanel class) :

OOP (Java): GUI II/13 46 // inner classes class MouseHandler extends MouseAdapter { // as in slide } class MouseMotionHandler extends MouseMotionAdapter { // as in slide } } // end of DoodlePanel

OOP (Java): GUI II/13 47 Using Anonymous Classes The third way of implementing a listener is with anonymous (inner) classes. The third way of implementing a listener is with anonymous (inner) classes. –let's recode DoodlePanel to use them

OOP (Java): GUI II/13 48 The DoodlePanel Class public class DoodlePanel extends JPanel { // fields (as before) public DoodlePanel() { setBackground(Color.white); addMouseMotionListener( new MouseMotionAdapter() { public void mouseDragged( MouseEvent e) { if (nPoints < MAXPOINTS) points[nPoints++] = new Point(e.getX(),e.getY()); repaint(); } }); : Version 3 uses the superclass name

OOP (Java): GUI II/13 49 addMouseListener( new MouseAdapter() { public void mousePressed( MouseEvent e) { System.out.println( "Mouse pressed at (" + e.getX() + "," + e.getY() + ")" ); } public void mouseReleased( MouseEvent e) { System.out.println( "Mouse released at (" + e.getX() + "," + e.getY() + ")" ); } }); } // end of DoodlePanel()

OOP (Java): GUI II/13 50 // getPreferredSize() and paintComponent() methods // (as in first DoodlePanel class) // no inner classes } // end of DoodlePanel class

OOP (Java): GUI II/ The SwingSet2 Examples The JDK comes with excellent examples, complete with source code. The Swing examples are found in: C:\Program Files\Java\jdk1.6.0_22\ demo\jfc\SwingSet2 The source code is in the subdirectory src\ continued

OOP (Java): GUI II/13 52 The examples are run by executing the JAR file: c:> java -jar SwingSet2.jar A JAR file is very similar to a zipped file: – –a compressed file containing various Java resources (e.g. compiled code, images) – –a good way to distribute finished programs continued

OOP (Java): GUI II/13 53 Or you can start the JAR file by double- clicking on it. Or you can start the JAR file by double- clicking on it.

OOP (Java): GUI II/13 54 SwingSet2 Start-up Screen

OOP (Java): GUI II/13 55 JTable Example

OOP (Java): GUI II/ More Information o o The Java tutorial "Creating a GUI with JFC/Swing". o o Sub-topics include: – –Getting Started with Swing – –Swing Features and Concepts – –Using Swing Components – –Laying Out Components Within a Container – –Writing Event Listeners continued Excellent

OOP (Java): GUI II/13 57 o o Weighing in at 1621 pages!!: – –Graphic Java 2: Mastering the JFC Volume 2: Swing David M. Geary Sun MicroSystems, 1999, 3rd edition o o The other volumes: – –AWT (vol. 1), Advanced Swing (vol. 3) Java 2D (vol. 4) We have two copies in our library.