90.7k views
5 votes
Write a class called Line that represents a line segment between two Points. Your Line objects should have the following methods: public Line(Point p1, Point p2) Constructs a new line that contains the given two points. public Point getP1() Returns this line's first endpoint. public Point getP2() Returns this line's second endpoint. public String toString() Returns a string representation of this line, such as "[(22, 3), (4, 7)]". Write a complete program to check your work. Please submit Line, and client class .java files.

1 Answer

5 votes

Answer:

We can draw lines by using Java Swing. Below is the full example.

Step-by-step explanation:

Explanation of Below code is in comment, line starts with //.

import java.awt.*;

import javax.swing.*;

//Creating Point class which will hold point data

class Point {

public int x;

public int y;

}

//MyCanvas is the class used to draw the line

class MyCanvas extends JComponent {

//Declaring 2 points variable

Point p1;

Point p2;

// Creating Getter and Setter for above 2 variables

public Point getP1() {

return p1;

}

public void setP1(Point p1) {

this.p1 = p1;

}

public Point getP2() {

return p2;

}

public void setP2(Point p2) {

this.p2 = p2;

}

//When canvas load, it will call this method and draw a line

public void paint(Graphics g)

{

// draw and display the line

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

}

//toString method to show the points data

@Override

public String toString() {

return "[(" +

p1.x+","+p1.y+")," +

"("+p2.x+","+p2.y+")]";

}

}

//This class will start the program and initialize canvas class

//to draw new line on canvas

public class DrawLine {

public static void main(String[] a)

{

// creating object of JFrame

JFrame window = new JFrame();

// Operation when window closes

window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// setting size of window

window.setBounds(30, 30, 200, 200);

// Creating instance of MyCanvas class

MyCanvas canvas = new MyCanvas();

// Adding two points in MyCanvas object with its Setter method

Point p1 = new Point();

p1.x=10;

p1.y=10;

Point p2 = new Point();

p2.x=40;

p2.y=40;

canvas.setP1(p1);

canvas.setP2(p2);

// setting canvas to draw new line

window.getContentPane().add(canvas);

// visibility to true

window.setVisible(true);

//calling toString method to show two point values

System.out.println(canvas.toString());

}

}

User Mitat Koyuncu
by
7.2k points