how to draw lines in java
In this tutorial, we are going to see how to describe lines, rectangles and circles in JFrame. Java offers the states an easy way to depict graphics using Graphics class in AWT parcel which allows us to draw primitive geometric types similar lines, circles, etc… This tutorial explains the different functions of Graphics class used to draw shapes.
Describe a line
Graphics class provides the Graphics.drawline(int x1, int y1, int x2, int y2) method to draw a line on the screen. While x1 is the ten-coordinate of the outset betoken in the line and y1 is the y-coordinate of the showtime point in the line. Similarly, x2 and y2 are the coordinates of the 2d point in the line.
Here is the program that draws a line.
import java.awt.Graphics; import javax.swing.*; public class DrawMyLine extends JPanel { public void paint(Graphics thousand){ yard.drawLine(20, 20, 200, 180); } public static void main(String[] args){ JFrame f = new JFrame("Draw a line"); f.getContentPane().add(new DrawMyLine()); f.setSize(250, 250); f.setVisible(true); f.setResizable(imitation); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } Output:
Draw a circle
Y'all can depict a circumvolve and oval using the Graphics.drawOval(int x, int y, int width, int pinnacle) method. This function performs both functions. 'x' and 'y' are the starting indicate on the screen, and 'width' and 'height' are the parameters to gear up the width and summit of the oval or circumvolve. For the circumvolve, set the same width and superlative.
Hither is the program that draws a circle on the screen.
import java.awt.Graphics; import javax.swing.*; public class DrawMyCercle extends JPanel { public void paint(Graphics yard){ g.drawOval(50, twoscore, 150, 150); } public static void main(String[] args){ JFrame f = new JFrame("Draw a circle"); f.getContentPane().add(new DrawMyCercle()); f.setSize(250, 250); f.setVisible(true); f.setResizable(imitation); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } Output:
Draw a rectangle
Graphics class provides the Graphics.drawRect(int 10, int y, int width, int height) method for drawing a rectangle or foursquare. The beginning 2 parameters specify the starting point and the last two parameters specify the width and height of the rectangle or square. The width and elevation of the square must be identical.
Here is the program that draws a rectangle on the screen.
import java.awt.Graphics; import javax.swing.*; public grade DrawMyRect extends JPanel { public void paint(Graphics g){ m.drawRect(50, 35, 150, 150); } public static void primary(String[] args){ JFrame f = new JFrame("Draw a rectangle"); f.getContentPane().add(new DrawMyRect()); f.setSize(250, 250); f.setVisible(true); f.setResizable(false); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } Output:
Source: https://stackhowto.com/how-to-draw-lines-rectangles-and-circles-in-jframe/
Posted by: gibsonthistalre98.blogspot.com

0 Response to "how to draw lines in java"
Post a Comment