为什么我的重画不起作用?

时间:2013-07-12 18:52:43

标签: java applet awt java-2d repaint

我有代码:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class obj_Dingus 
extends Applet
implements KeyListener{

    private Rectangle rect; //The rectangle that we move 

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

    public void paint(Graphics g)
    {
        setSize(500,500);
        Graphics2D g2 = (Graphics2D)g;
        g2.fill(rect);
    }

    @Override
    public void keyPressed(KeyEvent e) {
        repaint();
        if (e.getKeyCode() == KeyEvent.VK_RIGHT){
            rect.setLocation(rect.x + 2, rect.y);
        }  if (e.getKeyCode() == KeyEvent.VK_LEFT){
            rect.setLocation(rect.x - 2, rect.y);
        }  if (e.getKeyCode() == KeyEvent.VK_UP){
            rect.setLocation(rect.x, rect.y - 2);
        }  if (e.getKeyCode() == KeyEvent.VK_DOWN){
            rect.setLocation(rect.x, rect.y + 2);
        }
        repaint();
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }
}

据我所知,它应该制作一个在屏幕上移动的黑匣子,但屏幕不会更新,并且不会清除旧框。它最终在屏幕上显示一条巨大的黑线,我不知道我做错了什么,我是一个初学者。

1 个答案:

答案 0 :(得分:1)

public void paint(Graphics g)
{
    setSize(500,500);
    Graphics2D g2 = (Graphics2D)g;
    g2.fill(rect);
}

永远不要在paint(Graphics)方法中调用可能导致GUI repaint()的任何内容。添加组件,更改组件内容或设置GUI的大小都会触发repaint(),因此这个小程序会进入无限循环。

它应该更符合:

public void paint(Graphics g)
{
    super.paint(g); // always call the parent method 1st..
    Graphics2D g2 = (Graphics2D)g;
    g2.fill(rect);
}