CS 240 Week 9. EventQueue.invokeLater In Swing, all user interface operations must occur on the “UI thread” – All components should be created on the.

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
Frame Windows A frame object is used to create a graphical frame window. This frame is used to show information in a graphical application. The JFrame.
Graphics You draw on a Graphics object The Graphics object cannot directly be created by your code, instead one is generated when the method paintComponent.
Graphics Programming. Introduction GOAL: Build the Indexer Client Event-driven vs. Sequential programs Terminology – Top-level windows are called “frame.
CS18000: Problem Solving and Object-Oriented Programming.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
Graphical User Interfaces, 2D Graphics & Game Programming.
Chapter 5 Programming Graphics. Chapter Goals To be able to write simple applications To display graphical shapes such as lines and ellipses To use colors.
Chapter 5 Programming Graphics. Chapter Goals To be able to write applications with simple graphical user interfaces To display graphical shapes such.
Events and the AWT The objectives of this chapter are: To understand the principles of the Java 1.1 event model To understand how the event model is used.
Event Handling. In this class we will cover: Basics of event handling The AWT event hierarchy Semantic and low-level events in the AWT.
Graphics Programming. In this class, we will cover: The difference between AWT and Swing Creating a frame Frame positioning Displaying information in.
Event Handling. In this class we will cover: Keyboard Events Mouse Events Focus Events Action Interface Multicasting.
Java Review Structure of a graphics program. Computer Graphics and User Interfaces Java is Object-Oriented A program uses objects to model the solution.
Swing Graphics ● Empty Swing containers have no visual appearance except for a background color ● Every JComponent must have a paintComponent method that.
CSE 331 Software Design & Implementation Dan Grossman Spring 2015 GUI Event-Driven Programming (Based on slides by Mike Ernst, Dan Grossman, David Notkin,
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
28-Aug-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Event Handling – GUI Part II.
1 Interface Types & Polymorphism & introduction to graphics programming in Java.
1 Graphical User Components (II) Outline JTextArea Creating a Customized Subclass of JPanel JPanel Subclass that Handles Its Own Events Windows: Additional.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
CSE 219 Computer Science III Images. HW1 Has been posted on Blackboard Making a Game of Life with limited options.
Graphics in Java hussein suleman uct cs
Using the JImageViewer classes. JImageViewer classes JImageViewer class JImageViewer class ImagePanel class ImagePanel class Image class Image class.
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.
Dale Roberts GUI Programming using Java - Event Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
Swing II. Swing II Topics WindowListener interface WindowListener interface Icons Icons Scrollbars Scrollbars The Graphics class The Graphics class Colors.
– 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.
1 Unit 5 GUI Aum Amriteshwaryai Namah. 2 Overview Shall learn how to reuse the graphics classes provided by Java for constructing Graphical User Interface.
Copyright © 2002, Systems and Computer Engineering, Carleton University b-Gui2.ppt * Object-Oriented Software Development Part 18-b Building.
Omer Boyaci.  GUIs are event driven.  When the user interacts with a GUI component, the interaction—known as an event—drives the program to perform.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
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.
UID – Event Handling and Listeners Boriana Koleva
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.
(C) 2010 Pearson Education, Inc. All rights reserved.  Class Graphics (from package java.awt) provides various methods for drawing text and shapes onto.
Anonymous Classes An anonymous class is a local class that does not have a name. An anonymous class allows an object to be created using an expression.
CMSC 341 Making Java GUIs Functional. 09/29/2007 CMSC 341 Events 2 More on Swing Great Swing demo at /demos/jfc/SwingSet2/SwingSet2Plugin.html.
Object Oriented Programming.  Interface  Event Handling.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Event-Driven Programming 1.
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.
Introduction to Java Chapter 8 - Introduction to Java Graphics1 Chapter 8 Introduction to Java Graphics.
GUI DYNAMICS Lecture 11 CS2110 – Fall GUI Statics and GUI Dynamics  Statics: what’s drawn on the screen  Components buttons, labels, lists, sliders,
Image Panel & Image Navigator. Review Graphics2D class for drawing shapes in a component – paintComponent(Graphics g) – Graphics2D g2 = (Graphics2D)g;
CIS Intro to JAVA Lecture Notes Set 8 9-June-05.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 10: Event Handling 1 Chapter 10 Event Handling.
Event Handling. User actions are called “events” – Low-level window events Window changes – Low-level component events Mouse events, Keyboard events,
Creating User Interfaces Event-Driven Programming.
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.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Jaeki Song ISQS6337 JAVA Lecture 10 Applets. Jaeki Song ISQS6337 JAVA Applet Applets run within the Web browser environment –Applets bring dynamic interaction.
Jozef Goetz Credits: Copyright  Pearson Education, Inc. All rights reserved. expanded by J. Goetz, 2016.
Sep 181 Example Program DemoTranslateEnglishGUI.java.
C Sc 335 Object-Oriented Programming and Design Rick Mercer
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
GUI Programming in Java Hao Jiang Boston College April, 2009.
10/20/2005week71 Graphics, mouse and mouse motion events, KeyEvent Agenda Classes in AWT for graphics Example java programs –Graphics –Mouse events –Mouse.
Advanced User Interfaces
Java Graphics CS 2511.
CSE 331 Software Design and Implementation
Swing II.
CSE 331 Software Design and Implementation
Events, Event Handlers, and Threads
Presentation transcript:

CS 240 Week 9

EventQueue.invokeLater In Swing, all user interface operations must occur on the “UI thread” – All components should be created on the UI thread – All method calls on UI components should happen on the UI thread EventQueue.invokeLater runs the specified code on the UI thread The main method for Swing programs should call EventQueue.invokeLater to create the UI The main thread exits immediately after calling EventQueue.invokeLater, but the UI thread keeps the program running EXAMPLE: EmptyFrameEmptyFrame

JFrame Use JFrame class to create top-level windows setTitle method sets the window’s title setDefaultCloseOperation method specifies what should happen when the user clicks the window’s close icon setLocation method sets the window’s location on the desktop setVisible method shows or hides the window setSize method sets the window’s size EXAMPLE: EmptyFrameEmptyFrame

JFrame add method adds a new subcomponent to the window pack method sets the window’s size according to the preferred size and layout of the window’s subcomponents EXAMPLE: SimpleFrameSimpleFrame

JComponent User interface components are subclasses of JComponent that provide custom drawing and event handling functionality getSize and setSize methods get and set component’s width and height – getWidth and getHeight methods return component’s width and height individually setBackground method is used to set the component’s background color setPreferredSize, setMinimumSize, setMaximumSize methods are used to express the components preferred, min, and max sizes paintComponent method draws the contents of the component Graphics2D class is used to perform drawing operations in a component EXAMPLE: DrawingDrawing

Color – Red, Green, Blue, Alpha (transparency) components – new Color(210, 180, 140, 192) – Graphics.setColor method sets the current drawing color Drawing origin is the component’s top-left corner. X values increase as you move right. Y values increase as you move down. Representing points – Point2D superclass Point2D.Float and Point2D.Double subclasses (nested inside Point2D) – Point2D.Double pt = new Point2D.Double(x, y)

Drawing Rectangles Rectangles – Graphics.drawRect(x, y, width, height) – Graphics.fillRect(x, y, width, height) – OR – Rectangle2D superclass Rectangle2D.Float and Rectangle2D.Double subclasses (nested inside Rectangle2D) – Rectangle2D rect = new Rectangle2D.Double(x, y, w, h) – Graphics2D.draw(rect) – Graphics2D.fill(rect) – EXAMPLE: DrawingDrawing

Drawing Ellipses Ellipses – Graphics.drawOval(x, y, width, height) – Graphics.fillOval(x, y, width, height) – OR – Ellipse2D superclass Ellipse2D.Float and Ellipse2D.Double subclasses (nested inside Ellipse2D) – Ellipse2D ellipse = new Ellipse2D.Double(x, y, w, h) – Graphics2D.draw(ellipse) – Graphics2D.fill(ellipse)

Drawing Lines Lines – Graphics.drawLine(x, y, width, height) – OR – Line2D superclass Line2D.Float and Line2D.Double subclasses (nested inside Line2D) – Line2D line = new Line2D.Double(x1, y1, x2, y2) – Graphics2D.setStroke method sets the line thickness and style g2d.setStroke(new BasicStroke(5)); // line 5 pixels wide – Graphics2D.draw(line) – EXAMPLE: DrawingDrawing

Drawing Text Font class represents fonts Font font = new Font(name, style, size) – Font font = new Font(“SansSerif”, Font.PLAIN, 72); Graphics.setFont method sets the current font – g2d.setFont(font); Graphics2D.drawString(string, x, y) – (x, y) is location of text’s baseline – g2d.drawString(“Hi There”, 100, 200); EXAMPLE: DrawingDrawing

Drawing Text Calculating text metrics (width, height, etc.) – FontRenderContext context = g2d.getFontRenderContext(); – Rectangle2D bounds = font.getStringBounds(message, context); – double stringWidth = bounds.getWidth(); – double stringHeight = bounds.getHeight(); – double ascent = -bounds.getY(); If you need descent and leading – LineMetrics metrics = font.getLineMetrics(message, context); – float descent = metrics.getDescent(); – float leading = metrics.getLeading();

Drawing Images The BufferedImage class can be used to store and manipulate images in memory. You can: Load an existing image into a BufferedImage Modify an image by changing the pixel values in a BufferedImage Create a new image by creating an empty BufferedImage and modifying its pixel values Save a BufferedImage to a file

Drawing Images The ImageIO class can be used to load images from disk or the web, and to save images to disk Load image from disk: – String filename = "..."; – Image image = ImageIO.read(new File(filename)); – EXAMPLE: DrawingDrawing Load image from URL: – String urlname = "..."; – Image image = ImageIO.read(new URL(urlname));

Drawing Images Graphics.drawImage(image, destX1, destY1, destX2, destY2, srcX1, srcY1, srcX2, srcY2) – “dest” is the destination rectangle where the image should be drawn in the component – “src” is the source rectangle in the image to be drawn Can be only part of the image – “dest” and “src” do not have to be the same size. The drawImage method will scale the source image to fit in the destination rectangle. This is one way to scale an image – EXAMPLE: DrawingDrawing

Event Handling User actions are called “events” – Low-level window events Window changes – Low-level component events Mouse events, Keyboard events, Component changes – High-level component-specific events Button events, Menu events, List events, etc. Events are handled by attaching “event listeners” to windows and components Swing defines a “listener interface” for each category of events – Examples: WindowListener, MouseListener, MenuListener

Event Handling A “listener” is an object that implements a listener interface Listeners are attached to windows and components by calling the appropriate “addXXXListener” methods – addWindowListener, addMouseListener, addMenuListener, etc. The window or component will notify all attached listeners about all relevant events – windowActivated, mouseClicked, menuSelected, etc. Listener methods accept an EventObject parameter that describes the event that occurred – WindowEvent, MouseEvent, MenuEvent, etc. – The EventObject.getSource method returns the window or component that generated the event

Event Handling Listeners are typically implemented as inner classes – Named inner class class MyMouseHandler implements MouseListener { … } this.addMouseListener(new MyMouseHandler()); – Anonymous inner class this.addMouseListener(new MouseListener() { … });

Event Handling Event Adapter classes – Frequently, a program only wants to handle a few of the events defined by a listener interface – However, implementing the listener interface requires implementations for all event methods – Swing provides Adapter superclasses that provide empty implementations of all methods in a listener interface WindowAdapter, MouseAdapter, KeyAdapter, etc. – This allows a program to create a listener by subclassing an adapter class, and overriding only the event methods it cares about – Some adapter classes implement multiple listener interfaces EXAMPLE: MouseAdapter implements MouseListener, MouseMotionListener, and MouseWheelListener

Mouse Events MouseListener interface MouseMotionListener interface MouseWheelListener interface MouseAdapter class EXAMPLE: Dragging and scrolling shapes in DrawingDrawing

Component Events ComponentListener interface ComponentAdapter class EXAMPLE: Updating width and height in text shapes in DrawingDrawing

Window Events WindowListener interface WindowStateListener interface WindowAdapter class EXAMPLE: Frame window in DrawingDrawing

Keyboard Events Keyboard Focus – When the user types a key, which component gets the key event? The component with the “keyboard focus” – Only one window has the keyboard focus at a time – Within that window, only one component has the keyboard focus at a time – A component can request the keyboard focus by calling Component.requestFocus or Component.requestFocusInWindow – EXAMPLE: A text field requests the keyboard focus when the user clicks on it so it will receive key events

Keyboard Events When a window receives or loses the keyboard focus, it generates “gained focus” and “lost focus” events – WindowFocusListener interface When a component receives or loses the keyboard focus, it generates “gained focus” and “lost focus” events – FocusListener interface EXAMPLE: In Drawing, when the frame window receives keyboard focus, DrawingFrame calls requestFocusInWindow on the DrawingComponent so it will receive keyboard eventsDrawing

Keyboard Events KeyListener interface KeyAdapter class EXAMPLE: Moving shapes with arrow keys in DrawingDrawing