Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/neo4j/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Jframe上的图纸清理_Java_Swing_Graphics_Paintcomponent - Fatal编程技术网

Java Jframe上的图纸清理

Java Jframe上的图纸清理,java,swing,graphics,paintcomponent,Java,Swing,Graphics,Paintcomponent,我正在做一个游戏,我用鼠标移动一个方块,但当我移动鼠标时,旧方块不会被删除,这会导致方块的轨迹。我希望它只有一个正方形,它跟在我的鼠标后面。这是我目前的代码。我读过使用paintcomponents的书,但我不知道如何使用它,因为我还是一个初学者 这是在我的“游戏面板”课上 这是我的“英雄”课 不要使用this.getGraphics()。这是您绝对不想做的事情,因为它会产生工件(如您所提到的) 最好将鼠标位置存储为变量,然后在调用paintComponent(Graphics)方法时处理所有渲

我正在做一个游戏,我用鼠标移动一个方块,但当我移动鼠标时,旧方块不会被删除,这会导致方块的轨迹。我希望它只有一个正方形,它跟在我的鼠标后面。这是我目前的代码。我读过使用paintcomponents的书,但我不知道如何使用它,因为我还是一个初学者

这是在我的“游戏面板”课上

这是我的“英雄”课


不要使用
this.getGraphics()
。这是您绝对不想做的事情,因为它会产生工件(如您所提到的)

最好将鼠标位置存储为变量,然后在调用
paintComponent(Graphics)
方法时处理所有渲染。请务必同时调用
super.paintComponent(Graphics)
以消除瑕疵

通常,您只应在
paintComponent(graphics)
方法内部以及仅从
paintComponent(graphics)
方法调用的任何方法中处理图形


这里有一个问题涉及到为什么应该避免使用
组件#getGraphics()



下面是我围绕图形渲染回答的另一个问题:

使用扩展JPanel的单独类:

class DrawPane extends JPanel {
 public void paintComponent(Graphics g) {
  super.paintComponent(g);
  g.drawImage(heroPic, x, y, this);

 }


}
然后创建一个将保存该类对象的变量:

DrawPane dp = new DrawPane();
之后,将变量设置为上下文窗格:

JFrame.setContencePane(dp);
现在要重新绘制此图,请执行以下操作:

 dp.repaint();

不要担心“图形g”,你不必输入任何东西。

不要直接在
JFrame
上绘图。使用
JPanel
在其上绘制。在这里找到一个示例代码“我已经阅读了使用
paintcomponents
”-实际上你想要
paintComponent
,没有
s
g.drawImage(heroPic,x,y,null)应该是
g.drawImage(heroPic,x,y,this)
JPanel
是一个
ImageObserver
JFrame.setContencePane(dp);
 dp.repaint();