Page 224 - CTS - CSA TP - Volume 2
P. 224
COMPUTER SOFTWARE APPLICATION - CITS
EXERCISE 119 : Create a GUI to draw different plane shapes
over a predefined area
Objectives
At the end of this exercise you shall be able to
• Develop Java programs to Create a GUI to draw different plane shapes over a predefined area.
Requirements
Tools/Materials
• PC/Laptop with Windows OS
• JDK Software
• Text Editor (Visual Studio/Sublime/Notepad)
Procedure
TASK 1: Example program that allows the user to draw different plane shapes (e.g., circles, rectangles)
on a JPanel using mouse interactions
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
class PlaneShapesGUI extends JFrame {
private ArrayList<Shape> shapes = new ArrayList<>();
private Shape currentShape;
private int startX, startY;
public PlaneShapesGUI() {
setTitle(“Plane Shapes Drawing”);
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel drawingPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
drawShapes(g);
}
};
209