我创建了一个简单的动画,其中一个正方形从一个角弹到另一个角。但是,它仅在固定范围内执行此操作。如果我调整帧大小,它仍然只在范围内反弹。如何实时更改边界,以便在窗口拉伸(stretch)时形状仍会在整个窗口上呈现动画?
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);
}
}
最佳答案
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;}
不要害怕使用空格来使代码更具可读性。
关于java - 如何实时调整Java动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33557663/