我有代码:
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) {
}
}
据我所知,它应该制作一个在屏幕周围移动的黑框,但屏幕没有更新,旧框也没有被清除。它最终在屏幕上出现一条巨大的黑线,我不知道我做错了什么,我是个初学者。
最佳答案
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);
}
关于java - 为什么我的重绘不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17622058/