简体   繁体   中英

drawing a line between two points

Hi I have 2 points (X1,Y1) and (X2,Y2) how can I draw a line between them? thanks

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:

@Override
protected void paintComponent(Graphics g) {
    g.drawLine(X1, Y1, X2, Y2);
}

To see all available methods on the Graphics class, see the Javadocs .

Take a look at the Graphics.drawLine method.

You'll basically need to override some widget (like JPanel) or get a Canvas and in the paint method you do something like:

graphics.drawLine( p1.x, p1.y, p2.x, p2.y );

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.):

public void paint(Graphics g) {
    g.drawLine(X1,X2,Y1,Y2);
}

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 = [[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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM