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

Graphical User Interfaces

H212 Introduction to Software Systems Honors

Computer Science 210: Data Structures. Intro to Java Graphics

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

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

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

GUI in Java TalentHome Solutions

CS 251 Intermediate Programming GUIs: Event Listeners

Java Foundations John Lewis Peter DePasquale Joe Chase Third Edition

GUI Event Handlers (Part II)

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

G51PRG: Introduction to Programming Second semester Applets and graphics

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

The AWT Event Model 9

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

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

Introduction to the JAVA UI classes Advanced HCI IAT351

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

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

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

Java GUI Design: the Basics

More about JOptionPane Dialog Boxes

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

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

(Incomplete) History of GUIs

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

Event Driven Programming

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

Unit 7: Event driven programming

Handling Mouse and Keyboard Events

Object-Oriented Programming in Java

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

Graphic User Interfaces. - GUI concepts - Swing - AWT

Programming Languages and Techniques (CIS120)

Java for Interfaces and Networks (DT3010, HT10)

CSE 331 Software Design & Implementation

Lecture 19 GUI Events

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

Programming Languages and Techniques (CIS120)

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

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

User interfaces and Swing

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

CS2110. GUIS: Listening to Events

COMPSCI 230. Software Design and Construction. Swing

CS 2113 Software Engineering

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

JLayeredPane. Depth Constants in JLayeredPane

Packages: Putting Classes Together

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Lecture 3: Java Graphics & Events

Chapter 1 GUI Applications

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

CSE 331 Software Design and Implementation. Lecture 19 GUI Events

Programming Languages and Techniques (CIS120)

DM503 Programming B. Peter Schneider-Kamp.

Lecture 5: Java Graphics

Java Coordinate System

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

Programming Languages and Techniques (CIS120)

Object-oriented programming in Java (2)

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

Chapter 14: Applets and More

Programming Languages and Techniques (CIS120)

Introduction to Java. Nihar Ranjan Roy.

Overview. Applets. A Java GUI inside your browser! Important methods Drawing images Playing audio Getting input parameters Double buffering

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

BM214E Object Oriented Programming Lecture 13

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

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

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

L4,5: Java Overview II

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

Advanced Java Programming (17625) Event Handling. 20 Marks

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!

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science

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

JRadioButton account_type_radio_button2 = new JRadioButton("Current"); ButtonGroup account_type_button_group = new ButtonGroup();

CS2110. GUIS: Listening to Events

(listener)... MouseListener, ActionLister. (adapter)... MouseAdapter, ActionAdapter. java.awt AWT Abstract Window Toolkit GUI

FirstSwingFrame.java Page 1 of 1

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

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

The init() Method. Browser Calling Applet Methods

3 Events and Listeners

2IS45 Programming

Windows and Events. created originally by Brian Bailey

AP CS Unit 12: Drawing and Mouse Events

Class 16: The Swing Event Model

PESIT Bangalore South Campus

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

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.

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

3 Combining Widgets to create Graphical User Interfaces

Lecture 9. Lecture

Transcription:

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

Extending JFrame Dialog boxes Ge?ng user input Overview Displaying message or error Listening for input Mouse Keyboard Java images 2

Extending JFrame Method 1: Class's main method creates an instance of the class Runs an instance method (e.g. go) that creates a JFrame and associated GUI elements How Head First Java does it Method 2: Create a class that extends JFrame Constructor of class handles GUI setup Class is itself a JFrame, not need to create one Main program class instanoates 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); 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); Op#on 1: Create an object and run a method that explicitly creates JFrame 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); public ButtonCount2() super("buttoncount2"); Op#on 2: Make a class that extends JFrame 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(); 5

Dialog boxes Ask the user a quesoon Dialog boxes Or give the user an error, informaoon, etc. Typically modal Blocks rest of GUI unol 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 reference to the JFrame object OK OK 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 Lots of other dialog related opoons, see: h^p://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html#dialogdemo 8

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

Mouse input MouseEvent x- and y- coordinate, (0,0) is upper- led Number of quick, consecuove clicks Which bu^on changed state (pushed, released, clicked) Method int getclickcount() int getx() int gety() Point getpoint() int getbutton() Purpose Number of quick, consecuove 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 locaoon Which bu^on changed state: NOBUTTON, BUTTON1, BUTTON2, or BUTTON3. 10

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) Note: events only triggered in JTextArea not JButton JTextArea widget JScrollPane widget that contains the JTextArea widget Ye Olde JButton widget MouseTextBox.java 11

Mouse mooon 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 bu^on pressed. User is moving the mouse while holding a mouse bu^on down (i.e. a dragging acoon). Always preceded by call to mousepressed event. 12

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

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 ader user types a Unicode character Called just ader the user presses a key Called just ader the user releases a key 14

Keyboard input KeyEvent Figure out what the user typed or pressed Actual character to 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 = le^er A, VK_DOWN = down arrow key. Extended modifier mask for the event, such as whether shid or alt key was down. 15

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

Drawing images Loading a JPG, PNG, GIF: Construct an ImageIcon object Pass it the filename Convert to an Image object for drawing Width and height will be - 1 on error Image image = new ImageIcon("cat.jpg").getImage(); int width = image.getwidth(this); int height = image.getheight(this); The component (e.g. JFrame, JPanel) that image is being drawn on. 17

Drawing images Drawing on a panel In the paintcomponent(graphics g) method g.drawimage(image img, int x, int y, ImageObserver obs) NOTE: (x, y) is the upper- led corner of the image Keep the Image object around So you don't have to keep loading from disk using the ImageIcon constructor g.drawimage(img, 0, 0, this); The component (e.g. JFrame, JPanel) that image is being drawn on. 18

Programming acovity Create an image slideshow GUI Loads images specified on command line Outputs height/width, ignore bogus files Cycles between images every second % java ShowImages cat.jpg frog.jpg dog.jpg bogus.jpg cat.jpg [240 x 160] frog.jpg [240 x 118] dog.jpg [240 x 228] 19

Summary Extending JFrame Constructor sets up the GUI widgets Dialog boxes Collect a string or response to several bu^ons Can just provide informaoon or error message Responding to mouse events MouseListener handler for click- related events MouseMotionListener for tracking mouse coordinates Responding to keyboard events Make sure listening component can and does have focus Loading and display images 20