import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class mouse2 extends Applet implements MouseListener
{
public void start( ){addMouseListener(this); setSize(200,200);}
int xcord,ycord,which_shape=-1,size=20;
public void paint ( Graphics g)
{
switch(which_shape)
{
case(0):
g.setColor(Color.red);
g.fillRect(xcord,ycord,size,size);
showStatus("Rectangle at " + xcord + " " + ycord);
break;
case(1):
g.setColor(Color.blue);
g.fillOval(xcord,ycord,size,size);
showStatus("Rectangle at " + xcord + " " + ycord);
break;
}
}
applets
Page 1 of 13 Replies - 464 Views - Last Post: 07 February 2012 - 03:50 PM
Topic Sponsor:
#1
applets
Posted 07 February 2012 - 02:37 PM
Currently in the Mouse2.java the mouse coordinates represent the top left hand corner of the rectangle or oval. how do i alter the program so that oval or rectangle are drawn with the mouse coordinates in the centre of the shape.
Replies To: applets
#2
Re: applets
Posted 07 February 2012 - 03:26 PM
g.fillRect(xcord,ycord,size,size);
xcord and ycord are initialized to 0 when the applet is initialized, and those are the values you send to fillRect, therefore your rectangle appears at (0, 0), the upper left hand corner. If you want the shape drawn in the middle set xcord to applet.height/2 and the other in a similar manner. If you want the shape drawn at the point of a mouse click, you need to register a mouse listener (which you did), and override one of the event callbacks.
class MyApplet extends Applet implements MouseListener {
int xcord,ycord;
void paint(Graphics g){g.fillRect(xcord,ycord,size,size);}
public void mouseClicked(MouseEvent evt) {
xcord = evt.getX();
ycord = evt.getY();
repaint(); //calls paint()
}
}
When paint is called again the shape will be drawn at the mouse click.
This post has been edited by blackcompe: 07 February 2012 - 03:29 PM
#3
Re: applets
Posted 07 February 2012 - 03:36 PM
I assume you mean to ask how to change the coordinates reported by the "Rectangle at " statements at lines 19 and 24. Correct?
If you want to report the center of the, calculate the coordinates of the center of the rectangle and use those instead of the top left corner.
Can you find the coordinates at the center of a rectangle knowing the coordinates of the top left corner and the width and height?
If you want to report the center of the, calculate the coordinates of the center of the rectangle and use those instead of the top left corner.
Can you find the coordinates at the center of a rectangle knowing the coordinates of the top left corner and the width and height?
#4
Re: applets
Posted 07 February 2012 - 03:50 PM
i have to have the coordinates of the centre of the rectangle and oval when clicked, it currently shows the top left corner co-ordinates. so i was wondering what code i would have to change to be able to do this.
Page 1 of 1
|
|

New Topic/Question
Reply



MultiQuote



|