Graphical User Interfaces 2

Similar documents
Graphical User Interfaces 2

Graphical User Interfaces 2

Method Of Key Event Key Listener must implement three methods, keypressed(), keyreleased() & keytyped(). 1) keypressed() : will run whenever a key is

H212 Introduction to Software Systems Honors

Computer Science 210: Data Structures. Intro to Java Graphics

G51PRG: Introduction to Programming Second semester Applets and graphics

Graphical User Interfaces

CSC 160 LAB 8-1 DIGITAL PICTURE FRAME. 1. Introduction

GUI in Java TalentHome Solutions

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

GUI Event Handlers (Part II)

CS 251 Intermediate Programming GUIs: Event Listeners

Introduction to the JAVA UI classes Advanced HCI IAT351

ว ฒนพงศ ส ทธภ กด Java Programming ( )

Java Foundations John Lewis Peter DePasquale Joe Chase Third Edition

Windows and Events. created originally by Brian Bailey

AP Computer Science Unit 13. Still More Graphics and Animation.

ECE 462 Object-Oriented Programming using C++ and Java. Key Inputs in Java Games

Java for Interfaces and Networks (DT3010, HT10)

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

The AWT Event Model 9

GUI 4.1 GUI GUI MouseTest.java import javax.swing.*; import java.awt.*; import java.awt.event.*; /* 1 */

Datenbank-Praktikum. Universität zu Lübeck Sommersemester 2006 Lecture: Swing. Ho Ngoc Duc 1

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

Graphic User Interfaces. - GUI concepts - Swing - AWT

Event Driven Programming

More about JOptionPane Dialog Boxes

Java GUI Design: the Basics

Lecture 19 GUI Events

Outline. More on the Swing API Graphics: double buffering and timers Model - View - Controller paradigm Applets

Programming Languages and Techniques (CIS120)

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing.

Object-Oriented Programming in Java

Unit 7: Event driven programming

(Incomplete) History of GUIs

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline

CSE 331 Software Design & Implementation

User interfaces and Swing

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Heavyweight with platform-specific widgets. AWT applications were limited to commonfunctionality that existed on all platforms.

Exam: Applet, Graphics, Events: Mouse, Key, and Focus

Java & Graphical User Interface II. Wang Yang wyang AT njnet.edu.cn

COSC 123 Computer Creativity. Graphics and Events. Dr. Ramon Lawrence University of British Columbia Okanagan

Object-oriented programming in Java (2)

Handling Mouse and Keyboard Events

Programming Languages and Techniques (CIS120)

OOP Assignment V. For example, the scrolling text (moving banner) problem without a thread looks like:

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

Java Mouse Actions. C&G criteria: 5.2.1, 5.4.1, 5.4.2,

Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008

GUI (Graphic User Interface) Programming. Part 2 (Chapter 8) Chapter Goals. Events, Event Sources, and Event Listeners. Listeners

CSE 331 Software Design and Implementation. Lecture 19 GUI Events

Programming Languages and Techniques (CIS120)

CS2110. GUIS: Listening to Events

Programming Languages and Techniques (CIS120)

Chapter 1 GUI Applications

AP CS Unit 12: Drawing and Mouse Events

FirstSwingFrame.java Page 1 of 1

Lecture 5: Java Graphics

CS 335 Graphics and Multimedia. Image Manipulation

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

SAMPLE EXAM Exam 2 Computer Programming 230 Dr. St. John Lehman College City University of New York Thursday, 5 November 2009

Lecture 3: Java Graphics & Events

11/7/12. Discussion of Roulette Assignment. Objectives. Compiler s Names of Classes. GUI Review. Window Events

EXCEPTIONS & GUI. Errors are signals that things are beyond help. Review Session for. -Ankur Agarwal

Programming Languages and Techniques (CIS120)

HW#1: Pencil Me In Status!? How was Homework #1? Reminder: Handouts. Homework #2: Java Draw Demo. 3 Handout for today! Lecture-Homework mapping.

CS2110. GUIS: Listening to Events Also anonymous classes versus Java 8 functions. Anonymous functions. Anonymous functions. Anonymous functions

DM503 Programming B. Peter Schneider-Kamp.

COMPSCI 230. Software Design and Construction. Swing

Java Coordinate System

CSSE 220. Event Based Programming. Check out EventBasedProgramming from SVN

class BankFilter implements Filter { public boolean accept(object x) { BankAccount ba = (BankAccount) x; return ba.getbalance() > 1000; } }

Previously, we have seen GUI components, their relationships, containers, layout managers. Now we will see how to paint graphics on GUI components

CS2110. GUIS: Listening to Events. Anonymous functions. Anonymous functions. Anonymous functions. Checkers.java. mainbox

CS2110. GUIS: Listening to Events

CS 2113 Software Engineering

Packages: Putting Classes Together

Chapter 14: Applets and More

8/23/2014. Chapter Topics. Introduction to Applets. Introduction to Applets. Introduction to Applets. Applet Limitations. Chapter 14: Applets and More

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

Chapter 14: Applets and More

Class 16: The Swing Event Model

JLayeredPane. Depth Constants in JLayeredPane

CSCI 136 Written Exam #2 Fundamentals of Computer Science II Spring 2012

JFrame In Swing, a JFrame is similar to a window in your operating system

Programming Languages and Techniques (CIS120)

Lab 4. D0010E Object-Oriented Programming and Design. Today s lecture. GUI programming in

Graphical User Interface (GUI)

Come & Join Us at VUSTUDENTS.net

CSCI 136 Written Exam #2 Fundamentals of Computer Science II Spring 2015

Final Examination Semester 2 / Year 2012

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

MIT AITI Swing Event Model Lecture 17

public static void main(string[] args) { GTest mywindow = new GTest(); // Title This program creates the following window and makes it visible:

GUI Event Handlers (Part I)

Transcription:

Graphical User Interfaces 2 CSCI 136: Fundamentals CSCI 136: Fundamentals of Computer of Science Computer II Science Keith II Vertanen Keith Vertanen Copyright 2011

Extending JFrame Dialog boxes Overview Getting user input Displaying message or error Drawing shapes and images JPanel Listening for input Mouse Keyboard 2

Approach 1: (last lecture) Extending JFrame main() creates instance of the class Runs instance method, e.g. go() Creates a JFrame and associated GUI elements How Head First Java does it Preferred method Approach 2: Create a class that extends JFrame Constructor handles GUI setup No need to create a JFrame Main program class instantiates the class 3

import javax.swing.*; import java.awt.event.*; public class ButtonCount implements ActionListener private int count = 0; private JButton button; public void actionperformed(actionevent event) count++; button.settext("count = " + count); Approach 1: Create an object and run a method that explicitly creates JFrame public void go() JFrame frame = new JFrame("ButtonCount"); button = new JButton("count = " + count); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.getcontentpane().add(button); frame.setsize(300,300); frame.setvisible(true); button.addactionlistener(this); public static void main(string [] args) ButtonCount gui = new ButtonCount(); gui.go(); 4

import javax.swing.*; import java.awt.event.*; public class ButtonCount2 extends JFrame implements ActionListener private int count = 0; private JButton button; public void actionperformed(actionevent event) count++; button.settext("count = " + count); Approach 2: Make a class that extends JFrame public ButtonCount2() super("buttoncount2"); button = new JButton("count = " + count); setdefaultcloseoperation(jframe.exit_on_close); getcontentpane().add(button); setsize(300,300); setvisible(true); button.addactionlistener(this); public static void main(string [] args) ButtonCount2 gui = new ButtonCount2(); Calls JFrame constructor that takes the window title as a parameter. These are instance methods of JFrame, but we are a JFrame, so no need to put anything before method name. 5

Dialog boxes Dialog boxes Asks a question Or gives an error, information, etc. Typically modal Blocks rest of GUI until closed Displays different icons depending on parameter Constant Java look and feel Windows look and feel JOptionPane.ERROR_MESSAGE JOptionPane.INFORMATION_MESSAGE JOptionPane.WARNING_MESSAGE JOptionPane.QUESTION_MESSAGE JOptionPane.PLAIN_MESSAGE 6

public class NameDialog public static void main(string [] args) String name = JOptionPane.showInputDialog("What is your name?"); JOptionPane.showMessageDialog(null, "Hello there " + name + "!", "Greetings", JOptionPane.PLAIN_MESSAGE); Normally a reference to the JFrame object OK (text entered) OK (no text entered) Cancel 7

public class YesNoDialog public static void main(string [] args) int result = JOptionPane.showConfirmDialog(null, "Are we having fun yet?", "Question", JOptionPane.YES_NO_OPTION); JOptionPane.showMessageDialog(null, "Answer = " + result, "Result", JOptionPane.PLAIN_MESSAGE); No (Windows 7) Lots of other dialog related options, see: http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html#dialogdemo 8

JPanel Panels Purpose 1: Container for other widgets Allows more control of layout Purpose 2: Place to draw lines, circles, images, etc. Like StdDraw Needs to be added to a JFrame Class that extends JPanel, drawing done by: public void paintcomponent(graphics g) Called automatically when needed e.g. window resized Or by calling repaint() on JFrame 9

public class MyDrawPanel extends JPanel public void paintcomponent(graphics g) g.setcolor(color.orange); g.fillrect(20,50,100,100); g.setcolor(new Color(1.0f, 0.0f, 1.0f)); g.drawline(0, 0, 100, 100); g.setcolor(color.blue); g.filloval(200, 100, 50, 25); BufferedImage image = null; try image = ImageIO.read(new File("cat.jpg")); catch (IOException e) e.printstacktrace(); g.drawimage(image, 70, 170, null); public class Panel public static void main(string [] args) JFrame frame = new JFrame(); MyDrawPanel panel = new MyDrawPanel(); frame.getcontentpane().add(borderlayout.center, panel); frame.setsize(400, 400); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setvisible(true); 10

Drawing images Loading a JPG, PNG, GIF: Construct BufferedImage using static method Pass it a File object constructed using filename Will be null on error ImageIO.read can throw IOException Special static method that constructs an object of type BufferedImage. BufferedImage image = ImageIO.read(new File("cat.jpg")); if (image!= null) int width = image.getwidth(); int height = image.getheight(); 11

Drawing on a panel Drawing images In the paintcomponent(graphics g) method g.drawimage(image image, int x, int y, ImageObserver obs) NOTE: (x, y) is the upper-left corner of image Keep the BufferedImage object around Avoid loading from disk each time you need it g.drawimage(image, 0, 0, null); The component (e.g. JFrame, JPanel) that gets notified if image was not completely loaded when drawimage was first called. We can just say null since we always load image from disk before calling. 12

Mouse input MouseListener Watches for mouse entry/exit from component Watches for button events No events if just moving mouse inside component Only if inside the listening component! Method mousepressed(mouseevent) mousereleased(mouseevent) mouseclicked(mouseevent) mouseentered(mouseevent) mouseexited(mouseevent) Purpose After the user presses a mouse button while the cursor is over the component. After the user releases a mouse button after a mouse press over the component. After the user clicks the component (after the user has pressed and released). After the cursor enters bounds of the component. After the cursor exits bounds of the component. 13

Mouse input MouseEvent (x, y) pixel coordinate: (0,0) is upper-left Number of consecutive clicks Button that changed state (pushed, released, clicked) Method int getclickcount() int getx() int gety() Point getpoint() int getbutton() Purpose Number of quick, consecutive clicks (including this event). For example, returns 2 for a double click. Get the x-coordinate at which event occurred Get the y-coordinate at which event occurred Return a Point object containing event location Which button changed state: NOBUTTON, BUTTON1, BUTTON2, or BUTTON3. 14

Mouse input example 1 GUI with a single big text area Add line of text to area on MouseListener event Output event type and mouse (x, y) Events only triggered in JTextArea not JButton JTextArea widget JScrollPane widget that contains the JTextArea widget Ye Olde JButton widget MouseTextBox.java 15

Mouse motion MouseMotionListener Detects movement of mouse inside a component With or without the mouse pressed Method mousemoved(mouseevent) mousedragged(mouseevent) Purpose User is moving the mouse with no mouse button pressed. User is moving the mouse while holding a mouse button down (i.e. a dragging action). Always preceded by call to mousepressed event. 16

Mouse motion example 2 Simple drawing application During MouseDragged event, add Point objects Requires a custom JPanel that draws all the points Override paintcomponent(graphics g) method Also display current mouse (x, y) in upper-left MouseDrawPanel extends JPanel MouseDraw.java MouseDrawPanel.java 17

Keyboard input KeyListener When a key is pressed, released, or typed Typed event only for printable characters Not arrow keys, etc. Numeric key codes for all event types Component must have focus to fire event For custom components (e.g. game drawing panel): Ensure it can accept focus: setfocusable(true) mouseclicked() handler that calls requestfocusinwindow() Or make all other UI widgets not focusable Method keytyped(keyevent) keypressed(keyevent) keyreleased(keyevent) Purpose Called just after user types a Unicode character Called just after the user presses a key Called just after the user releases a key 18

Keyboard input KeyEvent Figure out what was typed or pressed Actual character for typed events Only key code for pressed/released events Method int getkeychar() int getkeycode() int getmodifiersex() Purpose Return Unicode character of event, only use for key typed events. Return the key code associated with event. For example, VK_A = letter A, VK_DOWN = down arrow key. Extended modifier mask for the event, such as whether shift or alt key was down. 19

Keyboard input example Listen for keyboard events Output text about each event JTextArea inside a JScrollPane JPanel forced to always have focus KeyTextBox.java 20

Extending JFrame Summary Constructor sets up the GUI widgets Dialog boxes Collect a response, provide info or error Drawing shapes and images Requires a JPanel Responding to mouse and keyboard events MouseListener for click related events MouseMotionListener for tracking mouse KeyListener for keyboard events 21