1
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/*
<applet height=800 width=600 code="RaceApplet.java"></applet>
*/

public class RaceApplet extends JApplet implements KeyListener
{
    private Image player;
    private Image bg;
    private int nx = 800;
    private int ny = 0;
    private Rectangle rect;

    private void loadPicture()
    {
        bg = new ImageIcon("RaceBack.png").getImage();
        player = new ImageIcon("KD//KDE.png").getImage();
    }

    public void init()
    {
        loadPicture();
        rect = new Rectangle(250, 93, 50, 50);
        this.addKeyListener(this);
    }

    public void paint(Graphics g)
    {
        super.paint(g);
        g.setColor(Color.green);
        g.fillRect(0, 0, 34567, 34567);
        g.drawImage(bg, nx - 800, ny, null);
        g.drawImage(player, rect.x, rect.y, null);

    }

    public void keyPressed(KeyEvent e)
    {
        if( e.getKeyCode() == KeyEvent.VK_RIGHT )
        {
            nx = nx - 20;
            player = new ImageIcon("KD//KDE.png").getImage();
        }
        if( e.getKeyCode() == KeyEvent.VK_LEFT )
        {
            nx = nx + 20;
            player = new ImageIcon("KD//KDW.png").getImage();
        }
        if( e.getKeyCode() == KeyEvent.VK_UP )
        {
            ny = ny + 20;
            player = new ImageIcon("KD//KDN.png").getImage();
        }
        if( e.getKeyCode() == KeyEvent.VK_DOWN )
        {
            ny = ny - 20;
            player = new ImageIcon("KD//KDS.png").getImage();
        }

        repaint();
    }

    public void keyReleased(KeyEvent e)
    {

    }

    public void keyTyped(KeyEvent e)
    {

    }

}

问题是当我在小程序屏幕上移动我的汽车时,它会闪烁。有没有办法解决这个问题。我怎样才能使它无闪烁屏幕。我搜索了大多数网站,但他们显示的方式并没有那么有效

thnx 提前寻求帮助

4

2 回答 2

5

您应该在开始时加载所有图像,而不是每次需要时都实例化它们。

于 2013-07-10T10:36:37.830 回答
1

除了您在 上加载图像这一事实之外KeyEvents,您正在覆盖paint它并没有利用 Swing 的优化双缓冲绘制机制。覆盖paint而不是paintComponent导致闪烁。

将您的绘画功能移动到一个新的类子类化JComponent和覆盖paintComponent而不是paint记住调用super.paintComponent(g)

public class ImageComponent extends JComponent {

    private Image player;
    private Image backgroundImage; // formerly bg
    private int nx = 800;
    private int ny = 0;
    private Rectangle rect;

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

        g.setColor(Color.green);
        g.fillRect(0, 0, 34567, 34567);
        g.drawImage(backgroundImage, nx - 800, ny, null);
        g.drawImage(player, rect.x, rect.y, null);

    }

    public void setPlayer(Image player) {
        this.player = player;
    }

    public void setBackgroundImage(Image backgroundImage) {
        this.backgroundImage = backgroundImage;
    }
}

不相关,但考虑使用Key Bindings而不是 KeyListeners 处理与KeyStrokes

于 2013-07-10T10:42:09.423 回答