How to draw various shapes in Java Swing
In this program, we will learn how to draw various types of shapes in Java swing using AWT. Java AWT package provides many methods of displaying the graphics. They are a few methods :
- for string-: public abstract void drawString(String str, int x, int y): with this method, we can draw a specified string.
- oval-: public abstract void drawOval(int x, int y, int width, int height): with this method, we can draw an oval with specified dimensions.
- Fill oval-: public abstract void fillOval(int x, int y1, int x2, int y2): with this method, we can draw an oval with specified dimensions and color.
- Line-: public abstract void drawLine(int x1, inty1, int x2, int y2): with this method, we can draw a line with specified dimensions.
- Image-: public abstract void drawImage(Image img, int x. int y, ImageObserver observer): with this method, we can draw an image.
- Draw Arc-: public abstract void drawArc(int x, int y, int width, int height, int startAngle int arcAngle): with this method, we can draw circular things like a circle, eclipse, etc.
- Fill Arc-:
- public abstract void fillArc(int x, int y, int width, int height, int startAngle): with this method, we can draw eclipse, a circle with the specified color.
Java program to draw shapes in Swing AWT
import java.awt.*; import javax.swing.JFrame; public class DisplayGraphics extends Canvas{ public void paint(Graphics g) { g.drawString("Hello",40,40); setBackground(Color.WHITE); g.fillRect(130, 30,100, 80); g.drawOval(30,130,50, 60); setForeground(Color.RED); g.fillOval(130,130,50, 60); g.drawArc(30, 200, 40,50,90,60); g.fillArc(30, 130, 40,50,180,40); } public static void main(String[] args) { DisplayGraphics m=new DisplayGraphics(); JFrame f=new JFrame(); f.add(m); f.setSize(400,400); //f.setLayout(null); f.setVisible(true); } }
The output of the Java program

output: java program to draw shapes using swing AWT
You may also read these:
Leave a Reply