I’ve got a class called Shape which inherits from JPanel.
A number of sub-classes in turn extend the Shape classes, one for each type of shape.
Each shape has its own overriden paint() method, which draws the respective shape.
I would like to be able to click on any shape, and am trying to implement this logic for now. Please note that each shape has been added to an arrayList.
However, the contains statement always returns false, even when I have clearly clicked inside the shape.
Any ideas?
Never override
paint()inJPanelratherpaintComponent(..)Im not quite sure I understand however I made a short example which I hope will help.
Basically it is a simple
JFramewith aDrawingPanel(my own class which extendsJPaneland the shapes are drawn on). This panel will create shapes (only 2 for testing) add them to anArrayListand draw them to theJPanelviapaintComponent(..)and aforloop, it also has aMouseAdapterto check for usermouseClicked(..)evnets on theJPanel. When a click is made we iterate through eachShapein theArrayListand check whether theShapecontains the point or not, and if so prints its class name and usesinstance ofto check what type ofShapeis clicked and prints appropriate message:Output (after clicking both shapes):
ShapeClicker.java: