BufferedImage is not cleared before each rendering

I am trying to learn how to build a simple game through the tutorial that I am looking at. So far, everything has been fine, but when I move the image, the previous image is not erased or deleted. I don’t know exactly what happened or why this is happening. I have 3 classes, the main class, the player class, and the bufferimageloader class.

Main class:

import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.swing.JFrame;

public class Main extends Canvas implements Runnable {
private boolean running = false;
private Thread thread;
private BufferedImage player;
private Player p;

public void init(){ // load and initiliaze
    BufferedImageLoader loader = new BufferedImageLoader();

    try {
        player = loader.loadImage("/player_shotgun2.png");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    p = new Player(100, 100, this);

}

private synchronized void start(){
if(running)
    return;
running = true;
thread = new Thread(this);
thread.start();
}

private synchronized void stop(){
    if(!running)
        return;
    running = false;
    try {
        thread.join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.exit(1);
}

public void run() {
    init();
    long lastTime = System.nanoTime();
    final double amountOfTicks = 60.0;
    double ns = 1000000000 / amountOfTicks;// 1 second divided by 60, run 60 times per second
    double delta = 0;
    int updates = 0;
    int frames = 0;
    long timer = System.currentTimeMillis();
    System.out.println("hi");
    while(running){
        long now = System.nanoTime();
        delta += (now - lastTime) / ns;
        lastTime = now;
        if(delta >= 1){// delta = 1 = 1 second
            tick();
            updates++;
            delta--;
        }
        render();
        frames++;
        if(System.currentTimeMillis() - timer > 1000){
            timer+= 1000;
            System.out.println(updates + " Ticks, Fps " + frames);
            updates = 0;
            frames = 0;
        }
    }
    stop();
}

// Everything thats is updated in the game
private void tick(){
    p.tick();
}

// Everything that is rendered in the game
private void render(){
    BufferStrategy bs = this.getBufferStrategy();
    if(bs == null){
        createBufferStrategy(3);
        return;
    }
    Graphics g = bs.getDrawGraphics();
    //////////////////////////////
    p.render(g);

    //////////////////////////////
    g.dispose();
    bs.show();
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Main main = new Main();
    JFrame window = new JFrame();
    window.setSize(500,600);
    window.setTitle("Zombie Game");
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setVisible(true);
    window.add(main);
    main.start();
}

public BufferedImage getPlayerImage(){
    return player;
}

}

Player Class:

import java.awt.Graphics;
import java.awt.image.BufferedImage;

import javax.swing.JPanel;

public class Player extends JPanel {

    private double x;
    private double y;
    public BufferedImage player;

    public Player(double x, double y, Main main){
        this.x = x;
        this.y = y;

        player = main.getPlayerImage();
    }

    public void tick(){
        x++;
    }

    public void render(Graphics g){
        super.paintComponent(g);
        g.drawImage(player, (int)x, (int)y, null);
        g.dispose();
    }
}

Bufferedimageloader Class:

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

public class BufferedImageLoader {

    private BufferedImage image;

    public BufferedImage loadImage(String path) throws IOException{
        image = ImageIO.read(getClass().getResource(path));
        return image;
    }
}

This is the result that I get at startup, and the image moves:

enter image description here

+1
source share
2 answers

Swing Moving Eyes. .

, , . , , Swing. .

GUI Swing.

Moving eyes

// Swing. , :

  • .
  • .
  • .
  • / .

, . Swing - Android.

// Swing . , , , , . .

:

package com.ggl.testing;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class MovingEyes implements Runnable {

    private static final int drawingWidth = 400;
    private static final int drawingHeight = 400;
    private static final int eyeballHeight = 150;
    private static final int eyeballWidthMargin = 125;

    private DrawingPanel drawingPanel;

    private Eye[] eyes;

    private JFrame frame;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new MovingEyes());
    }

    public MovingEyes() {
        this.eyes = new Eye[2];
        this.eyes[0] = new Eye(new Point(eyeballWidthMargin, eyeballHeight));
        this.eyes[1] = new Eye(new Point(drawingWidth - eyeballWidthMargin,
                eyeballHeight));
    }

    @Override
    public void run() {
        frame = new JFrame("Moving Eyes");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        drawingPanel = new DrawingPanel(drawingWidth, drawingHeight);
        frame.add(drawingPanel);

        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public class DrawingPanel extends JPanel {

        private static final long serialVersionUID = -2977860217912678180L;

        private static final int eyeballOuterRadius = 50;
        private static final int eyeballInnerRadius = 20;

        public DrawingPanel(int width, int height) {
            this.addMouseMotionListener(new EyeballListener(this,
                    eyeballOuterRadius - eyeballInnerRadius - 5));
            this.setBackground(Color.WHITE);
            this.setPreferredSize(new Dimension(width, height));
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            g.setColor(Color.BLACK);

            for (Eye eye : eyes) {
                drawCircle(g, eye.getOrigin(), eyeballOuterRadius);
                fillCircle(g, eye.getEyeballOrigin(), eyeballInnerRadius);
            }
        }

        private void drawCircle(Graphics g, Point origin, int radius) {
            g.drawOval(origin.x - radius, origin.y - radius, radius + radius,
                    radius + radius);
        }

        private void fillCircle(Graphics g, Point origin, int radius) {
            g.fillOval(origin.x - radius, origin.y - radius, radius + radius,
                    radius + radius);
        }

    }

    public class Eye {
        private final Point origin;
        private Point eyeballOrigin;

        public Eye(Point origin) {
            this.origin = origin;
            this.eyeballOrigin = origin;
        }

        public Point getEyeballOrigin() {
            return eyeballOrigin;
        }

        public void setEyeballOrigin(Point eyeballOrigin) {
            this.eyeballOrigin = eyeballOrigin;
        }

        public Point getOrigin() {
            return origin;
        }

    }

    public class EyeballListener extends MouseMotionAdapter {

        private final double eyeballDistance;

        private final DrawingPanel drawingPanel;

        public EyeballListener(DrawingPanel drawingPanel, double eyeballDistance) {
            this.drawingPanel = drawingPanel;
            this.eyeballDistance = eyeballDistance;
        }

        @Override
        public void mouseMoved(MouseEvent event) {
            Point p = event.getPoint();
            for (Eye eye : eyes) {
                Point origin = eye.getOrigin();
                double theta = Math.atan2((double) (p.y - origin.y),
                        (double) (p.x - origin.x));
                int x = (int) Math.round(Math.cos(theta) * eyeballDistance)
                        + origin.x;
                int y = (int) Math.round(Math.sin(theta) * eyeballDistance)
                        + origin.y;
                eye.setEyeballOrigin(new Point(x, y));
            }

            drawingPanel.repaint();
        }

    }

}

Model

Eye - Java, () . Eye .

MovingEyes - , JFrame. MovingEyes . SwingUtilities invokeLater, , Swing Dispatch.

JFrame. JFrame. , Swing Java, - . , DrawingPanel.

MovingEyes Eye. run JFrame. run Swing.

DrawingPanel . DrawingPanel JPanel, paintComponent. DrawingPanel . Swing.

paintComponent DrawingPanel super paintComponent. Swing paintComponent.

paintComponent DrawingPanel . () paintComponent. .

EyeballListener - . Swing.

EyeballListener MouseMotionAdapter. MouseMotionListener. Im , , MouseMotionAdapter.

mouseMoved EyeballListener MouseEvent . , . - .

Eye for. . , .

, . , . , , , Dispatch.

+4

BufferStrategy? https://docs.oracle.com/javase/7/docs/api/java/awt/image/BufferStrategy.html

BufferStrategy , . , , , . fillRect, .

+2

Source: https://habr.com/ru/post/1659942/


All Articles