2014-01-29 78 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

這裏是一個正在運行的例子