告诉Java不要重绘

时间:2015-01-08 14:47:31

标签: java swing user-interface applet repaint

我正在创建一个applet,允许用户在使用箭头键的同时移动网格上的框。我已经做了这样的盒子移动但我有一个问题。我想遮蔽任何已经访问过黑色的网格框。因此,如果我的盒子的坐标是(20,20,20,20),它会留下一个盒子,最终整个屏幕都是黑色的。我已尝试删除repaint();但该程序无法正常工作。有没有办法告诉java不重绘特定的帧?非常感谢任何帮助!

package robot;
import java.awt.*;
import java.awt.event.KeyEvent;
import javax.swing.JApplet;
 import java.awt.event.KeyListener;


public class Robot extends JApplet implements KeyListener  {
private Rectangle rect; 

public void init(){
rect = new Rectangle (0, 0, 20,20);
setFocusable(true);
requestFocusInWindow();

addKeyListener(this);
} 

public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.white);
g.fillRect(0,0,500,500);
{
this.setSize(360, 360);
}



g.setColor(Color.black);
g.drawLine(0,0,360,0);
g.drawLine(0,20,360,20);
g.drawLine(0,40,360,40);
g.drawLine(0,60,360,60);
g.drawLine(0,80,360,80);
g.drawLine(0,100,360,100);
g.drawLine(0,120,360,120);
g.drawLine(0,140,360,140);
g.drawLine(0,160,360,160);
g.drawLine(0,180,360,180);
g.drawLine(0,200,360,200);
g.drawLine(0,220,360,220);
g.drawLine(0,240,360,240);
g.drawLine(0,260,360,260);
g.drawLine(0,280,360,280);
g.drawLine(0,300,360,300);
g.drawLine(0,320,360,320);
g.drawLine(0,340,360,340);
g.drawLine(0,360,360,360);
//verticle lines
g.drawLine(0,0,0,360);
g.drawLine(20,0,20,360);
g.drawLine(40,0,40,360);
g.drawLine(60,0,60,360);
g.drawLine(80,0,80,360);
g.drawLine(100,0,100,360);
g.drawLine(120,0,120,360);
g.drawLine(140,0,140,360);
g.drawLine(160,0,160,360);
g.drawLine(180,0,180,360); 
g.drawLine(200,0,200,360);
g.drawLine(220,0,220,360);
g.drawLine(240,0,240,360);
g.drawLine(260,0,260,360);
g.drawLine(280,0,280,360);
g.drawLine(300,0,300,360);
g.drawLine(320,0,320,360);
g.drawLine(340,0,340,360);
g.drawLine(360,0,360,360);













Graphics2D g1 = (Graphics2D) g;

g1.setColor(Color.black);
g1.fill(rect);
}


@Override
public void keyPressed(KeyEvent e)
{ switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
    rect.x -= 20;
    break;
case KeyEvent.VK_RIGHT:
    rect.x += 20;
    break;
case KeyEvent.VK_UP:
    rect.y -= 20;
    break;
case KeyEvent.VK_DOWN:
    rect.y += 20;
    break;


}

repaint();

}
public void pain(Graphics g){
g.fillRect(rect.x, rect.y, 20, 20);
}



@Override
public void keyTyped(KeyEvent e) {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated          methods, choose Tools | Templates.
}

@Override
public void keyReleased(KeyEvent e) {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}


} 

2 个答案:

答案 0 :(得分:3)

不,Java必须能够在需要时重新绘制。不仅在更新屏幕时调用重绘。如果用户移动框架或最小化框架或将另一个窗口放在前面等等。所有这些可能需要重新绘制。

这意味着您必须让程序跟踪框的位置,以便重绘前一行。

然而,这可能会很慢。另一种更复杂的选择是将您的盒子绘制到BufferedImage上,然后在paint()中显示您的BufferedImage。对盒子位置的任何更新都只能覆盖BufferedImage中所需的像素

答案 1 :(得分:0)

您正在使用低级别图形。因此,您必须设计一个涵盖此功能的算法。如果你的Canvas不是那么大,那么当你移动盒子时,一个好的解决方案就是创建黑色方块。请记住,当您在这个级别上进行图形处理时,几乎都是逐像素逻辑。