Program 10 - Draw Shapes at Mouse Click Positions
Program 10 - Draw Shapes at Mouse Click Positions
Aim: Create a Java program that allows the user to draw a circle, square,
ellipse, and rectangle at the mouse click positions. The shapes can be selected
using keyboard input.
Algorithm:
Step 1: Start.
Step 3: Define an `ArrayList` to store the drawn shapes and set the default
shape choice to "C" (circle).
Step 9: Create the frame, add the `drawingPanel`, and set frame properties.
Show the frame.
public DrawShapesAtClick() {
setTitle("Draw Shapes at Mouse Clicks");
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
shapes = new ArrayList<>();
shapeChoice = "C";
drawingPanel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
switch (shapeChoice) {
case "S":
shapes.add(new Square(x, y, 40));
break;
case "E":
shapes.add(new Ellipse(x, y, 50, 30));
break;
case "R":
shapes.add(new Rectangle(x, y, 70, 40));
break;
default:
shapes.add(new Circle(x, y, 30));
}
drawingPanel.repaint();
}
});
drawingPanel.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
char keyChar = Character.toLowerCase(e.getKeyChar());
if ("cser".indexOf(keyChar) != -1) {
shapeChoice = Character.toString(keyChar).toUpperCase();
}
}
});
drawingPanel.setFocusable(true);
drawingPanel.requestFocusInWindow(); // Set focus to the drawingPanel
to receive keyboard events
add(drawingPanel);
}
@Override
public void draw(Graphics g) {
g.setColor(Color.RED);
g.drawOval(x - radius, y - radius, radius * 2, radius * 2);
}
}
@Override
public void draw(Graphics g) {
g.setColor(Color.BLUE);
g.drawRect(x - side / 2, y - side / 2, side, side);
}
}
@Override
public void draw(Graphics g) {
g.setColor(Color.GREEN);
g.drawOval(x - width / 2, y - height / 2, width, height);
}
}
@Override
public void draw(Graphics g) {
g.setColor(Color.ORANGE);
g.drawRect(x - width / 2, y - height / 2, width, height);
}
}
}
Output: