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

Java 鼠标单击绘制矩形-不显示,java,mouseevent,Java,Mouseevent,我试图在我正在制作的游戏(麻将纸牌)中“突出”一个瓷砖对象。为此,我在与平铺相同的位置绘制了一个矩形2D对象,并试图在单击鼠标时显示它 我能够让鼠标单击事件工作,并识别何时选择了平铺,但由于某些原因,当我在mousePressed函数中时,不会绘制矩形。我似乎不明白为什么 这里是我考虑的相关代码——如果需要的话,我可以扩展它! /* Above this, the positions of tiles are set */ if (content[i][y][x].isVisible()) {

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

我能够让鼠标单击事件工作,并识别何时选择了平铺,但由于某些原因,当我在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);
        }
“图形”图形对象被传递给函数:

public void paintComponent(final Graphics graphics) { ... }
如有任何建议,将不胜感激!
提前感谢您的帮助

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

编辑1

例如,请在此处查看我的示例程序:

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

编辑1

例如,请在此处查看我的示例程序:

要更快地获得更好的帮助,请发布一个。要更快地获得更好的帮助,请发布一个。非常感谢您的帮助@克莉丝汀·艾利斯:非常欢迎你,祝你的项目好运!非常感谢你的帮助@克莉丝汀·艾利斯:非常欢迎你,祝你的项目好运!