Kristina Elise
Kristina Elise

Reputation: 89

Drawing Rectangle on Mouse Click - Does Not Display

I'm attempting to sort of "highlight" a tile object within a game I'm making (Mahjong Solitaire). To do this, I'm drawing a Rectangle2D object in the same position as the tile and trying to have it display when the mouse is clicked.

I'm able to get the mouse click event to work and recognize when tiles are selected, but for some reason, the rectangle is not drawn when I'm within the mousePressed function. I can't seem to figure out why...

Here is what I consider the relevant code - I can expand it if necessary!

/* Above this, the positions of tiles are set */

if (content[i][y][x].isVisible()) {

  /* Draws the image to screen at the appropriate location */
  graphics.drawImage(image, x*TILEW+TILEW/2+i*TILESKEW, (y+1)*TILEH/2-i*TILESKEW,null);

}

/* Represents the area around a tile, so that you can determine
 * whether appropriate area pressed within a tile */
final Rectangle2D rect = new Rectangle2D.Double(x*TILEW+TILEW/2+i*TILESKEW,(y+1)*TILEH/2-i*TILESKEW, image.getWidth(null), image.getHeight(null));

/* Set colour of border rectangle */    
graphics.setColor(Color.red);

/* Store positions and sizes of tile objects */                         
final int xPos = x*TILEW+TILEW/2+i*TILESKEW;
final int yPos =  (y+1)*TILEH/2-i*TILESKEW;
final int height = image.getHeight(null)+2;

/* This works - outside of the mouse event */       
//graphics.drawRoundRect(xPos, yPos, width, height, 7, 7);

/* Mouse event */
addMouseListener(new MouseAdapter() { 

    public void mousePressed(MouseEvent me) { 

            /* Draw the rectangle to the screen -- Doesn't display! */
            graphics.drawRoundRect(xPos, yPos, width, height, 7, 7);
        }

The "graphics" Graphic object is passed to the function:

public void paintComponent(final Graphics graphics) { ... }

Any suggestions would be greatly appreciated! Thank you in advance for your help!

Upvotes: 1

Views: 1771

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

Your program structure sounds off in that you usually shouldn't have the MouseListener directly manipulating the Graphics object that is passed into paintComponent. The reason for this is that the Graphics object obtained this way won't persist. Usually you'll have the MouseAdapter (both MouseListener and MouseMotionListener) alter class fields and then call repaint() on the component. Then paintComponent uses the fields set by the mouse adapter to draw the rectangle.

Edit 1
For example, please see my sample program here: drawing-a-rectangle-over-an-existing-graphics-page

Upvotes: 1

Related Questions