Matthew
Matthew

Reputation: 4617

Java - Get Name of Drawn Component

I have a Java application containing five buttons:

i) Square ii) Rectangle iii) Circle iv) Triangle iv) Clear

Clicking on any of the four buttons will result in the respective shape being drawn on the drawing canvas. This is the code used to draw the shape:

The drawing canvas class inherits from JPanel. The shapes which are clicked by the user and are drawn to the drawing canvas are stored in an ArrayList called Shapes.

Now in the drawing canvas class I have a number of mouse listeners. In the MousePressed Event, I want to detect what was clicked.

This is what I used for the buttons:

The naming of the buttons was achieved using the setName method of the JButton class.

However, the Graphics class does not have such a method. How can I detect that one of the shapes has been clicked on the canvas please (once it has been drawn)?

Upvotes: 0

Views: 154

Answers (2)

Qwerky
Qwerky

Reputation: 18455

If you're just drawing your shapes with fill and draw methods in Graphics then there's no way of getting the information back out again, not out og the Graphics object anyway. You're going to have to do something yourself.

If the objects in your list inherit from Shape then you can get check if the click is within the bounds of each shape.

public void mousePressed(MouseEvent e) {
  for (Shape shape : shapes) {
    if (shape.contains(e.getPoint())) {
      //the shape was clicked
    }
  }
}

Upvotes: 0

appnus
appnus

Reputation: 101

To keep track of what was drawn, you should keep track of the coordinates of the shapes being drawn into the canvas in a Collection such as an ArrayList and do a check based on this array to the mouse location of the click.

Upvotes: 1

Related Questions