Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Changing a rectangle color with MouseListener  RSS feed

Arnon Neder
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I'm trying to build a program which sets a fill color for a rectangle. Each time the mouse is clicked the fill color changes according to the position of the mouse's X and Y.
I succeeded to create a JFrame with a changing background according to the Mouse's position, but I can't seem to change the color of the rectangle (defined in MyPanel class).

This is the current code, thanks in advance for any suggestions!

Chris Barrett
Posts: 321
Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Arnon,

You're really close!

You don't need a MouseListener in MyPanel, as the MouseListener in the MouseEventDemo2 could simply call a setter in MyPanel to set the color of MyPanel.

Try changing the MouseListener in MouseEventDemo2 to:

(Notice I moved the mp MyPanel creation above the MouseListener).

Then, add to your MyPanel (after removing the MouseListener in MyPanel):

Now, the MouseListener in MouseEventDemo2 sends the mouse position information to MyPanel via setColor. setColor() updates the color instance variable and requests the rectangle be drawn in the new color.

Oh, and just a few general observations:
  • Be careful with defining a Container class. JFrame is a extension of Container already. Plus, mixing that with this and getContainer() can cause debugging confusion
  • Check out the MouseAdapter class. In this situation, MouseAdapter should make your code much cleaner. MouseAdapter implements the MouseListener, MouseMotionListener, and MouseWheelListener interfaces - requiring you to only override and implement the specific mouse events you need (all the event methods required by the interfaces are in MouseAdapter to satisfy the requirements of the interfaces, but are empty).
  • If someone was to resize the window beyond 255 pixels, the setColor method in the sample code above is going to generate an IllegalArgumentException (as Color parameters can only go between 0-255. I think you know that already, though, as your code on line 122 of your MouseEventDemo2 class has that issue).

  • Cheers!
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!