【问题标题】:Clearing drawings on Jframe在 Jframe 上清除图纸
【发布时间】:2014-06-03 12:25:04
【问题描述】:

我正在制作一个游戏,在其中我用鼠标移动一个正方形,但是当我移动鼠标时,旧的正方形并没有被删除,这导致了一个正方形的轨迹。我希望它只有一个跟随我的鼠标的正方形。这是目前我的代码。我已经阅读过使用paintcomponents,但我不知道如何使用它,因为我还是个初学者。

这是在我的“GamePanel”类中

public void mouseMoved(MouseEvent m) {

        Graphics g= this.getGraphics();
        h.changeX(m.getX());
        h.changeY(m.getY());
        h.drawHero(g);

    }

这是我的“英雄”课

public void drawHero(Graphics g){

        g.drawImage(heroPic,stX,stY,null); //heroPic is a picture I imported

【问题讨论】:

  • 不要直接在JFrame上画画。使用JPanel 绘制它。在这里找到示例代码How to draw in jPanel? (swing/graphics Java)
  • “我已经读过使用paintcomponents - 实际上你想要paintComponent,不想要s

标签: java swing graphics paintcomponent


【解决方案1】:

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

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

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


这里有一个问题涉及为什么你应该避免Component#getGraphics()Drawing an object using getGraphics() without extending JFrame


这是我围绕图形渲染回答的另一个问题:Java JFrame draw

【讨论】:

    【解决方案2】:

    使用扩展 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”,您不必输入任何内容。

    【讨论】:

    • g.drawImage(heroPic, x, y, null); 应该是 g.drawImage(heroPic, x, y, this);JPanel 是一个 ImageObserver
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多