Five-Minute Review What are the three data structures realized in the Java Collections Framework? What is the difference between strings and text files?

Slides:



Advertisements
Similar presentations
Chapter 10—Event-driven Programs The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Event-driven Programs C H A P T E R 1.
Advertisements

Graphic User Interfaces Layout Managers Event Handling.
CMSC 341 Building Java GUIs. 09/26/2007 CMSC 341 GUI 2 Why Java GUI Development? Course is about Data Structures, not GUIs. We are giving you the opportunity.
Corresponds with Chapter 12
Nested for Statements The body of a control statement can contain other statements. Such statements are said to be nested. Many applications require nested.
1 GUI Elements in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Scott Grissom, copyright 2006Ch 11: GUI Slide 1 Graphical User Interfaces (Ch 11) Careful design of a graphical user interface is key to a viable software.
Lesson 35: Review of the Java GUI. The JFrame, Container and JButton.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
Java Programming Chapter 10 Graphical User Interfaces.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
Java Software Solutions Lewis and Loftus Chapter 10 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Graphical User Interfaces --
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
Introduction to GUI in Java 1. Graphical User Interface Java is equipped with many powerful,easy to use GUI component such as input and output dialog.
Object Oriented Programming Ders 11: Interfaces Mustafa Emre İlal
Java Programming: Advanced Topics 1 Common Elements of Graphical User Interfaces Chapter 6.
GUI Components and Design Here we add one more component to our programs, JButtons –JButtons can only be inserted into JPanels (or JApplets) –Clicking.
GUI Chapter 10 Graphics context and objects Creating a window based application JFrame, JTextField, JButton Containers and Controls Graphics commands Layout.
Lesson 34: Layering Images with Java GUI. The FlowLayout RECAP.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
– 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.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Layout Managers Arranges and lays out the GUI components on a container.
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
Java Programming Applets. Topics Write an HTML document to host an applet Understand simple applets Use Labels with simple AWT applets Write a simple.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
Intro to Applets. Applet Applets run within the Web browser environment Applets bring dynamic interaction and live animation to an otherwise static HTML.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
1 GUI programming Graphical user interface-based programming Chapter G1 (pages )
Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets.
Interactors Eric Roberts CS 106A February 19, 2010.
Basics of GUI Programming Chapter 11 and Chapter 22.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Graphical User Interface (GUI)
1 Lecture 8: User Interface Components with Swing.
Interactors Eric Roberts CS 106A February 19, 2016.
Introduction to GUI Programming in Java: Frames, Simple Components, and Layouts.
Programming – Lecture 13 Event-driven Programs (Chapter 10) Java event model Responding to mouse events Rubber-banding, dragging objects Keyboard events.
CIS 270—Application Development II Chapter 11—GUI Components: Part I.
GUI.1 Graphical User Interfaces GUIs. GUI.2 The Plan Components Flat Layouts Hierarchical Layouts Designing a GUI Coding a GUI.
GUI Programming in Java Hao Jiang Boston College April, 2009.
Programming – Lecture 13 Event-driven Programs (Chapter 10)
Interactors For examples, references:
CSC 205 Programming II Lecture 5 AWT - I.
CompSci 230 S Programming Techniques
A First Look at GUI Applications
INFSY 547: WEB-Based Technologies
Computer Science 209 Graphics and GUIs.
Graphical User Interface (pronounced "gooey")
Ellen Walker Hiram College
GUI Programming III: Events
Chap 7. Building Java Graphical User Interfaces
Chapter 10—Event-driven Programs
Chapter 13: Advanced GUIs and Graphics
Graphical User Interfaces -- Introduction
CS 106A, Lecture 24 Interactors and NameSurfer
Timer class and inner classes
CS 106A, Lecture 14 Events and Instance Variables
Graphical user interface-based programming
Events, Event Handlers, and Threads
GUI building with the AWT
Advanced GUIs and Graphics
Graphical User Interface
Presentation transcript:

Five-Minute Review What are the three data structures realized in the Java Collections Framework? What is the difference between strings and text files? What does a try/catch block do? What are checked exceptions? Example? What do iterators do? Lists, Sets, Maps Strings: temporary data, reside in RAM; random access. Text files: permanent data, exist in file system (hard disk); sequential access. Creates a scope for catching exceptions. Catch specifies which class (+ subclasses) of exceptions is caught. Exceptions that must be caught (try-catch) or propagated (throws). Example: IOException. Iterate through elements of collections, methods are hasNext() and next()

Programming – Lecture 13 Event-driven Programs (Chapter 10) Java event model Responding to mouse events Rubber-banding, dragging objects Keyboard events GUI control strips Swing interactor hierarchy Text fields Component hierarchy Layout managers Randomness in games

Event Listeners Mouse / keyboard / action events Are asynchronous ListenerExample addMouseListeners() Mouse / keyboard / action events Are asynchronous Event-driven / interactive programs Listener interface for each event type Listener method parameters contain event info

Abstract Window Toolkit import acm.program.*; import java.awt.event.*; public class DrawStarMap extends GraphicsProgram { private static final double STAR_SIZE = 20; public void init() { addMouseListeners(); } public void mouseClicked(MouseEvent e) { GStar star = new GStar(STAR_SIZE); star.setFilled(true); add(star, e.getX(), e.getY()); See https://cs.stanford.edu/people/eroberts/jtf/rationale/ProgramPackage.html for discussion on run() vs. init(): After setting up the standard JApplet component hierarchy, the Program startup code executes the following three steps: Calls the init method to initialize the application. Calls validate on the content pane to ensure that its components are arranged correctly on the screen. Creates a new thread to execute the run method. Although it can be useful to include both methods in a single program, most student programs will define either an init method or a run method, but not both. The init method is used for interactive applications in which the program creates and arranges a set of components and then waits for the user to trigger some action, typically by clicking on a button. The run method is intended for programs that have an independent thread of control unrelated to the actions of the user. Programs that animate a graphical object or require console interaction are usually of this form. The run method in a Program is analogous to the main method in a Java application. The key difference is that the run method is not static and therefore has an object to work with. It can use instance variables in that object and can invoke other methods that are not themselves static. This change alone represents the central advantage of the acm.program package. The rationale behind the init method The February 2005 release of the acm.program package did not describe the init method, although it was there as part of the standard applet paradigm. At the time, we proposed that initialization occur in a constructor for the class. That strategy, however, did not prove viable. The constructor for a program is invoked very early and therefore has no access to any contextual information. Inside the constructor, for example, it is impossible to determine the dimensions of the applet frame, to perform any operations that require a code base such as loading an image, or even to determine whether one is running in an application or applet context. Students found these restrictions very difficult to understand. The init method is invoked after the object has been instantiated and installed in the frame, which means that the program has access to the required information. For discussion on init() vs. run() vs. main(): https://cs.stanford.edu/people/eroberts/jtf/rationale/ProgramPackage.html

addMouseListeners enables mouse-event reporting mouse clicked event Call to mouseClicked Add GStar to canvas DrawStarMap DrawStarMap mouse clicked

Called when user clicks mouse mouseClicked(e) mousePressed(e) mouseReleased(e) mouseMoved(e) mouseDragged(e) Called when user clicks mouse Called when mouse button is pressed Called when mouse button is released Called when user moves mouse Called when mouse is dragged with button down e: MouseEvent

Rubber-Banding public class DrawLines extends GraphicsProgram { private GLine line; public void init() { addMouseListeners(); } public void mousePressed(MouseEvent e) { line = new GLine(e.getX(), e.getY(), e.getX(), e.getY()); add(line); public void mouseDragged(MouseEvent e) { line.setEndPoint(e.getX(), e.getY());

Call addMouseListeners in init mousePressed adds zero-length line Each mouseDragged extends line to new position DrawLines DrawLines mouse pressed mouse dragged mouse dragged mouse dragged mouse dragged mouse dragged mouse dragged mouse dragged

Pressing mouse button selects object Dragging mouse moves selected object Clicking mouse moves selected object to front DragObjects

import acm.graphics.*; import acm.program.*; import java.awt.*; import java.awt.event.*; public class DragObjects extends GraphicsProgram { private GObject gobj; private GPoint last; public void init() { GRect rect = new GRect(100, 100, 150, 100); rect.setFilled(true); rect.setColor(Color.RED); add(rect); GOval oval = new GOval(300, 115, 100, 70); oval.setFilled(true); oval.setColor(Color.GREEN); add(oval); addMouseListeners(); }

public void mousePressed(MouseEvent e) { last = new GPoint(e.getPoint()); gobj = getElementAt(last); } public void mouseDragged(MouseEvent e) { if (gobj != null) { gobj.move(e.getX() - last.getX(), e.getY() - last.getY()); public void mouseClicked(MouseEvent e) { if (gobj != null) gobj.sendToFront();

Keyboard Events Called when user presses key keyPressed(e) keyReleased(e) keyTyped(e) Called when user presses key Use e.getKeyChar() Called when key comes back up Use e.getKeyCode() Called when user types (presses and releases) key e: KeyEvent, indicates key + modifier keys (SHIFT, CTRL, ALT) See https://docs.oracle.com/javase/9/docs/ api/java/awt/event/KeyEvent.html

DragObjects + Arrow Keys public void keyPressed(KeyEvent e) { if (gobj != null) { switch (e.getKeyCode()) { case KeyEvent.VK_UP: gobj.move(0, -1); break; case KeyEvent.VK_DOWN: gobj.move(0, +1); break; case KeyEvent.VK_LEFT: gobj.move(-1, 0); break; case KeyEvent.VK_RIGHT: gobj.move(+1, 0); break; } Must call addKeyListeners in init

GUI – Control Strips CENTER NORTH SOUTH WEST EAST

Please do not press this button again. HitchhikerButton Please do not press this button again. Please do not press this button again. Red

import acm.program.*; import java.awt.event.*; import javax.swing.*; public class HitchhikerButton extends ConsoleProgram { public void init() { add(new JButton("Red"), SOUTH); addActionListeners(); } public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Red")) { print("Please do not press "); println("this button again.");

Swing Interactor Hierarchy JComponent AbstractButton JSlider JLabel JComboBox JTextComponent JButton JToggleButton JTextField acm.gui JCheckBox JRadioButton IntField DoubleField ButtonGroup

Interactive Stoplight GStoplightGUI Red Yellow Green

public class GStoplightGUI extends GraphicsProgram { public void init() { stoplight = new GStoplight(); add(stoplight, getWidth() / 2, getHeight() / 2); add(new JButton("Red"), SOUTH); add(new JButton("Yellow"), SOUTH); add(new JButton("Green"), SOUTH); addActionListeners(); } public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("Red")) { stoplight.setState(Color.RED); } else if (cmd.equals("Yellow")) { stoplight.setState(Color.YELLOW); } else if (cmd.equals("Green")) { stoplight.setState(Color.GREEN); /* Private instance variables */ private GStoplight stoplight;

JTextField Hello, world. Hello, InfProgOO. HelloGUI Name InfProgOO

import acm.program.*; import java.awt.event.*; import javax.swing.*; public class HelloGUI extends ConsoleProgram { public void init() { nameField = new JTextField(10); add(new JLabel("Name"), SOUTH); add(nameField, SOUTH); nameField.addActionListener(this); } public void actionPerformed(ActionEvent e) { if (e.getSource() == nameField) { println("Hello, " + nameField.getText()); private JTextField nameField;

Each Container has Layout Manager Component Hierarchy Component Container Panel JComponent GCanvas IOConsole Window Applet JPanel Frame Swing interactor classes JApplet JFrame Program Each Container has Layout Manager

public class FlowLayoutSlider extends Program { public void init() { setLayout(new FlowLayout()); add(new JLabel("Small")); add(new JSlider(0, 100, 50)); add(new JLabel("Large")); } FlowLayoutSlider Small Large FlowLayoutSlider Small Large

setLayout(new GridLayout(2, 3)); for (int i = 1; i <= 6; i++) { public void init() { setLayout(new GridLayout(2, 3)); for (int i = 1; i <= 6; i++) { add(new JButton("Button " + i)); } GridLayoutExample Button 1 Button 2 Button 3 Button 4 Button 5 Button 6 GridLayoutExample Button 1 Button 2 Button 3 Button 4 Button 5 Button 6

TemperatureConverter F -> C Degrees Fahrenheit C -> F Degrees Celsius 32 1 212 10 100

TemperatureConverter public class TemperatureConverter extends Program { public void init() { setLayout(new TableLayout(2, 3)); fahrenheitField = new IntField(32); fahrenheitField.setActionCommand("F -> C"); fahrenheitField.addActionListener(this); celsiusField = new IntField(0); celsiusField.setActionCommand("C -> F"); celsiusField.addActionListener(this); add(new JLabel("Degrees Fahrenheit")); add(fahrenheitField); add(new JButton("F -> C")); add(new JLabel("Degrees Celsius")); add(celsiusField); add(new JButton("C -> F")); addActionListeners(); } Note that giving the same action command "F -> C" to both fahrenheitField and the JButton means that the same ActionCommand is performed for both TemperatureConverter F -> C Degrees Fahrenheit C -> F Degrees Celsius 32 1 212 10 100 page 1 of 2 skip code

/* Listens for a button action */ public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("F -> C")) { int f = fahrenheitField.getValue(); int c = GMath.round((5.0 / 9.0)*(f - 32)); celsiusField.setValue(c); } else if (cmd.equals("C -> F")) { int c = celsiusField.getValue(); int f = GMath.round((9.0 / 5.0) * c + 32); fahrenheitField.setValue(f); } /* Private instance variables */ private IntField fahrenheitField; private IntField celsiusField; page 2 of 2 skip code

Calculator 25 42 2 1 17 7 8 9 + 4 5 6 – 1 2 3 x C = /

setLayout(new TableLayout(5, 4)); display = new CalculatorDisplay(); public void init() { setLayout(new TableLayout(5, 4)); display = new CalculatorDisplay(); add(display, "gridwidth=4 height=" + BUTTON_SIZE); addButtons(); addActionListeners(); } private void addButtons() { String constraint = "width=" + BUTTON_SIZE + " height=" + BUTTON_SIZE; add(new DigitButton(7), constraint); add(new DigitButton(8), constraint); add(new DigitButton(9), constraint); add(new AddButton(), constraint); add(new DigitButton(4), constraint); add(new DigitButton(5), constraint); add(new DigitButton(6), constraint); add(new SubtractButton(), constraint); ... Setting up the Calculator Display

TableLayout Constraints gridwidth=columns or gridheight=rows Indicates that this table cell should span the indicated number of columns or rows. width=pixels or height=pixels The width specification indicates that the width of this column should be at least the specified number of pixels. The height specification similarly indicates the minimum row height. weightx=weight or weighty=weight If the total size of the table is less than the size of its enclosure, TableLayout will ordinarily center the table in the available space. If any of the cells, however, are given nonzero weightx or weighty values, the extra space is distributed along that axis in proportion to the weights specified. fill=fill Indicates how component in this cell should be resized if its preferred size is smaller than cell size. Legal values are NONE, HORIZONTAL, VERTICAL, and BOTH, indicating the axes along which stretching should occur; default is BOTH. anchor=anchor If a component is not being filled along a particular axis, the anchor specification indicates where component should be placed in its cell. Default value is CENTER, but you may also use any of the standard compass directions (NORTH, SOUTH, EAST, WEST, NORTHEAST, NORTHWEST, SOUTHEAST, or SOUTHWEST).

Resizing, Component Listeners MovingRect Setting up the Calculator Display public class MovingRect extends Program { public void init() { MyCanvas canvas = new MyCanvas(); add(canvas); }

class MyCanvas extends GCanvas implements ComponentListener { public MyCanvas() { addComponentListener(this); rect = new GRect(BOX_WIDTH, BOX_HEIGHT); rect.setFilled(true); } public void update() { removeAll(); add(rect, (getWidth() - BOX_WIDTH) / 2, (getHeight() - BOX_HEIGHT) / 2); Setting up the Calculator Display

public void componentResized( ComponentEvent e) { update(); } public void componentHidden( ComponentEvent e) { } public void componentMoved( public void componentShown( private GRect rect; private static final double BOX_WIDTH = 200; private static final double BOX_HEIGHT = 100; Setting up the Calculator Display

Summary I Events: user actions that happen outside of normal sequential program flow Java programs respond to events by designating objects as listeners to particular event types Event listeners must implement interface defined in java.awt.event (MouseListener, ...) Program class implements these interfaces by supplying empty methods, e.g., mouseClicked – which are overridden by own methods The init method specifies initialization code, e.g. addMouseListeners Randomness in games

Summary II javax.swing and acm.gui define classes whose instances are interactors To determine which button caused an action event e, can call e.getSource, which returns object that caused the event, or e.getActionCommand, which returns a string Easiest way to add interactors is to add them to a control bar along borders of program window Arranging interactors in interior usually requires layout manager The TableLayout manager allows to specify constraints on layout Randomness in games