使用Java Swing进行双缓冲,留下痕迹

时间:2015-05-22 00:31:24

标签: java swing

我正在处理的项目旨在展示一个背后有背景的可移动.gif。目前,如果我使用super.paint(g);,则字符和背景会闪烁。如果我不这样做,那么它会留下像所包含的图像一样的痕迹。我不知道为什么会这样,需要帮助。

image animation with java swing

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JLabel;

public class keyboardinput extends JFrame implements ActionListener, KeyListener {
    private JPanel contentPane;

    private Image playerModelRight;
    private Image playerModelLeft;
    private Image playerModelAttackRight;
    private Image playerModelAttackLeft;
    private Image playerModelStandRight;
    private Image playerModelStandLeft;
    private Image background;
    private Image doubleBuffer;

    private int direction;

    private Timer timer;

    private boolean up;
    private boolean down;
    private boolean left;
    private boolean right;
    private boolean attack;

    private int x, y;
    private int speed = 4;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    keyboardinput frame = new keyboardinput();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public keyboardinput() {

        super("Keyboard input testing");

        x = 200;
        y = 200;

        ImageIcon playerModelIconRight = new    ImageIcon(keyboardinput.class.getResource("/images/bitdashright.gif"));
        playerModelRight = playerModelIconRight.getImage();

        ImageIcon playerModelIconLeft = new ImageIcon(keyboardinput.class.getResource("/images/bitdashleft.gif"));
        playerModelLeft = playerModelIconLeft.getImage();

        ImageIcon playerModelIconStandRight = new ImageIcon(keyboardinput.class.getResource("/images/bitdashstandright.gif"));
        playerModelStandRight = playerModelIconStandRight.getImage();

        ImageIcon playerModelIconStandLeft = new ImageIcon(keyboardinput.class.getResource("/images/bitdashstandleft.gif"));
        playerModelStandLeft = playerModelIconStandLeft.getImage();

        ImageIcon playerModelIconAttackRight = new ImageIcon(keyboardinput.class.getResource("/images/bitdashattackright.gif"));
        playerModelAttackRight = playerModelIconAttackRight.getImage();

        ImageIcon playerModelIconAttackLeft = new ImageIcon(keyboardinput.class.getResource("/images/bitdashattackleft.gif"));
        playerModelAttackLeft = playerModelIconAttackLeft.getImage();

        ImageIcon backgroundIcon = new ImageIcon(keyboardinput.class.getResource("/images/backgroundtest.png"));
        background = backgroundIcon.getImage();

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(50, 50, 800, 500);
        contentPane = new JPanel();

        addKeyListener(this);

        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        timer = new Timer(10, this);
        timer.start();
    }

    public void update(Graphics g) {
        Dimension size = getSize();
        if (doubleBuffer == null || doubleBuffer.getWidth(this) != size.width || doubleBuffer.getHeight(this) != size.height) {
            doubleBuffer = createImage(size.width, size.height);
        }

        if (doubleBuffer != null) {
            Graphics g2 = doubleBuffer.getGraphics();
            paint(g2);
            g2.dispose();

            g.drawImage(doubleBuffer, 0, 0, null);
        } else {
            paint(g);
        }
    }

    public void paint(Graphics g) {
        super.paintComponents(g);
        if (attack) {
            if (direction == 1)
                g.drawImage(playerModelAttackRight, x, y, this);
            if (direction == 0) {
                x -= 15;
                g.drawImage(playerModelAttackLeft, x, y, this);
                x += 15;
            }
        } else if (left && right)
            g.drawImage(playerModelStandRight, x, y, this);
        else if (right)
            g.drawImage(playerModelRight, x, y, this);
        else if (left)
            g.drawImage(playerModelLeft, x, y, this);
        else {
            if (direction == 1)
                g.drawImage(playerModelStandRight, x, y, this);
            if (direction == 0)
                g.drawImage(playerModelStandLeft, x, y, this);
        }
        // g.drawImage(background, 0, 0, this);

    }

    public void actionPerformed(ActionEvent arg0) {
        if (attack)
            return;
        if (up && y > 235)
            y -= speed;
        if (down && y < 430)
            y += speed;
        if (left && x > -10)
            x -= speed;
        if (right && x < 750)
            x += speed;
        repaint();
        System.out.println(x + ", " + y);
    }

    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            right = true;
            direction = 1;
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            left = true;
            direction = 0;
        }
        if (e.getKeyCode() == KeyEvent.VK_DOWN)
            down = true;
        if (e.getKeyCode() == KeyEvent.VK_UP)
            up = true;
        if (e.getKeyCode() == KeyEvent.VK_SPACE)
            attack = true;

    }

    public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_RIGHT)
            right = false;
        if (e.getKeyCode() == KeyEvent.VK_LEFT)
            left = false;
        if (e.getKeyCode() == KeyEvent.VK_DOWN)
            down = false;
        if (e.getKeyCode() == KeyEvent.VK_UP)
            up = false;
        if (e.getKeyCode() == KeyEvent.VK_SPACE)
            attack = false;
    }

    public void keyTyped(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }

}

2 个答案:

答案 0 :(得分:4)

public void paint(Graphics g) {
    super.paintComponents(g);
  1. 这确保带来麻烦。不要在覆盖中调用错误的超级方法。
  2. 不要直接在JFrame中绘制,而是在JPanel的paintComponent方法中绘制。
  3. 不要在Swing程序中覆盖update
  4. 执行查看教程:

答案 1 :(得分:2)

  1. 你打破了油漆链,从super.paintComponents(g);内拨打paint。这将导致奇怪和美妙的绘画问题的结束
  2. 你应该避免覆盖paint顶级容器,因为它们不是双缓冲的,但Swing组件是,所以你真的应该使用JPanel并覆盖它的paintComponent方法代替。您还应该避免像JFrame那样绘制到顶级容器,因为它允许您在框架边框下绘制,从不漂亮,JFrame还有许多其他重叠的组件在它上面,这可能会导致它们被重新绘制时出现问题(因为子组件在重新绘制时可能不会通知它的父容器)
  3. 在绘制缓冲区之前,您没有“重置”缓冲区,因此您将获得累积更新
  4. 在您的更新方法中调用g2.fillRect(0, 0, getWidth(), getHeight());之前,您可以“添加paint代码,但正如我已经说过的那样,您在某些事情上浪费了大量的时间和精力已经完成并由API提供,如果你正确使用它

    仔细查看Performing Custom PaintingPainting in AWT and Swing是否应该完成绘画