Java 在两点之间画一条线
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4218145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
drawing a line between two points
提问by user472221
Hi
I have 2 points (X1,Y1)
and (X2,Y2)
how can I draw a line between them?
thanks
嗨,我有 2 点(X1,Y1)
,(X2,Y2)
如何在它们之间划一条线?谢谢
采纳答案by jjnguy
In Swing:
在摇摆中:
Graphics g;
g.drawLine(X1, Y1, X2, Y2);
IF you are drawing on a JPanel
, you will usually put this code in the paintComponent
method:
如果您在 a 上绘图JPanel
,您通常会将以下代码放在paintComponent
方法中:
@Override
protected void paintComponent(Graphics g) {
g.drawLine(X1, Y1, X2, Y2);
}
To see all available methods on the Graphics
class, see the Javadocs.
要查看Graphics
该类的所有可用方法,请参阅Javadocs。
回答by javamonkey79
Take a look at the Graphics.drawLinemethod.
看看Graphics.drawLine方法。
You'll basically need to override some widget (like JPanel) or get a Canvas and in the paint method you do something like:
您基本上需要覆盖一些小部件(如 JPanel)或获取 Canvas 并在paint方法中执行以下操作:
graphics.drawLine( p1.x, p1.y, p2.x, p2.y );
回答by Scribbleno1
For a JFrame, you would add a paint method, which is ran when the JVM is ready to draw on the JFrame, inside of the class that has inherited the JFrame class. Then, inside of that, you would call the 'drawLine' method of the graphic, as demonstrated (ensure that the "Graphics" class has been imported and replace the X1, Y1, X2, Y2 with the integars of your choice.):
对于 JFrame,您将在继承 JFrame 类的类中添加一个绘制方法,该方法在 JVM 准备好在 JFrame 上绘制时运行。然后,在其中,您将调用图形的 'drawLine' 方法,如图所示(确保已导入“Graphics”类并将 X1、Y1、X2、Y2 替换为您选择的整数。):
public void paint(Graphics g) {
g.drawLine(X1,X2,Y1,Y2);
}
回答by Rebecca Phillips
You can also try this:
你也可以试试这个:
var draw = function(ctx,x1,y1,x2,y2) {
ctx.strokeStyle = "Black";
ctx.lineWidth = 4;
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.stroke();
};
var drawPoints = function(ctx,points) {
ctx.strokeStyle = "Black";
ctx.lineWidth = 4;
for(var i = 0; i<points.length -1;i++){
draw(ctx,points[i][0],points [i][1],points[i+1][0],points[i+1][1]);
}
};
var ctx = canvas.getContext("2d")
Now call the function as:
现在调用函数:
drawPoints(ctx, points);
You can change the var points array
to any points you like.
您可以将 更改为var points array
您喜欢的任何点。
var points = [[50,50],[50,100],[100,100],[100,50]];
This should connect all the points with a black line. If you enter three points it makes a triangle, with four, a square and so on. Please let me know if I made a mistake.
这应该用黑线连接所有点。如果你输入三个点,它会形成一个三角形,四个,一个正方形等等。如果我犯了错误,请告诉我。