2015-11-06 83 views
0

我創建了一個簡單的動畫,其中一個正方形從一個角落跳到另一個角落。但是,它只能在一個固定範圍內進行。如果我調整幀大小,它仍然只在範圍內反彈。如何實時更改邊界,如果窗口被拉伸,該形狀仍然會在整個窗口中生成動畫?如何實時調整Java動畫?

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

public class Animation extends JPanel implements ActionListener{ 

Timer timer = new Timer(5, this); 
int x=0, xspeed=2,y=0,yspeed=2,framex=575,framey=575; 

public void paintComponent(Graphics g){ 
    super.paintComponent(g); 
    g.setColor(Color.BLUE); 
    g.fillRect(x, y, 50, 50); 
    timer.start(); 
} 

public void actionPerformed(ActionEvent e) { 

    if(x<0||x>framex){xspeed=-xspeed;} 
    if(y<0||y>framey){yspeed=-yspeed;} 

    x=x+xspeed; 
    y=y+yspeed; 
    repaint(); 
} 

public static void main(String[] args){ 
    Animation a = new Animation(); 
    JFrame frame = new JFrame("Animate"); 
    frame.setSize(600, 600); 
    frame.setVisible(true); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.add(a); 
} 
} 
+0

paintComponent有時被稱爲*每秒多次。*不要在該方法中啓動Timer,也不要執行繪製組件所需的任何其他邏輯。但是,從actionPerformed方法重新啓動計時器是安全的。 – VGR

回答

3
if(x<0||x>framex){xspeed=-xspeed;} 
if(y<0||y>framey){yspeed=-yspeed;} 

你得到使用的getSize()方法的面板的當前大小。

Dimension d = getSize(); 

if(x < 0 || x > d.width){xspeed =- xspeed;} 

if(y < 0 || y > d.height){yspeed =- yspeed;} 

不要害怕使用空格來提高代碼的可讀性。