drawing square ( width=height) ? problem
I need to drawing square (width=height)
The problem :
Rectangle(x,y,height,height); - drawing good when the mouse moving in y Axes
Rectangle(x,y,width,width);- drawing good when the mouse moving in x Axes
But to drawing in both Axes ? how ?
publicvoid jPanel1_mousePressed(MouseEvent e){
sx=e.getX();//start x
sy=e.getY();// start y
}
publicvoid jPanel1_mouseDragged(MouseEvent e){
Graphics2D g2d=(Graphics2D)jPanel1.getGraphics();
dx=e.getX();//end x
dy=e.getY();// end y
g2d.setColor(Color.white);
g2d.fillRect(0,0,jPanel1.getWidth(),jPanel1.getHeight());
g2d.setColor(Color.BLUE);
int width,height,x,y;
x=Math.min(sx,dx);
y=Math.min(sy,dy);
width=Math.abs(dx-sx);
height=Math.abs(dy-sy);
Rectangle tt=new Rectangle(x,y,height,height);
g2d.draw(tt);
}
[1337 byte] By [
lover91a] at [2007-11-26 22:32:45]

# 4
but the rectangle Sliding
This is caused by these:
x=Math.min(sx,dx);
y=Math.min(sy,dy);
Allowing x and y to become dx and dy causes the sliding.
If you always keep x and y functions of sx and sy it will not slide.
Deal with dx and dy in the width and height variables.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
public class SquareDrag extends JPanel {
Rectangle tt=new Rectangle();
int sx=0,sy=0,dx=0,dy=0;
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d=(Graphics2D)g;
g2d.setColor(Color.BLUE);
g2d.draw(tt);
g2d.setPaint(Color.green.darker());
g2d.fillRect(sx-2,sy-2,4,4);
g2d.setPaint(Color.red);
g2d.fillRect(dx-2,dy-2,4,4);
}
private MouseInputAdapter mia = new MouseInputAdapter() {
public void mousePressed(MouseEvent e) {
sx=e.getX(); //start x
sy=e.getY(); // start y
}
public void mouseDragged(MouseEvent e) {
dx=e.getX(); //end x
dy=e.getY(); // end y
int width=Math.abs(dx-sx);
int height=Math.abs(dy-sy);
int side=Math.max(width, height);
int x, y;
if(sx<=dx) {
x=sx;
} else {
x=sx-side;
}
if(sy<=dy) {
y=sy;
} else {
y=sy-side;
}
tt.setRect(x,y,side,side);
repaint();
}
};
public static void main(String[] args) {
SquareDrag test = new SquareDrag();
test.addMouseListener(test.mia);
test.addMouseMotionListener(test.mia);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(test);
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
}
}