The following program demonstrates How to Create a Java application to draw different figures using AWT.
Creating a Java application to draw different figures using AWT (Abstract Window Toolkit) involves creating a Canvas
or a Panel
and overriding its paint
method to draw various shapes and figures. The following code shows a simple Java application that draws different figures using AWT.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DrawingFigures extends JFrame {
private DrawingPanel drawingPanel;
public DrawingFigures() {
setTitle("Drawing Figures");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawingPanel = new DrawingPanel();
add(drawingPanel);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new DrawingFigures();
});
}
class DrawingPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw a rectangle
g.setColor(Color.RED);
g.fillRect(50, 50, 100, 60);
// Draw an ellipse
g.setColor(Color.BLUE);
g.fillOval(200, 50, 80, 80);
// Draw a line
g.setColor(Color.GREEN);
g.drawLine(50, 200, 250, 200);
// Draw a triangle
int[] xPoints = {150, 200, 100};
int[] yPoints = {250, 300, 300};
int numPoints = 3;
g.setColor(Color.ORANGE);
g.fillPolygon(xPoints, yPoints, numPoints);
}
}
}
In this program:
- We create a
DrawingFigures
class that extendsJFrame
to create the main window. - Inside the
DrawingFigures
constructor:- We set the title, size, and default close operation for the window.
- We create a
DrawingPanel
object and add it to the frame.
- The
DrawingPanel
class is an inner class that extendsJPanel
and overrides itspaintComponent
method. Inside this method, we use theGraphics
object to draw various shapes:- A red filled rectangle at (50, 50) with dimensions 100×60.
- Another blue filled ellipse at (200, 50) with dimensions 80×80.
- Furthermore, a green line from (50, 200) to (250, 200).
- Finally, an orange filled triangle defined by arrays of x and y coordinates.
- In the
main
method, we useSwingUtilities.invokeLater
to create theDrawingFigures
object on the Event Dispatch Thread.
Compile and run this program to see how it draws different figures using AWT on a JFrame. You can customize the shapes, colors, and positions as needed.
Further Reading
Spring Framework Practice Problems and Their Solutions
From Google to the World: The Story of Go Programming Language
Why Go? Understanding the Advantages of this Emerging Language
Creating and Executing Simple Programs in Go