我的程序涉及在我单击它们的地方绘制三角形。
有两个类,Ecad 和 Line 类。Ecad 是主框架,Line 类用于绘制线条。
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);
}
}
}
这是线类
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());
}
}
在 Ecad 类的 paint() 方法中,如果我使用 scale 选项来放大或缩小,鼠标坐标不会被转换。所以在它被放大之后,如果我点击一个点,三角形就会被放置在另一个点上。当我缩放图形组件时,有没有办法转换鼠标坐标?