AP CS Unit 12: Drawing and Mouse Events

Similar documents
AP CS Unit 11: Graphics and Events

Advanced Java Unit 6: Review of Graphics and Events

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

TWO-DIMENSIONAL FIGURES

2IS45 Programming

PIC 20A GUI with swing

G51PRG: Introduction to Programming Second semester Applets and graphics

OBJECT ORIENTED PROGRAMMING. Course 8 Loredana STANCIU Room B613

CSIS 10A Assignment 14 SOLUTIONS

Practice Midterm 1. Problem Points Score TOTAL 50

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

Lecture 3: Java Graphics & Events

Name CS/120 Sample Exam #1 -- Riley. a) Every program has syntax, which refers to the form of the code, and, which refers to the meaning of the code.

Unit 7: Event driven programming

Assignment 2. Application Development

Practice Midterm 1 Answer Key

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

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

Designing Classes Part 2

cs Java: lecture #5

CS 201 Advanced Object-Oriented Programming Lab 10 - Recursion Due: April 21/22, 11:30 PM

User interfaces and Swing

Appendix F: Java Graphics

Graphics Applets. By Mr. Dave Clausen

Computer Science II - Test 2

Appendix F: Java Graphics

Lecture 5: Java Graphics

Graphic User Interfaces. - GUI concepts - Swing - AWT

Here is a list of a few of the components located in the AWT and Swing packages:

Example: Building a Java GUI

Dr. Hikmat A. M. AbdelJaber

Graphical User Interfaces 2

Example: Building a Java GUI

Class 16: The Swing Event Model

Control Statements: Part Pearson Education, Inc. All rights reserved.

H212 Introduction to Software Systems Honors

CSCI 053. Week 5 Java is like Alice not based on Joel Adams you may want to take notes. Rhys Price Jones. Introduction to Software Development

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

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

Garfield AP CS. Graphics

More about GUIs GEEN163

public void mouseexited (MouseEvent e) setminute(getminute()+increment); 11.2 public void mouseclicked (MouseEvent e) int x = e.getx(), y = e.gety();

Graphics Applets. By Mr. Dave Clausen

CSC System Development with Java Introduction to Java Applets Budditha Hettige

AplusBug dude = new AplusBug(); A+ Computer Science -

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

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

Building Java Programs

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

CS 315 Software Design Homework 1 First Sip of Java Due: Sept. 10, 11:30 PM

CS2110. GUIS: Listening to Events

IT101. Graphical User Interface

Programmierpraktikum

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

Building Java Programs

CS/120 Final Exam. Name

(0,0) (600, 400) CS109. PictureBox and Timer Controls

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

9. APPLETS AND APPLICATIONS

Graphical User Interface (GUI)

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!

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

CSE115 Lab 4 Fall 2016

Block I Unit 2. Basic Constructs in Java. AOU Beirut Computer Science M301 Block I, unit 2 1

Building Java Programs

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

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

2. (True/False) All methods in an interface must be declared public.

Lab 10: Inheritance (I)

Advanced Internet Programming CSY3020

FirstSwingFrame.java Page 1 of 1

Please show all of your work.

CS 201 Advanced Object-Oriented Programming Lab 1 - Improving Your Image Due: Feb. 3/4, 11:30 PM

MIT AITI Swing Event Model Lecture 17

Inheritance. One class inherits from another if it describes a specialized subset of objects Terminology:

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

Topic Notes: Java and Objectdraw Basics

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

In this lecture we will briefly examine a few new controls, introduce the concept of scope, random numbers, and drawing simple graphics.

ming 3 Resize the Size to [700, 500]. Note that the background containers in the program code: reference the then under () { 153, 255, 0 ) );

Chapter. We've been using predefined classes. Now we will learn to write our own classes to define objects

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

Chapter 24. Graphical Objects The GraphicalObject Class

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

Java Coordinate System

PESIT Bangalore South Campus

Programming: You will have 6 files all need to be located in the dir. named PA4:

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

Graphical User Interface (GUI)

Final Examination Semester 2 / Year 2011

Using the API: Introductory Graphics Java Programming 1 Lesson 8

UI Software Organization

1.00/1.001 Introduction to Computers and Engineering Problem Solving Fall (total 7 pages)

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

CompSci 125 Lecture 17. GUI: Graphics, Check Boxes, Radio Buttons

@Override public void start(stage primarystage) throws Exception { Group root = new Group(); Scene scene = new Scene(root);

Programming Language Concepts: Lecture 8

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

Transcription:

AP CS Unit 12: Drawing and Mouse Events A JPanel object can be used as a container for other objects. It can also be used as an object that we can draw on. The first example demonstrates how to do that. Copy these files and run them. The first file simply contains the main method which instantiates the frame and displays it. The MyFrame1 class looks very similar to the classes that we wrote in Unit 11. However, one difference is that we are adding a DemoPanel object. The DemoPanel class extends JPanel and is on the next page. public class RunDemo1 { 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.LIGHT_GRAY ); jp.setpreferredsize( new Dimension( 300, 250 ) ); jp.setlayout( null ); DemoPanel d = new DemoPanel( Color.WHITE); d.setbounds( 5, 50, 290, 150 ); jp.add( d ); getcontentpane().add( jp ); pack(); public void display() { EventQueue.invokeLater(new Runnable() { public void run() { setvisible(true); ); 1

import javax.swing.*; import java.awt.*; public class DemoPanel extends JPanel { public DemoPanel( Color c ) { setbackground( c ); setborder( BorderFactory.createLineBorder(Color.BLACK ) ); @Override public void paintcomponent( Graphics g ) { super.paintcomponent( g ); int w = getwidth(); int h = getheight(); g.setcolor( Color.GREEN ); g.drawrect( 50, 10, w/2, 4*h/5 ); g.setcolor( Color.BLUE ); g.filloval( 0, h/2, w, h/4 ); Some of the Graphics methods are described below. Note: the panel has its own coordinate plane. Its origin is in its upper left hand corner. Who calls the paintcomponent method?!? In the above example, we override the paintcomponent method but there are no statements in our program that actually call this method. So how is it being called? The JVM executes our program and every time certain events occur (such as when the program is loaded or the frame is resized), the JVM calls the paintcomponent for each component. Some Methods of the Graphics Class void drawline( int x1, int y1, int x2, int y2 ) Draws a line from (x1, y1) to (x2, y2) void drawoval( int x, int y, int width, int height ) Every oval can be enclosed in a rectangle. x and y specify the coordinates of the upper left hand corner. void drawpolygon(int[] x, int[] y, int n) Draws a polygon where the vertices are (x[0],y[0]), (x[1],y[1]), to (x[n-1],y[n-1]). The arrays should have a length of at least three and n should be less than or equal to the length of the arrays. void drawrect( int x, int y, int width, int height ) x and y specify the coordinates of the upper left hand corner. void filloval( int x, int y, int width, int height ) Same as drawoval except that the oval is filled. void fillpolygon(int[] x, int[] y, int n) Same as drawpolygon except that the polygon is filled. void fillrect( int x, int y, int width, int height ) Same as drawrect except that the rectangle is filled. void setcolor( Color c ) Sets the color to use for all future drawing 2

Ex. 1. Create a program like the one shown. The main panel has a preferred size of 350 by 200 pixels. Inside the main panel is a panel with the following: - the background color is orange. - there is a light gray rectangle drawn so that there is a ten pixel space between the rectangle and the edges of the panel. - there is a white circle with a 25 pixel radius in the upper left hand corner. - there is a gray circle with a 25 pixel radius in the lower right hand corner. Ex. 2. Create a program like the one to the right. The main panel has a preferred size 450 pixels wide by 300 pixels high. Write a class that extends JPanel and it draws 4 evenly spaced vertical lines. The height of these lines should match the height of the panel. Instantiate two objects of this class. The one on the left has an orange background and the one on the right has a yellow background. Both have red borders. You should size and position them so that it looks similar to the figure but it doesn t have to be exact. Handling Interactions Between a JPanel Subclass and Other Components. In this example there is a button, label, and panel. When the button is clicked, (1) a random number between 1 and 50 is generated, (2) the number is displayed in the label, and (3) that number of lines is drawn on the panel. I did not provide the code for the runner class but the code for the other two classes is on the next page. 3

import javax.swing.*; import java.awt.*; public class Demo2Panel extends JPanel { private int numlines = 0; New. There s an instance variable for the number of lines to draw. public Demo2Panel( Color c ) { setbackground( c ); setborder( BorderFactory.createLineBorder(Color.BLACK ) ); @Override public void paintcomponent( Graphics g ) { super.paintcomponent( g ); g.setcolor( Color.BLACK ); int h = getheight(); for ( int n = 1; n <= numlines; n++ ) g.drawline( 0, 0, n*25, h ); public void update( int n ){ if ( n < 0 ) numlines = 0; else numlines = n; repaint(); This method gets called from the frame class whenever the button is clicked. New and important. The repaint method sends a message to the JVM that it needs to call the paintcomponent method. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Demo2Frame extends JFrame { private JButton button = new JButton("Update Panel"); private JLabel lbl = new JLabel("Number of Lines: 0"); private Demo2Panel p1 = new Demo2Panel( Color.ORANGE ); public Demo2Frame(){ setdefaultcloseoperation(exit_on_close); settitle( "Graphics" ); JPanel jp = new JPanel(); jp.setbackground( Color.WHITE ); jp.setpreferredsize( new Dimension( 400, 250 ) ); jp.setlayout( null ); 4

button.setbounds( 10, 10, 150, 30 ); button.addactionlistener( new ButtonEars() ); lbl.setbounds( 10, 50, 150, 30 ); p1.setbounds( 170, 10, 200, 200 ); jp.add( button ); jp.add( lbl ); jp.add( p1 ); getcontentpane().add( jp ); pack(); public void display() { EventQueue.invokeLater(new Runnable() { public void run() { setvisible(true); ); private class ButtonEars implements ActionListener{ public void actionperformed(actionevent e) { int num = (int)( 50*Math.random() ) + 1; lbl.settext( "Number of Lines: " + num ); p1.update( num ); Everything in the Demo2Frame class should look familiar. The only real change is adding an object that is a subclass of JPanel and calling one of its methods whenever the button is clicked. Ex. 3. Create a program like the one to the right. The panel has a solid oval that just touches the four sides of the panel. The initial color of the circle is black. Add a method to this class that allows the color of the circle to be updated. The main panel contains a button and two panels. Whenever the button is clicked, generate a random color and pass this color to the two sub-panels. Every time the button is clicked the circles should change color. The exact sizes and positions do not matter for this exercise. 5

Ex. 4. Create a program like the one shown. When the button is clicked, those number of vertical and horizontal lines, evenly spaced, should be displayed in the two panels. Assume the textboxes are either empty or contain an integer. If the textbox is empty, assume the value is 0. The update method for the panel will have two int parameters for the number of lines. Remember that the coordinates are integer values. There are two consequences to this. (1) If the number of lines is greater than the width/height of the panel, the spacing between lines will be zero - which is bad. If your calculated spacing is zero, make it one instead. (2) Depending on the number of lines and the size of the panel, there may be some extra space on the right or bottom. This is unavoidable. Ex. 5. Create a program like the one shown. There are two buttons and three panels. In each panel there is rectangle drawn that fills the panel except for a 10 pixel edge. When the Start button is clicked, start a timer which causes the background color of each panel to swap with the color of the rectangle. Clicking the Stop button stops the timer. Here s an outline of the sub-panel public class Ex5Panel extends JPanel { private Color backcolor, rectcolor; public Ex5Panel( Color bg, Color rect ) { initialize the instance variables, set the background color, and draw a border @Override public void paintcomponent( Graphics g ) { super.paintcomponent( g ); draw a rectangle that s the right color in the right location with the right size public void swapcolors(){ switch the colors, resets the background color, and calls repaint 6

Ex. 6. Create a program like the one shown. There are three panels and one timer. When the program starts there are 10 circles in every panel that are moving upward. When a circle hits the top of the panel it reappears at the bottom of the panel. You will need to use the Point class. Here s some sample code: Point p = new Point( 4, 7 ); System.out.println( p.x ); // 4 p.y = 1; System.out.println( p.y ); // 1 Here is an outline of the panel class. public class Ex6Panel extends JPanel { private ArrayList<Point> pts = new ArrayList<Point>(); public Ex6Panel( Color bg, int w, int h ) { w and h should be the width and height of the panel do not use getwidth and getheight in the constructor Add 10 Point objects to the array list. Their initial x and y coordinates should be random values based on the width and height of the panel. set the background color and put a black border around panel @Override public void paintcomponent( Graphics g ) { Draw circles with a diameter of 10 pixels based on the points in the array list public void move(){ Loop through the array list and change the y coordinates by 10 pixels so that the circles move up. If the circle moves off the top of the panel reset y to the bottom of the panel. You can use the getheight method here. Be sure to call repaint. 7

The MouseListener interface is used to detect certain events associated with the mouse. It has five methods: void mousepressed( MouseEvent e ) Invoked when the mouse button has been pressed (this event occurs before the click event). void mousereleased( MouseEvent e ) Invoked when the mouse button has been released. void mouseclicked( MouseEvent e ) Invoked when a mouse button has been clicked (pressed and released) on a component. You can use this with a JButton but the ActionListener is simpler. Use a MouseListener when you want to know where a mouse was when it was clicked. void mouseentered( MouseEvent e ) Invoked when a mouse enters a component. You could use this is change the color of a component (panel, label, etc.) when the mouse goes over it. void mouseexited( MouseEvent e ) Invoked when a mouse exits a component. You could use this is change the color of a component (panel, label, etc.) when the mouse leaves it. Note. For a click event to occur, the pressed and released event must both occur on the same component with a short amount of time. Notice that the parameter for all of the above methods is a MouseEvent object. Here a few methods of the MouseEvent class. int getx() Returns the horizontal x position of the event relative to the source component. int gety() Returns the vertical y position of the event relative to the source component. To detect if it was a right or left click, where e is the MouseEvent if ( SwingUtilities.isLeftMouseButton( e ) ) if ( SwingUtilities. isrightmousebutton( e ) ) SwingUtilities is in the javax.swing package. Here s a program that demonstrates one way to use a MouseListener. In this program I placed the MouseListener inner class in the class that extends JPanel. My reasoning was that I only wanted to respond to mouse events within those panels. Four things will happen. 1) When you press the mouse a circle will appear where the mouse was pressed down. If you release the mouse the circle disappears. 2) When the mouse enters a panel the background color gets brighter. This will not effect the red panel but it does effect the orange panel. When the mouse leaves the panel the background color gets darker. 3) No code was written for the mouseclicked. The code for the runner class was not provided. The code for the other two classes is on the next page. 8

import javax.swing.*; import java.awt.*; import java.awt.event.*; public class DemoMousePanel extends JPanel { private int x = -50; // x and y are coordinates of the circle that is drawn private int y = -50; // arbitrary values outside the viewable area of the panel public DemoMousePanel( Color bg ) { setbackground( bg ); setborder( BorderFactory.createLineBorder(Color.BLACK ) ); addmouselistener( new Mickey() ); @Override public void paintcomponent( Graphics g ) { super.paintcomponent( g ); g.setcolor( Color.BLACK ); g.drawoval( x-20, y- 20, 40, 40 ); private class Mickey implements MouseListener{ public void mousepressed( MouseEvent e ){ x = e.getx(); y = e.gety(); repaint(); public void mousereleased( MouseEvent e ) { x = -50; y = -50; repaint(); public void mouseentered( MouseEvent e ){ Color c = getbackground(); setbackground( c.brighter() ); public void mouseexited( MouseEvent e ){ Color c = getbackground(); setbackground( c.darker() ); public void mouseclicked( MouseEvent e ){ Code for the class that extends JFrame is on the next page. 9

import javax.swing.*; import java.awt.*; import java.awt.event.*; public class DemoMouseFrame extends JFrame { private DemoMousePanel p1 = new DemoMousePanel( Color.RED ); private DemoMousePanel p2 = new DemoMousePanel( Color.ORANGE ); public DemoMouseFrame(){ setdefaultcloseoperation(exit_on_close); settitle( "Graphics" ); JPanel jp = new JPanel(); jp.setbackground( Color.WHITE ); jp.setpreferredsize( new Dimension( 300, 250 ) ); jp.setlayout( null ); p1.setbounds( 20, 20, 100, 200 ); p2.setbounds( 160, 20, 100, 200 ); jp.add( p1 ); jp.add( p2 ); getcontentpane().add( jp ); pack(); public void display() { EventQueue.invokeLater(new Runnable() { public void run() { setvisible(true); ); Ex. 7. Create two panels. Whenever you left-click on the a panel, a 20 by 20 pixel square appears centered on the point you clicked on. If you right click all the squares should disappear. Here are some hints. You may use the mousepressed or the mouseclicked methods. The only instance variable the panel class should have is an array list of points. The array list class has a clear method that removes everything from the array list. 10

Ex. 8. There is a button, a label, and an 8 x 8 array of panels. Yeehaw! When a mouse enters a panel its background color turns black, when the mouse exits the background color goes back to white. At no time will more than one panel have a black background. Whenever the user clicks on the button, a random color will appear in the label. Then if a mouse enters a panel its background color turns to that color. Here are some hints for the panel class. There should only be two instance variables, the starting color of white and its special color which starts out as black. Add a mutator method that can change the special color. There s no need to override the paintcomponent method because nothing is being drawn on the panels. You will need to add an inner class that implements the MouseListener interface. Here are some hints for the frame class JLabels are transparent by default. Call the setopaque method and set the label s background to black. When the button is clicked, generate a random color. Change the background color of the label to this color and call the mutator method for each of the 62 panels. You can pick your own dimensions. My panels are 50 by 50 pixels. Ex. 9. There is one label and one panel. At the start there are 10 blue circles are moving to the right. When one goes off the right side it reappears on the left. Yes, there s a timer and so far this is very similar to exercise 6. Whenever the user clicks on a circle, the circle disappears and the label is updated. Nothing special happens when the last circle is clicked on. In this program the timer needs to tell the panel to update itself and the panel needs to tell the label in the frame to change whenever a circle is clicked on. The outline on the next page shows how this can be done. 11

Many now familiar details are left out so that we can focus on key new details. public class Ex9Frame extends JFrame { private Ex9Panel p1; private JLabel lblstatus = new JLabel( "There are 10 circle(s)" ); private javax.swing.timer timer; public Ex9Frame(){ usual stuff plus somewhere you need to have the following statement p1 = new Ex9Panel( Color.YELLOW, 300, 300, this ); public void updatelabel( int n ){ lblstatus.settext( "There are " + n + " circle(s) left." ); Display method Inner class to handle Action events from the timer. Whenever an action event is received, call the move method of the panel class. public class Ex9Panel extends JPanel { private ArrayList<Point> pts = new ArrayList<Point>(); private Ex9Frame frame; private static final int RADIUS = 15; public Ex9Panel( Color bg, int w, int h, Ex9Frame f ) { frame = f; Create the 10 points which represent the center of each circle Be sure to add a mouse listener @Override public void paintcomponent( Graphics g ) { Loop through the array list and draw the circles. The points in the array are the centers of the circles, not the upper left hand corners public void move(){ Loop through the array list and move each point to the right 5 pixels. If the point went outside the visible region of the panel, move it back to the left side. Remember to call the method that causes paintcomponent to be called. Inner class to respond to the mouse events. When the mouse is pressed, calculate the distance between that point and each of the points in the array list. Remove any point with 15 pixels of where the mouse went down. Afterwards update the label and call the method. 12

Ex. 10. There are four JLabels over one panel. The panel is initially white and empty. If you press, drag, and then release the mouse a red rectangle should appear. This should work no matter where you start on the panel and which direction you drag the mouse. HOWEVER, the rectangle does not appear until you release the mouse. If you click on one of the four colored labels, any future rectangles will be that color. Hints for the panel class. Create a Color instance variable to represent the current color being used when creating rectangles. Initialize this to red. Create an array list of Rectangle objects. The Rectangle constructor looks like this: Rectangle r = new Rectangle( x, y, width, height); and it has four public instance variables: x, y, width, and height. Create an array list of Colors to hold the rectangle colors. Create two instance variables, x and y, to store the coordinates of where the mouse is pressed down. Add a mutator method for the current color. Override the paintcomponent method to draw the rectangles. Add a mouse listener to the panel. When the mouse is pressed, store that point. When the mouse is released, create a rectangle based on the starting ending points. This isn t as simple as it seems but it s not that hard either. Add the rectangle and current color to the array lists. Hints for the frame class. You cannot add an action listener to a JLabel so you ll have to add a mouse listener. This is a different inner class from the one you wrote for the panel. Whenever someone presses the mouse on a JLabel (or clicks, your choice though one is better than the other), get the color of the label and call the panel s mutator method for the current color. If you have trouble figuring out how to do this, the answer (slightly obfuscated) is below. 13