banner



Java Code To Draw A Line Using Points

Home » Java » Applets » How to Draw a Line In Java with drawline() method.

The simplest shape that you can draw with Graphics class is a line. The drawLine() method of the Graphics class is used to draw a line with current color between two points. This method takes the following form

void drawLine(int x1, int y1, int x2, int y2)

The DrawLine method can be used for drawing straight lines between two points (x1, y1) and (x2, y2) data. Following example DrawLine shows how to  Draw a Line on Applet window using drawLine method of Graphics class.

To draw a point at (x, y) we could write: g.drawLine (x, y, x, y); The point thus drawn using the current color of the graphics context, which can be changed using the setColor method.

For example, the statement g.drawLine (20, 100, 90, 100) will draw a straight line from the coordinate point (20, 100) to (90, 100) as shown in Figure

Figure A Straight Line Having Coordinates (20,100) and (90,100)

                import java.applet.Applet;                
import java.awt.*;
import java.awt.event.*;
public class DrawLine extends Applet
{
      public static void main(String[] args)
    {
        Frame drawLineApplet = new Frame("Draw Line in Applet Window Example");
        drawLineApplet.setSize(350, 250);
        Applet DrawLine = new DrawLine();
        drawLineApplet.add(DrawLine);
        drawLineApplet.setVisible(true);
        drawLineApplet.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {System.exit(0); }
                                                                                   });
    }
  public void paint(Graphics g)
  {
          // Now we tell g to change the font
         g.setFont(new Font("Arial",Font.BOLD,14));
        //Syntax: drawString(String str, int xBaselineLeft, int yBaselineLeft);
         g.drawString("This is Draw Line Example", 100, 70);
        // draws a Line
         g.setColor(Color.blue);  // Now we tell g to change the color
        //Syntax For:- drawLine(int x1, int y1, int x2, int y2);
         g.drawLine(90, 135, 90, 180);
        g.setColor(Color.green);  // Now we tell g to change the color
        g.drawLine(0, 0, 100, 100);
   }
}

Draw Line in Applet Window Example

Java Code To Draw A Line Using Points

Source: https://ecomputernotes.com/java/awt-and-applets/draw-line-in-applet-window

Posted by: carrdidellp.blogspot.com

0 Response to "Java Code To Draw A Line Using Points"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel