AP CS Unit 11: Graphics and Events

Similar documents
Advanced Java Unit 6: Review of Graphics and Events

AP CS Unit 12: Drawing and Mouse Events

Class 16: The Swing Event Model

MIT AITI Swing Event Model Lecture 17

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

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

PIC 20A GUI with swing

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Name: Checked: Learn about listeners, events, and simple animation for interactive graphical user interfaces.

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

17 GUI API: Container 18 Hello world with a GUI 19 GUI API: JLabel 20 GUI API: Container: add() 21 Hello world with a GUI 22 GUI API: JFrame: setdefau

Window Interfaces Using Swing Objects

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

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages.

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

First Name: AITI 2004: Exam 2 July 19, 2004

Window Interfaces Using Swing Objects

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!

Part I: Learn Common Graphics Components

Building a GUI in Java with Swing. CITS1001 extension notes Rachel Cardell-Oliver

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

Course Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski

Hanley s Survival Guide for Visual Applications with NetBeans 2.0 Last Updated: 5/20/2015 TABLE OF CONTENTS

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

G51PRG: Introduction to Programming Second semester Applets and graphics

Unit 7: Event driven programming

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

1.00 Lecture 14. Lecture Preview

Class 14: Introduction to the Swing Toolkit

First Name: AITI 2004: Exam 2 July 19, 2004

Graphical User Interface (GUI)

We are on the GUI fast track path

GUI Forms and Events, Part II

Java Swing. based on slides by: Walter Milner. Java Swing Walter Milner 2005: Slide 1

Java Programming Lecture 6

An array is a type of variable that is able to hold more than one piece of information under a single variable name.

What Is an Event? Some event handler. ActionEvent. actionperformed(actionevent e) { }

Queen s University Faculty of Arts and Science School of Computing CISC 124 Final Examination December 2004 Instructor: M. Lamb

SINGLE EVENT HANDLING

Java Swing. Recitation 11/(20,21)/2008. CS 180 Department of Computer Science, Purdue University

Swing from A to Z Some Simple Components. Preface

User interfaces and Swing

CS Exam 1 Review Suggestions

Example: Building a Java GUI

Lecture 3: Java Graphics & Events

Example: Building a Java GUI

Graphical User Interfaces. Comp 152

Assignment 2. Application Development

FirstSwingFrame.java Page 1 of 1

Part 3: Graphical User Interface (GUI) & Java Applets

CS108, Stanford Handout #22. Thread 3 GUI

CS 251 Intermediate Programming GUIs: Event Listeners

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

Goals. Lecture 7 More GUI programming. The application. The application D&D 12. CompSci 230: Semester JFrame subclass: ListOWords

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

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

Lecture 28. Exceptions and Inner Classes. Goals. We are going to talk in more detail about two advanced Java features:

H212 Introduction to Software Systems Honors

Graphics User Defined Forms, Part I

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

Packages: Putting Classes Together

CSIS 10A Assignment 7 SOLUTIONS

Adding Buttons to StyleOptions.java

To gain experience using GUI components and listeners.

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

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

Information Technology for Industrial Engineers 15 November ISE 582: Information Technology for Industrial Engineers

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

Section Basic graphics

Building Graphical User Interfaces. GUI Principles

Introduction. Introduction

Java Interfaces Part 1 - Events Version 1.1

COMP-202 Unit 10: Basics of GUI Programming (Non examinable) (Caveat: Dan is not an expert in GUI programming, so don't take this for gospel :) )

University of Cape Town Department of Computer Science. Computer Science CSC117F Solutions

Java Help Files. by Peter Lavin. May 22, 2004

CS 106A, Lecture 23 Interactors and GCanvas

2IS45 Programming

Introduction This assignment will ask that you write a simple graphical user interface (GUI).

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

Programming graphics

CS 251 Intermediate Programming GUIs: Components and Layout

Graphical Applications

UI Software Organization

COMP Assignment #10 (Due: Monday, March 11:30pm)

Lecture 5: Java Graphics

Chapter 12 GUI Basics

Graphic User Interfaces. - GUI concepts - Swing - AWT

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

Example 3-1. Password Validation

Handout 14 Graphical User Interface (GUI) with Swing, Event Handling

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Graphical User Interface (GUI)

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

Chapter 7: A First Look at GUI Applications

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

Swing/GUI Cheat Sheet

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing

Chapter 6 Using Objects

DEMYSTIFYING PROGRAMMING: CHAPTER FOUR

Transcription:

AP CS Unit 11: Graphics and Events This packet shows how to create programs with a graphical interface in a way that is consistent with the approach used in the Elevens program. Copy the following two classes and run the program. public class RunMyFrame1 { public static void main(string[] args) { MyFrame1 mf = new MyFrame1(); mf.display(); import javax.swing.jframe; import javax.swing.jpanel; import java.awt.color; import java.awt.dimension; import java.awt.eventqueue; public class MyFrame1 extends JFrame { public MyFrame1(){ setdefaultcloseoperation( EXIT_ON_CLOSE ); settitle( "HEY" ); JPanel jp = new JPanel(); jp.setbackground( Color.RED ); jp.setpreferredsize( new Dimension( 300, 200 ) ); jp.setlayout( null ); getcontentpane().add( jp ); pack(); A JFrame object is the window (title bar and borders). A JPanel object is added to the JFrame and fills the area under the title bar. public void display() { EventQueue.invokeLater(new Runnable() { public void run() { setvisible(true); ); All of our previous programs ran on the main thread. When using Swing classes, all code that modifies the user interface must/should run in the event dispatching thread. For an explanation about the code in the display method. http://stackoverflow.com/questions/4908824/explain-what-the-following-code-does 1

Ex 1. Create a program that displays a green background that is 300 pixels long and 100 pixels wide. Make the frame non-resizable. This method is in a superclass of the JFrame class. JButtons and JLabels and Positioning. Copy and run the following program. It consists of two files: RunDemoButton and DemoButtonFrame. public class RunDemoButton { public static void main(string[] args) { DemoButtonFrame f = new DemoButtonFrame(); f.display(); import javax.swing.*; import java.awt.*; public class DemoButtonFrame extends JFrame { public DemoButtonFrame(){ setdefaultcloseoperation(exit_on_close); settitle( "Button!" ); JPanel jp = new JPanel(); jp.setbackground( Color.WHITE ); jp.setpreferredsize( new Dimension( 150, 150 ) ); jp.setlayout( null ); JButton button = new JButton( "Click Here" ); button.setbounds( 25, 75, 100, 50 ); // x, y coordinates of the upper left // followed by width, height (all in pixels) jp.add( button ); getcontentpane().add( jp ); pack(); public void display() { EventQueue.invokeLater(new Runnable() { public void run() { setvisible(true); ); What is this? jp.setlayout( null ); Java typically uses Layout Manager objects that are responsible for managing the positions and sizes of different components. For example, the GridLayout manager will keep all components the same size and in a grid arrangement even if the frame/panel is resized. Calling the setlayout method with an argument of null means there is no layout manager and we are responsible for positioning everything. Use the setbounds method to position and size any components added to a JPanel. 2

The Coordinate System used by java is similar (but not identical) to the one used in algebra and geometry. Each panel has its own coordinate system where the upper-left hand corner is the origin. The top edge of the panel is the positive x- axis and the left edge of the panel is the positive (not the negative) y-axis. Coordinates can have negative values. -x -y +x +y Ex2. Create the program shown to the right. - The panel is initially 300 pixels wide and 400 pixels high. - Button 1 is 100 by 100 pixels in size and has an orange background. - Button 2 is 200 by 200 pixels in size and has a magenta background. - The buttons should be positioned as shown. Button 2 is initially centered in the panel though if the panel is resized the panel does not stay centered. After you complete the program, experiment with your code to answer the following questions. a) Can the x and/or coordinates be negative? b) What happens if the height or width of the button is not big enough to display the text? c) What happens if the width and/or height is set to a negative value? d) What happens if you position the buttons so that they overlap? Which one is displayed in front of the other? Does that order always stay that way? 3

Here s a figure that shows some of the subclasses of JComponent. Any method that JComponent has, such as setbackground, are inherited by JButton, JPanel, and so on. JComponent AbstractButton JPanel JLabel JTextComponent JButton JTextField Ex 3. Create the program shown to the right. There are two JLabels, two JTextFields, and one JButton inside one JPanel (which has a yellow background). You pick the sizes and positions to get your program to look as close to this as possible. Ex 4. Write a program that displays 10 panels inside of a white panel that is inside the frame. The 10 panels should be randomly positioned and have random widths and heights and random colors. You can create a random color using the following color. int red = (int)(256*math.random()); int green = (int)(256*math.random()); int blue = (int)(256*math.random()); Color c = new Color( red, green, blue ); 4

Events. An event can broadly be defined as something that happens: For example, a mouse is clicked or a window is resized. In the java event model, there are generally three objects involved. Event Source. This is the object that was effected. For example, the button that is clicked or the window that was resized. Event Object. This object contains information about the event. For example, a MouseEvent contains information about where the mouse was at the time of the event. Event Listener. This is the object that is responsible for responding to the event. Copy and run the following program. public class RunDemoAction { public static void main(string[] args) { DemoEventFrame f = new DemoEventFrame (); f.display(); import javax.swing.*; import java.awt.*; import java.awt.event.*; public class DemoEventFrame extends JFrame { private JLabel lbl = new JLabel( "Random Number" ); private JButton btneven = new JButton( "Display Random Even Number" ); private JButton btnodd = new JButton( "Display Random Odd Number" ); public DemoEventFrame (){ setdefaultcloseoperation(exit_on_close); settitle( "Buttons That Work" ); JPanel jp = new JPanel(); jp.setbackground( Color.WHITE ); jp.setpreferredsize( new Dimension( 250, 150 ) ); jp.setlayout( null ); ButtonListener spy = new ButtonListener(); btneven.addactionlistener( spy ); btnodd.addactionlistener( spy ); btneven.setbounds( 10, 10, 230, 30 ); btnodd.setbounds( 10, 60, 230, 30 ); lbl.setbounds( 10, 110, 150, 30 ); jp.add( btneven ); jp.add( btnodd ); jp.add( lbl ); getcontentpane().add( jp ); pack(); Something New! spy is the object that will respond when either button is clicked. 5

public void display() { EventQueue.invokeLater(new Runnable() { public void run() { setvisible(true); ); private class ButtonListener implements ActionListener{ public void actionperformed(actionevent e) { if (e.getsource().equals(btneven)) { int num = (int)( 5*Math.random() ) + 1; num = 2 * num; lbl.settext( num + "" ); // why is "" required here? else { // must be btnodd lbl.settext( "I should write this" ); ButtonListener is an inner class. It is declared inside the DemoEventFrame class. Why do this? Because: 1) The only class that ever uses this ButtonListener class is the DemoEventFrame class. By limiting its scope, no one else can use it. 2) An inner class can directly access the private instance variables, and methods, of its enclosing class. After you get this program running, modify the actionperformed method so that when the use clicks the Odd Button that a random odd number between 1 and 9 appears. In the above program, there are two Event Sources btneven and btnodd. When they are clicked, the JVM generates ActionEvent objects which are sent to the one EventListener object that we instantiated. To link the Event Sources to an Event Listener, we used these statements btneven.addactionlistener( spy ); btnodd.addactionlistener( spy ); The addactionlistener has one parameter of type ActionListener. ActionListener is an interface with one method: actionperformed. 6

Ex 5. Create the program to the right. There are three JLabels, two JTextFields, and two JButtons. You will need to use the gettext and settext methods. To convert a string into an integer use Integer.parseInt. Ex 6. Every time you click the button, the background color of the panel changes to another random color. Use the code from exercise 4 to generate the random color. Ex 7. Create the program shown above. There is an array of 26 buttons, a label, and another button. Whenever one of the 26 top buttons are pressed, that letter is displayed in the label. The figures show the panel after five buttons have been pressed. Click the bottom button to clear the label. Here s an outline for the loop that creates the 26 buttons. ButtonListener ear = new ButtonListener(); for ( int k = 0; k < 26; k++ ){ char ch = (char)(k + 65); String letter = ch + ""; // create the button // calculate the x and y coordinates based on the value of k, then call setbounds // add the action listener // add the button to the panel In the actionperformed method you may want to do this: JButton b = (JButton) e.getsource(); // must cast because getsource returns an Object String text = b.gettext(); 7

Simple Animation. Copy and run the following program. This uses a Timer object to generate action events at regular intervals. Explanations for certain statements can be found on the next page. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class DemoTimerFrame extends JFrame { private JLabel lbl = new JLabel( "0" ); private JButton btnstart = new JButton( "Start" ); private JButton btnstop = new JButton( "Stop" ); private JPanel jp = new JPanel(); private int count = 0; private javax.swing.timer timer; A public DemoTimerFrame(){ setdefaultcloseoperation(exit_on_close); settitle( "Timer" ); jp.setbackground( Color.WHITE ); jp.setpreferredsize( new Dimension( 150, 150 ) ); jp.setlayout( null ); btnstart.setbounds( 10, 5, 130, 30 ); lbl.setbounds( 60, 50, 90, 30 ); Font f = new Font("SansSerif", Font.BOLD, 36); lbl.setfont( f ); btnstop.setbounds( 10, 100, 130, 30 ); btnstart.addactionlistener( new Respond() ); btnstop.addactionlistener( new Respond() ); B timer = new javax.swing.timer( 100, new TimerListener() ); jp.add( btnstart ); jp.add( lbl ); jp.add( btnstop ); getcontentpane().add( jp ); pack(); C public void display() { EventQueue.invokeLater(new Runnable() { public void run() { setvisible(true); ); // continued on the next page 8

private class TimerListener implements ActionListener { public void actionperformed(actionevent e) { count++; lbl.settext( count + "" ); private class Respond implements ActionListener{ public void actionperformed(actionevent e) { if ( e.getsource().equals( btnstart ) ) timer.start(); else timer.stop(); D E Explanations. A private javax.swing.timer timer; Java has two different Timer classes; one is in the java.util package and one is in the javax.swing package. This syntax makes it clear to the compiler that we want the Timer class from the javax.swing package. We will not use the other Timer class. If you are curious why Java has two Timer classes: http://stackoverflow.com/questions/15556646/why-are-there-twotimer-classes-in-javaone-under-javax-swing-one-under-java-ut B Font f = new Font("SansSerif", Font.BOLD, 36); lbl.setfont( f ); This demonstrates how to change the font type of a JLabel. You could use the same approach on the buttons. Look up the Font class for more information. C new javax.swing.timer( 100, new TimerListener() ); The constructor for the Timer class has two parameters. First, the amount of time, in milliseconds, between events. Second, an object that will respond to the Action Events that a Timer object generates. D private class TimerListener implements ActionListener A Timer object generates Action events at regular intervals therefore the object that responds to those events must implement the ActionListener interface. I used a separate inner class for the timer events because I didn t think the same object should handle action events from buttons and action events from a timer. E timer.start(); timer.stop(); The start method causes the Timer object to start generating action events at the specified interval. The stop method causes the Timer object to stop generating action events. 9

Ex 8. Create the program shown to the right. Start and stop the timer with the two buttons. Whenever the timer generates an action event, the program should generate three random colors: - one color for the background of the panel - one color for the background of the two buttons - one color for the text on the buttons (use the setforeground method) Also, change the font type on the buttons and use the following method to the class that handles the action events from the timer. private Color random(){ int red = (int)(256*math.random()); int green = (int)(256*math.random()); int blue = (int)(256*math.random()); return new Color( red, green, blue ); Ex 9. Create a program which simulates a simple slot machine. The idea is the user starts with 100 tokens. If they get three matching numbers then they win 30 more tokens. If any two numbers match they get 10 tokens. If the numbers are all different, they lose 10 tokens. Comments/Hints. There are two buttons and four labels. Create an instance variable that represents how many tokens the user currently has. Clicking the Start button causes the timer object to start generating action events. The object that responds to the timer generated action events should display random integers (1 to 7 inclusive) in the labels. When the Stop button is clicked, stop the timer, determine if the user won or lost, update the number of tokens, and display an appropriate message. If the user clicks on the Stop button at the very start of the program, before any numbers have been displayed in the labels, there will be an error. The number of tokens may go negative. 10

Ex 10. Write a program that displays a message that scrolls across the window from the left to the right. When it is completely off the right side, it should slide in from the right. Comments/Hints. There is one JLabel in the JPanel; there are no JButtons objects. The animations should start as soon as the program starts. The animation does not stop. If the size of the window is changed, the program should still work correctly. Create an instance variable that represents the x coordinate of the label s upper left hand corner. Every time the timer fires off an action event, increase the x coordinate of the label s upper left hand corner. Then call setbounds again. There is a method, getwidth(), that returns the current width of a component. Use this to figure out if the label has gone past the right side of the panel. If so, reset the x coordinate so that the label will reappear on the left side. Ex 11. In this program that is an array of labels. Each label contains a single letter. As soon as the program starts these letters start dropping down and then reappear at the top of the window and drop again. Each letter drops at its own random speed. Comments/Hints. Your array of labels should have a length of at least five elements. Create an array of ints to store the current y coordinate of each label s corner. Create a second array of ints that stores random numbers between 5 and 10. This array should be the same length as the first two arrays. Every time the timer fires off an action event, increase the y coordinate of the label s upper left hand corner using the random numbers in the second array of ints. Then call setbounds again. There is a method, getheight(), that returns the current width of a component. Use this to figure out if a label has gone below the bottom of the panel. If so, reset the y coordinate so that the label will reappear on the left side. 11