我试图从三个坐标点的用户那里获得输入,这三个坐标点将是三条线的起点和终点,它们将形成一个三角形。我很确定我已经找到了逻辑,但出于某些原因,当我运行它时,它只绘制点而不是连接它们的线。我将发布我的主要方法的三角形部分以及我的三角形类。三角形类没有完成我只试图绘制其中一条线来测试它是否有效,但事实并非如此。
if(input==(4)) {
System.out.print("Enter starting X value: ");
x1 = sc1.nextInt();
System.out.print("Enter starting Y value: ");
y1 = sc1.nextInt();
System.out.print("Enter second X value: ");
x2 = sc1.nextInt();
System.out.print("Enter second Y value: ");
y2 = sc1.nextInt();
System.out.print("Enter final X value: ");
x3 = sc1.nextInt();
System.out.print("Enter final Y value: ");
y3 = sc1.nextInt();
Triangle myTriangle = new Triangle(x1,y1,x2,y2,x3,y3);
JFrame frame4 = new JFrame();
frame4.setSize(400,500);
frame4.setTitle("ShapeViewer");
frame4.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame4.add(myTriangle);
frame4.setVisible(true);}
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import javax.swing.JComponent;
public class Triangle extends JComponent{
private int x1;
private int y1;
private int x2;
private int y2;
private int x3;
private int y3;
private double l1;
private double l2;
private double l3;
public Triangle(int x1, int y1, int x2, int y2, int x3, int y3) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.x3 = x3;
this.y3 = y3;
}
public double getLength1(){
l1 = Math.sqrt(((x2-x1)*(x2-x1)) + ((y2-y1)*(y2-y1)));
return l1;
}
public double getLength2() {
l2 = Math.sqrt(((x3-x2)*(x3-x2)) + ((y3-y2)*(y3-y2)));
return l2;
}
public double getLength3() {
l3 = Math.sqrt(((x1-x3)*(x1-x3)) + ((y1-y3)*(y1-y3)));
return l3;
}
public double getPerimiter() {
return l1 + l2 + l3;
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
Line2D.Double line1 = new Line2D.Double(x1,x2,y1,y2);
g2.draw(line1);
g2.draw(new Line2D.Double (x2, x3, y2, y3));
g2.draw(new Line2D.Double (x1, x3, y1, y3));
}
}
最后,我还要打印每个长度的值以及面积和周长,这就是为什么这些函数在三角形类中但我知道如何做到这一点我只是实际绘制三角形时遇到了麻烦。
答案 0 :(得分:2)
Line2D.Double
的参数顺序为
(double x1, double y1, double x2, double y2)
你放(x1, x2, y1, y2)
旁注:您可以在距离函数中尝试Math.pow( ... , 2)
答案 1 :(得分:0)
从Java 7开始,可以使用 GeneralPath 类,该类表示由直线,二次曲线和三次曲线(贝塞尔曲线)构成的几何路径。它可以包含多个子路径。
Shape shape = null;
Paint paint = null;
Stroke stroke = null;
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
paint = Color.RED;
stroke = new BasicStroke(1.5f,0,0,10.0f,null,0.0f);
shape = new GeneralPath();
((GeneralPath)shape).moveTo(2, 2);
((GeneralPath)shape).lineTo(10, 2);
((GeneralPath)shape).lineTo(2, 10);
((GeneralPath)shape).lineTo(2, 2);
((GeneralPath)shape).closePath();
g2.setPaint(paint);
g2.setStroke(stroke);
g2.fill(shape);
g2.draw(shape);
g2.dispose();
}
使用后不要忘记 dispose()图形。