My program involves drawing triangles where i click them.
There are two classes, Ecad and Line class. Ecad is the main frame and Line class is for drawing lines.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Ecad extends JFrame implements MouseListener{
ArrayList<Line2> lines=new ArrayList();
public Ecad(){
this.setVisible(true);
this.setSize(600,400);
this.addMouseListener(this);
}
public void mouseReleased(MouseEvent me){
Point p1,p2,p3;
int X=me.getX();
int Y=me.getY();
p1=new Point(X,Y);
p2=new Point((int)(p1.getX()-100),(int)(p1.getY()+(1.732/2*200)));
p3=new Point((int)(p1.getX()+100),(int)(p1.getY()+(1.732/2*200)));
Line2 l1=new Line2(p2,p1);
Line2 l2=new Line2(p1,p3);
Line2 l3=new Line2(p2,p3);
lines.add(l1);
lines.add(l2);
lines.add(l3);
this.repaint();
}
public void mouseClicked(MouseEvent me){
}
public void mouseExited(MouseEvent me){
}
public void mouseEntered(MouseEvent me){
}
public void mousePressed(MouseEvent me){
}
public void mouseMoved(MouseEvent me){
}
public static void main(String args[]){
new Ecad();
}
public void paint(Graphics g){
Graphics2D g2=(Graphics2D)g;
super.paintComponents(g2);
//g2.scale(0.5, 0.5);
for(final Line2 r:lines){
r.paint((Graphics2D)g2);
}
}
}
This is the Line class
import java.awt.*;
public class Line2 {
Point start,end;
public Line2(Point a,Point b){
start=a;
end=b;
}
public void paint(Graphics2D g){
g.drawLine((int)start.getX(),(int)start.getY(),(int)end.getX(),(int)end.getY());
}
}
In the Ecad class’s paint() method, if i use the scale option to zoom in or out, the mouse co-ordinates does not get transformed. So after it is zoomed, if i click at one point, the triangle gets placed at some other point. Is there a way to transform the mouse co-ordinates as well when i scale the Graphics component??
Again, you should translate your shape that you’re drawing using the scale and a fixed point (again here it appears that the fixed point of each shape would be the apex of the triangle, but it could be the center should you so decide. The translation is based on simple geometric principles and would be the fixedPoint.x * (1 – scale) / scale, and the same for the y translation.
For example (and this one uses a JPanel as your example above should):
Note that I make copies of my Graphics object before transforming them so as to not have the transform effect other objects that may be drawn by the Graphic object. For example if you get rid of the Graphics2D copy that I use in the JPanel’s
paintComponent(...)method, you’ll find the JSlider gets scaled with everything else.