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

Similar documents
GUI in Java TalentHome Solutions

Java - Applets. C&G criteria: 1.2.2, 1.2.3, 1.2.4, 1.3.4, 1.2.4, 1.3.4, 1.3.5, 2.2.5, 2.4.5, 5.1.2, 5.2.1,

User interfaces and Swing

Java - Applets. public class Buttons extends Applet implements ActionListener

Programmierpraktikum

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

Computer Science 210: Data Structures. Intro to Java Graphics

Chapter 1 GUI Applications

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

G51PRG: Introduction to Programming Second semester Applets and graphics

CSIS 10A Practice Final Exam Solutions

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

Programming Languages and Techniques (CIS120)

CSIS 10A Assignment 14 SOLUTIONS

Programming Languages and Techniques (CIS120)

Graphical User Interfaces 2

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

UCLA PIC 20A Java Programming

Design Patterns: Prototype, State, Composite, Memento

PESIT Bangalore South Campus

Windows and Events. created originally by Brian Bailey

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

Advanced Java Programming

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

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 9: Writing Java Applets. Introduction

Advanced Internet Programming CSY3020

EE219 Object Oriented Programming I (2005/2006) SEMESTER 1 SOLUTIONS

Chapter 14: Applets and More

Programming Languages and Techniques (CIS120)

Java - Dates and Threads

Component-Based Behavioural Modelling with High-Level Petri Nets

An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a

H212 Introduction to Software Systems Honors

J.73 J.74 THE I/O PACKAGE. Java I/O is defined in terms of streams. Streams are ordered sequences of data that have a source and a destination.

Unit 7: Event driven programming

Applet which displays a simulated trackball in the upper half of its window.

CSIS 10A PRACTICE FINAL EXAM Name Closed Book Closed Computer 3 Sheets of Notes Allowed

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

Java. GUI building with the AWT

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.

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

CS2110. GUIS: Listening to Events

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Graphical User Interfaces 2

Java Applet Basics. Life cycle of an applet:

The AWT Event Model 9

I/O Framework and Case Study. CS151 Chris Pollett Nov. 2, 2005.

FirstSwingFrame.java Page 1 of 1

Graphical User Interfaces 2

1 Definitions & Short Answer (5 Points Each)

2IS45 Programming

Building Java Programs

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

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

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

Java Programming Lecture 6

Java for Interfaces and Networks (DT3010, HT10)

THE UNIVERSITY OF AUCKLAND

Programming Languages and Techniques (CIS120)

Chapter 7 Applets. Answers

Appendix G Navigation and Collision Detection for Web-Based 3D Experiment

Aim: Write a java program to demonstrate the use of following layouts. 1.FlowLayout 2.BorderLayout 3.GridLayout 4.GridBagLayout 5.

Computer Programming Java AWT Lab 18

Handling Mouse and Keyboard Events

Overloading Example. Overloading. When to Overload. Overloading Example (cont'd) (class Point continued.)

Chapter 12 Advanced GUIs and Graphics

AP CS Unit 12: Drawing and Mouse Events

OBJECT ORIENTED PROGRAMMING. Course 8 Loredana STANCIU Room B613

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

Advanced Java Unit 6: Review of Graphics and Events

Program 20: //Design an Applet program to handle Mouse Events. import java.awt.*; import java.applet.*; import java.awt.event.*;

ISO-2022-JP (JIS ) 1 2. (Windows95/98 MacOS ) Java UNICODE UNICODE. Java. .java.java.txt native2ascii. .java

CSC 551: Web Programming. Fall 2001

Lecture 5: Java Graphics

LAB 5(4 tiết): Sử dụng sự kiện chuột và bàn phím

Day before tests of Java Final test. IDM institution of Bandarawela. Project for department of education

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

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

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

CS2110. GUIS: Listening to Events

CISC 1600 Lecture 3.1 Introduction to Processing

Görünt Görün ülerin ölçeklenmesi ve yerle y ştirilmesi ş

: 15. (x, y) (x, y ) (x, y) ( x x = 1 y = y ) (x = x y y = 1) (12.1.1)

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!

CS 2113 Software Engineering

COMP 102: Test 2 Model Solutions

Programming graphics

BM214E Object Oriented Programming Lecture 13

Packages: Putting Classes Together

CHAPTER 2. Java Overview

UML and OOD. Some terms related to OOD. Dependency. Coupling. Interfaces. Multiple Interfaces

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

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

SEMESTER ONE EXAMINATIONS SOLUTIONS 2003/2004

CS 120 Fall 2008 Practice Final Exam v1.0m. Name: Model Solution. True/False Section, 20 points: 10 true/false, 2 points each

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.

Graphics -- To be discussed

Transcription:

Java Mouse Actions C&G criteria: 5.2.1, 5.4.1, 5.4.2, 5.6.2. The events so far have depended on creating Objects and detecting when they receive the event. The position of the mouse on the screen can also be used to fire code. If a program is run in the applet viewer the Window can be dragged to any size. If the relative mouse position is important it may be preferable to run code in a browser where the size of the running program can be set in HTML. The 1.1 mouse events are very different to those in Java 1.0, 5.42 in the C&G task list refers to the 1.0 model. This program with draw the current mouse coordinates as a String. import java.applet.*; import java.awt.*; import java.awt.event.*; public class MouseList extends Applet implements MouseListener //MouseListener is much like ActionListener and the rest int downx, downy; //do not miss out this essential line this.addmouselistener(this); public void mouseclicked(mouseevent e) downx = e.getx(); //get x and y downy = e.gety(); repaint(); public void mousereleased(mouseevent e) //note that all 5 mouse actions must be present in code even if only 1 is used public void mousepressed(mouseevent e) public void mouseentered(mouseevent e) public void mouseexited(mouseevent e) public void paint(graphics g) //draw the current coordinates at their position g.drawstring(downx+", "+downy,downx,downy); Run the code as it stands and with 1 of the mouse actions commented out. 1

Modifications Use Java.Math.Random to create a random mouse coordinate and have the user click on screen to find the hidden spot. A 200 by 200 Window is large enough for the applet. Inform the user when within 10 of the hidden spot. For the sake of testing it is useful to show the hidden coordinates. This ensures that the correct result is achieved. The following code will calculate the positive offset value from the point clicked (myx) and that chosen randomly (javax) and store it as the integer offx. offx=java.lang.math.abs(myx-javax); Drawing lines If Java knows 2 sets of points it can draw a line between them. Dragging achieved by public void mousedragged(mouseevent e) This must be accompanied by public void mousemoved(mouseevent e) In the same way that all the clicking events have to be together. They are not implemented by MouseListener but by MouseMotionListener. There is likely to be some clicking in the same program to a possible start is: public class MouseList extends Applet implements MouseMotionListener, MouseListener this.addmouselistener(this); this.addmousemotionlistener(this); To drag the initial and final mouse coordinates are required. So 2 sets of x and y values will have to be assigned to variables. A Boolean variable drawing will detect if dragging is starting or stopping. 2

public void mousepressed(mouseevent e) // mousepressed detects the start of dragging. if(!drawing) downx = e.getx(); downy = e.gety(); repaint(); public void mousereleased(mouseevent e) //stop of dragging drawing = false; public void mousedragged(mouseevent e) //the drag constantly updates mx1 and my1. mx1 =e.getx(); my1=e.gety(); drawing = true; repaint(); public void paint(graphics g) //last mx, my are where string is drawn g.drawstring(downx+", "+downy,downx,downy); if (drawing ==true) g.setcolor(color.red); g.drawline(downx,downy,mx1,my1); g.setcolor(color.blue); g.drawstring(mx1+", "+my1,mx1,my1); Complete this code to draw lines. 3

Modifications 1. When a new line is drawn the old one is lost because paint redraws the canvas based on what information it has. To redraw existing data their details could be placed in variables and accessed by paint but there is an easier way, using getgraphics(). The following method adapts the paint method from the above program. It is called instead of repaint. To draw multiple lines some changes will have to be made to when true and false are set. public void redraw() Graphics g = getgraphics(); g.drawstring(downx+", "+downy,downx,downy); if (drawing ==true) g.setcolor(color.red); g.drawline(downx,downy,mx1,my1); g.setcolor(color.blue); g.drawstring(mx1+", "+my1,mx1,my1); drawing=false; 2. Use alternative graphics methods to draw circles, ovals and squares. The redraw method can be adapted for the various shapes. Allow the user to choose what shape to draw, Buttons can handle this. 4

Layouts The layout in all programs so far is the default or flow layout. The controls flow across the Window in the order that they were created. If the Window shape changes the controls move about. The simplest layout is by the use of BorderLayout that allows controls to be placed in the 4 compass points of the Window or in the centre. The following code places 5 buttons in the 5 positions. It will not work without - setlayout(new BorderLayout()); Button bnorth, bsouth, beast, bwest, bcentre; setlayout(new BorderLayout()); bnorth= new Button("North"); add(bnorth,"north"); bsouth= new Button("South"); add(bsouth,"south"); beast= new Button("East"); add(beast,"east"); bwest= new Button("West"); add(bwest,"west"); bcentre= new Button("Centre"); add(bcentre,"center"); This is not a lot of use but each of the 5 positions can hold more than 1 control through the use of a Panel object. The following code uses a Panel to distribute 3 Buttons in the North area. Button part1, part2, part3; Panel layout; setlayout(new BorderLayout()); //must have this layout =new Panel();//create panel 1st //the GridLayout specifies (rows, cols, horiz spacing, vert spacing) layout.setlayout(new GridLayout(1,3,10,10)); part1= new Button("1"); layout.add(part1); //add controls to the Panel part2= new Button("2"); layout.add(part2); part3= new Button("3"); layout.add(part3); add(layout,"north"); //finally add the Panel to //the Window //add other controls 5

Drawing on a Canvas To allow a program to have a drawing area and controls without the controls sitting on the drawing area Java allows a Canvas to be used. A Canvas is an object like other controls but the various drawing methods relating to it have to be specified for the Canvas. This requires a Canvas Class to be created and an object of that Class added to the user interface Class. So we end up with more than 1 Class in the program. This is the norm in Java programming. This is an entire Canvas Class that is used to draw shapes. There are a number of key points that would not normally be followed in a user defined Class. All the methods are public and some public variables from the user interface Class are used by this Class (int mx, my, mx1, my1). class MyCanvas extends Canvas implements MouseMotionListener, MouseListener // the Class extends Canvas so as to make use of the methods of Class Canvas. public MyCanvas() //constructor method here is adds the mouse listeners this.addmouselistener(this); this.addmousemotionlistener(this); public void mouseclicked(mouseevent e) public void mousereleased(mouseevent e) //redraws the screen repaint(); public void mousepressed(mouseevent e) mx=e.getx(); my=e.gety(); mx1=e.getx(); my1=e.gety(); public void mouseentered(mouseevent e) public void mouseexited(mouseevent e) public void mousedragged(mouseevent e) mx1=e.getx(); my1=e.gety(); public void mousemoved(mouseevent e) public void update(graphics g) g.setcolor(currentcolour); //currentcolour is set by the interface Class if(currenttool==0) //currenttool is set by the interface Class g.drawline(mx,my,mx1,my1); else if(currenttool==1) 6

g.fillrect(mx,my, mx1-mx,my1-my); else if (currenttool==2) g.filloval(mx,my,mx1-mx,my1-my); else if(currenttool==3) //draw a very small rectangle g.fillrect(mx1,my1,2,2); //approximates a paint brush else if(currenttool==4) // if the drawing area is 300 x 300 g.clearrect(0,0,300,300); This Class is of no use without an appropriate interface Class to set the draw type, draw colour, starting and ending positions. It is not possible to shove all this code into a single Class due to the nature of the Canvas object. public class Draw2 extends Applet implements ActionListener //these are suggested controls any names and functions can be used. Panel palette,tools;//2 distinct panels Button line, rect,oval,draw,clear; Button black, white, red, blue, green, yellow; MyCanvas Drawarea; //instance of sub class int mx=0; int my=0; int mx1=0; int my1=0; int currenttool=0;//0=line, 1=rect, 2 = oval Color currentcolour = Color.White; //set controls and layout for palette setlayout(new BorderLayout()); //add controls in a suitable layout drawarea = new MyCanvas();//add the class instance add(drawarea,"center"); public void actionperformed(actionevent evt) // Button actions //Type the Canvas Class here note Canvas is not public Use the Panels and GridLayout to set up an interface similar to that on the next page. The exact positions and colours are not important. There is no need to implement action code until a reasonable interface is created. This will ensure that any interface set up code is correct before writing any actions. actionperformed(actionevent evt) only sets the currentcolour and currenttool. All the drawing actions are already handled by the Canvas object. 7

Modifications 1. Add another 2 colours to draw with. 2. Go back to the Calculator program and improve the layout. All the number Buttons could be part of 1 panel and the operator Buttons on another. 8