三角形的查看器
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class Viewer
{
static int counter = 0;
static double x1, x2, x3, y1, y2, y3;
public static void main (String [] args)
{
JFrame outerFrame = new JFrame();
JPanel panel = new JPanel();
outerFrame.add(panel);
panel.addMouseListener(new MouseAdapter(){
@Override
public void mousePressed(MouseEvent e){
if(counter == 0) {
x1 = e.getX();
y1 = e.getY();
} else if(counter == 1) {
x2 = e.getX();
y2 = e.getY();
} else if(counter == 2) {
x3 = e.getX();
y3 = e.getY();
}
counter++;
}
});
TriangleComponent component = new TriangleComponent(x1, x2, x3, y1, y2, y3);
outerFrame.add(component);
outerFrame.setSize(400, 400);
outerFrame.setTitle("Drawing Triangle");
outerFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
outerFrame.setVisible(true);
}
}
组件
import java.awt.*;
import javax.swing.*;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
public class TriangleComponent extends JComponent
{
private double x1, x2, x3, y1, y2, y3;
public TriangleComponent(double xOne, double xTwo, double xThree, double yOne, double yTwo, double yThree) {
x1 = xOne;
x2 = xTwo;
x3 = xThree;
y1 = yOne;
y2 = yTwo;
y3 = yThree;
}
public void paintComponent(Graphics triangle)
{
Point2D.Double L = new Point2D.Double(x1, y1);
Point2D.Double R = new Point2D.Double(x2, y2);
Point2D.Double M = new Point2D.Double(x3, y3);
Line2D.Double leftSegment = new Line2D.Double(L, R);
Line2D.Double rightSegment = new Line2D.Double(R, M);
Line2D.Double baseSegment = new Line2D.Double(M, L);
Graphics2D tri = (Graphics2D) triangle;
tri.setPaint(Color.RED);
tri.setStroke(new BasicStroke(5));
tri.draw(leftSegment);
tri.draw(rightSegment);
tri.draw(baseSegment);
}
}
我试图通过鼠标监听器获取我的x和y值,但我认为我有一个问题,因为三次点击后没有任何反应,并且框架的最左侧有一个点。