2014-01-29 79 views
1

我试图移动一个由Graphics2D绘制的矩形,但它不起作用。当我做x + = 1;它实际上将其移动1个像素并停止。如果我说的话,x + = 200;它在ONCE上移动200个像素,而不是每次更新,但一次。Java - 如何移动由Graphics2D绘制的矩形?

public void paint(Graphics g) 
{ 
    super.paint(g); 

    g.setColor(Color.WHITE); 
    g.fillRect(0, 0, this.getWidth(), this.getHeight()); 

    g.setColor(Color.RED); 
    g.fillRect(x, 350, 50, 50); 

    x += 1; 
} 

int x在void paint之外调用,以确保它不会每次增加150。 画好,只是不动,我尝试使用一个线程,并使用一个while循环,所以当线程正在运行时,它移动,但没有运气。

+0

对我们发出更多的代码 – Xabster

+0

如何触发'repaint()'? – Holger

+0

看看[**如何使用键绑定**移动屏幕上的矩形](http://stackoverflow.com/a/20844242/2587435)。它应该帮助你。 –

回答

2

而不是使用while循环或不同的线程,您应该使用动画java.swing.Timer。这里是基本的结构

Timer(int delay, ActionListener listener) 

,其中延迟到重绘之间的延迟你想要的时间,listener与回调函数来执行监听。你可以做这样的事情,在这里你改变x位置,然后调用repaint();

ActionListener listener = new AbstractAction() { 
     public void actionPerformed(ActionEvent e) { 
      if (x >= D_W) { 
       x = 0; 
       drawPanel.repaint(); 
      } else { 
       x += 10; 
       drawPanel.repaint(); 
      } 
     } 
    }; 
    Timer timer = new Timer(250, listener); 
    timer.start(); 

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

public class KeyBindings extends JFrame { 

    private static final int D_W = 500; 
    private static final int D_H = 200; 
    int x = 0; 
    int y = 0; 

    DrawPanel drawPanel = new DrawPanel(); 

    public KeyBindings() { 
     ActionListener listener = new AbstractAction() { 
      public void actionPerformed(ActionEvent e) { 
       if (x >= D_W) { 
        x = 0; 
        drawPanel.repaint(); 
       } else { 
        x += 10; 
        drawPanel.repaint(); 
       } 
      } 
     }; 
     Timer timer = new Timer(100, listener); 
     timer.start(); 
     add(drawPanel); 

     pack(); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 
     setLocationRelativeTo(null); 
     setVisible(true); 
    } 

    private class DrawPanel extends JPanel { 

     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      g.setColor(Color.GREEN); 
      g.fillRect(x, y, 50, 50); 
     } 

     public Dimension getPreferredSize() { 
      return new Dimension(D_W, D_H); 
     } 
    } 

    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       new KeyBindings(); 
      } 
     }); 
    } 
} 

enter image description here

这里是一个正在运行的例子