【问题标题】:Java repaint issueJava重绘问题
【发布时间】:2013-07-18 15:46:06
【问题描述】:

下面的代码不是完整的。如果你们需要完整的代码,请告诉我。我的问题是,当我启动程序时,我可以看到红色椭圆可以通过箭头移动,并且在它后面生成 999 个矩形。当我移动一个椭圆时,框架重绘和矩形在不同的坐标上再次生成。我想在不改变生成矩形位置的情况下实现移动椭圆。我知道这种不希望出现的效果的原因,但无法修复。谢谢!

    public void paintComponent(Graphics g){
    random=new Random();
    super.paintComponent(g);    

        for(int i=0;i<=1000;i++){
        rX=random.nextInt(400);
        rY=random.nextInt(400);
        g.drawRect(rX,rY,20,20);            
        }


    g.setColor(Color.red);
    g.fillRect(x,y,20,20);

}

public void keyPressed(KeyEvent e) {
    if(e.getKeyCode()==KeyEvent.VK_RIGHT){
        x=x+10;
        repaint();
        if(x>480)
            x=-10;
    }

【问题讨论】:

    标签: java swing keylistener paintcomponent rect


    【解决方案1】:

    为您的矩形创建一个自定义类,用于保存它们的位置并在构造函数中生成随机位置。比如:

    public class Rect {
    
        private int x;
        private int y;
        private int width;
        private int height;
    
        public Rect() {
            random=new Random();
            x=random.nextInt(400);
            y=random.nextInt(400);
            width=20;
            height=20;
        }
        //getters and setters
    }
    
    
    private Rect rectangles[1000] = new Rect[]();
    
    
    public void paintComponent(Graphics g){
        super.paintComponent(g);
    
        for (int i=0; i<1000;i++) {
            g.drawRect(rectangles[i].getX(), rectangles[i].getY(),
                       rectangles[i].getwidth(), rectangles[i].getHeight());
        }
    }
    

    【讨论】:

      【解决方案2】:

      引入一个布尔值来跟踪该组件之前是否绘制过矩形private boolean hasBeenPainted;

      然后在你的paintcomponent中:

      public void paintComponent(Graphics g){
       super.paintComponent(g);
       if(hasBeenPainted){return;}    
       random=new Random();
      
      for(int i=0;i<=1000;i++){
      rX=random.nextInt(400);
      rY=random.nextInt(400);
      g.drawRect(rX,rY,20,20);            
      }
      
      
      g.setColor(Color.red);
      g.fillRect(x,y,20,20);
      hasBeenPainted = true;
      }
      

      【讨论】:

      • if (!hasBeenPainted) 会比返回那里更好
      • 我担心这有什么问题......当我移动椭圆时,所有东西都会从框架中消失。
      猜你喜欢
      • 2010-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-15
      • 2011-11-05
      • 2013-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多