在鼠标单击上绘制矩形 - 不显示

时间:2011-11-13 23:45:56

标签: java mouseevent

我正试图在我正在制作的游戏(麻将纸牌)中“突出”一个瓷砖对象。为此,我在一个与tile相同的位置绘制一个Rectangle2D对象,并在单击鼠标时尝试显示它。

我能够让鼠标单击事件工作并识别选择图块的时间,但由于某种原因,当我在mousePressed函数内时,不会绘制矩形。我似乎无法弄明白为什么......

以下是我认为的相关代码 - 如有必要,我可以扩展它!

/* 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);
        }

“graphics”Graphic对象传递给函数:

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

任何建议都将不胜感激! 提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您的程序结构听起来很不合适,因为您通常不应让MouseListener直接操作传递给paintComponent的Graphics对象。原因是以这种方式获得的Graphics对象不会持久化。通常,您将使用MouseAdapter(MouseListener和MouseMotionListener)更改类字段,然后在组件上调用repaint()。然后paintComponent使用鼠标适配器设置的字段绘制矩形。

编辑1
例如,请在此处查看我的示例程序:drawing-a-rectangle-over-an-existing-graphics-page