Step 1: Take input two end points (x1, y1) and (x2, y2)
Step 2:Calculate m = dy/dx = (y2-y1)/(x2-x1)
Step 3:Repeat step 4 and 5 while ( x1 <= x2)
Step 5: if ( m < 1)
x1 = x1 + 1
y1 = y1 + m
else if ( m > 1)
x1 = x1 + (1/m)
y1 = y1 + 1
else
x1 = x1 + 1
y1 = y1 + 1
Source Code:
package today;import java.awt.Color;import java.awt.Graphics;import java.util.Scanner;import javax.swing.JFrame;import javax.swing.JPanel;public class DrawLineAlgorithm { public static void main(String[] args) { double x1,y1,x2,y2; Scanner input = new Scanner(System.in); System.out.println("Enter starting co-ordinate:"); x1 = input.nextDouble(); y1 = input.nextDouble(); System.out.println("Enter ending co-ordinate:"); x2 = input.nextDouble(); y2 = input.nextDouble(); input.close(); JFrame frame = new JFrame("My Frame"); NewClass nc = new NewClass(x1,y1,x2,y2); nc.setBackground(Color.WHITE); frame.add(nc); frame.setSize(500, 500); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }}class NewClass extends JPanel{ /** * */ private static final long serialVersionUID = 1L; double x1,y1,x2,y2; public NewClass(double x1,double y1,double x2,double y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } public void paintComponent(Graphics g){ super.paintComponent(g); lineDraw(x1, y1, x2, y2,g); } public void lineDraw(double x1,double y1,double x2,double y2,Graphics g){ double m; m = (y2-y1)/(x2-x1); for(int i=0; x1<=x2; i++){ g.setColor(Color.RED); g.fillOval((int)x1, (int)y1, 5, 5); if(m<1){ x1 = x1 + 1; y1 = y1 + m; g.fillOval((int)x1, (int)y1, 5, 5); }else if(m>1){ x1 = x1 + (1/m); y1 = y1 + 1; g.fillOval((int)x1, (int)y1, 5, 5); }else{ x1 = x1 + 1; y1 = y1 + 1; g.fillOval((int)x1, (int)y1, 5, 5); } } } }
No comments:
Post a Comment