Would someone look at this code and tell me where I've gone wrong?
In the method mouseClicked(MouseEvent me) the co-ords of the click are obtained.
* if they are within the confines of the rectangle rect, console output System.out.println("inside box") is displayed
* in either case the click co-ords are displayed in the console
I'm getting the co-ords of the mouse clicks but no message when the click is inside the box
Apart from that, your ARectangle class has its own fields x, y, w, h which shadow the fields in its superclass. The corresponding fields in teh superclass -- which will be used by its contains(...) method -- will all be 0.
There are no new questions, but there may be new answers.
posted 3 years ago
Thank you Daryl.
Your comment first of all made me realise that:
* for this experiment, that is catch a mouse click within a painted box, I don't need to subclass Rectangle - just create a new Rectangle object.
* I need to re-visit inheritance and fully understand the pitfalls of hidden fields.
By the way, I'm using AWT before moving on to Swing. I think it will a good grounding for it.
Campbell Ritchie wrote:No, AWT is 16 years out of date...
... and learning it will teach you bad habits for Swing and JavaFX.
posted 3 years ago
One learns from one's stupidity. After all, at 50 years old, I can't think as fast as the young things!
I've realised my mistake. I hope my analysis is correct. So here it is:
Just because I can store the dimensions of a rectangle (in say the variables xcoord, ycoord, wide and high and then use g.fillRect(...) to paint it doesn't mean I've created a rectangle object - even though I may have subclassed Rectangle and declared xcoord, ycoord ....etc., within that subclass (or worse still, declared variables that hid the instance variables of Rectangle).
An instance of the subclass wouldn't "know" what the new variables were for and the inherited instance variables (x, y, width, height) would all be zero - thus creating a rectangle (0,0,0,0).
An application of the .contains(mouse click coords) to an instance of such a subclass would thus always return false because a mouse click would never fall within a physically non-existent rectangle.
So the experiment succeeded after these changes:
* I wanted to subclass Rectangle because I wanted a Rectangle class that 'knew' its colour. It contained a new instance variable of type Color * In the subclass's constructor I used super to call the Rectangle(int x, int y, int width, int height)