【问题标题】:Java graphics being drawn on top of existing graphic在现有图形之上绘制 Java 图形
【发布时间】:2015-05-13 18:57:44
【问题描述】:

主类:

    public Main() {
    Frame f = new Frame();
    final Panel p = f.p;

    final Player player = new Player();

    Timer t = new Timer(UPDATE_PERIOD, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Graphics g = p.getGraphics();
            p.render(g);

            player.tick();
            player.render(g);

            g.dispose();
        }
    });
    t.start();
}

播放器渲染方法:

public void render(Graphics g) {
    g.drawImage(Images.get("player"), x, y, null);
}

问题是,之前绘制的所有图像仍然存在。示例(当我更改绘制图像的 x 或 y 时):

【问题讨论】:

  • 您需要清除上一次抽奖才能再次抽奖:g.clearRect(0, 0, getWidth(), getHeight());
  • 如果您想要的答案不是猜测,您需要使用更多complete example 更新问题。现在我们并不真正了解您的代码在做什么。 (p.getGraphics() 是做什么的?你在画什么?)
  • @Radiodef p 是扩展 JPanel 的类。 .getGraphics() 来自超类。这将是一个我刚刚开始并正在尝试的小游戏
  • 那么您已经收到了答案。 (不要那样画。)您还应该在这里查看我的答案:stackoverflow.com/a/30175751,它演示了一种更合适的游戏绘画方式,并提供了其他示例的链接。

标签: java image graphics


【解决方案1】:

要绘制Swing,您不应该直接从JPanel 获取Graphics 对象。相反,重写 paintComponent 方法并使用参数 Graphics 对象来执行您的自定义绘图,并调用父方法来擦除以前的绘图

@Override
public void paintComponent(Graphics g){
    super.paintComponent(g);
    //custom painting goes here
}

如果您希望触发重绘,请在 JPanel 上使用该名称的方法:

p.repaint();

【讨论】:

    【解决方案2】:

    而不是自定义渲染你的计时器,你真的应该在你的 paintComponent 方法中完成所有的绘画。比如:

       public void actionPerformed(ActionEvent e) {            
            player.tick();
            p.repaint();
        }
    

    然后在paintComponent()中重新渲染播放器和背景

    当您调整面板大小等时,像现在这样的绘画会遇到问题

    【讨论】:

      【解决方案3】:

      更改图形位置后,尝试在 ActionListener 中调用“p.repaint()”。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-11-19
        • 1970-01-01
        • 1970-01-01
        • 2017-03-02
        • 1970-01-01
        • 1970-01-01
        • 2021-11-05
        相关资源
        最近更新 更多