gpt4 book ai didi

Java Swing 动画

转载 作者:行者123 更新时间:2023-12-01 21:27:32 31 4
gpt4 key购买 nike

我正在尝试使用 java swing 制作翻转效果,但我的翻转方法看起来不像真正的翻转。在我的方法中,我使用 x var 和 xspeed 更改宽度,使图像更小,然后检查 x 是否 >= 我图像的一半。希望有人可以帮助我改进它,提前致谢。

动画类

public class Animation extends JPanel implements MouseListener {

private static final long serialVersionUID = 3264508834913061718L;

public Timer timer;
public int x = 0;
public int xspeed = 2;
public boolean turning = true;
public String pic = "/images/image.jpg";
public URL url = this.getClass().getResource(pic);
public ImageIcon im = new ImageIcon(url);
public String rev = "/images/image2.jpg";
public URL url2 = this.getClass().getResource(rev);
public ImageIcon reverse = new ImageIcon(url2);

public Animation(){
this.setPreferredSize(new Dimension(128,128));
this.setBackground(Color.BLACK);
this.setFocusable(true);
this.addMouseListener(this);

}

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

g.drawImage(im.getImage(), 0 , 0, im.getIconWidth() - x, im.getIconHeight(), null);
}

public void flipAnimation(){
ActionListener actionListener = new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
//
if (turning) {
x = x + xspeed;
}

repaint();
// x in the middle paint new image & set turning to false to stop animation
if(x >= im.getIconWidth()/2){
turning = false;
x = 0;
im = reverse;
}
}
};
if (turning) {
if (timer != null)timer.stop();

timer = new Timer(30, actionListener);
timer.start();
}
}


@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
e.getSource();
flipAnimation();
}

最佳答案

首先,我猜您希望图像从两侧“折叠”,因此您需要增加图像的左边缘和右边缘:

g.drawImage(im.getImage(), x / 2 , 0, im.getIconWidth() - x, im.getIconHeight(), this);

请注意,第一个 int 参数已从 0 更改为 x/2。另外,在 PaintComponent 方法中绘制图像时,最好将 this 作为 ImageObserver 参数传递,因为组件本身就是当图像在后台加载完成时有兴趣重新绘制自身的对象.

第二,更改此:

if (turning) {
x = x + xspeed;
}

对此:

x = x + xspeed;

您不需要标志来控制动画。 (停止动画的正确方法是调用timer.stop(),我稍后会介绍它。)

第三,更改此:

if(x >= im.getIconWidth()/2){ 
turning = false;
x = 0;

对此:

if(x >= im.getIconWidth()){ 
xspeed = -xspeed;
  • 正如我所说,不需要turning 标志。
  • x 与图像宽度而不是宽度的一半进行比较的原因是,我们只想在第一个图像完全“折叠”时才更改图像。
  • xspeed 的否定会反转动画。

最后,在 actionPerformed 方法的末尾,您需要添加以下内容:

if (x <= 0) {
timer.stop();
}

当反向图像达到其完整尺寸时,这会停止动画,这就是不需要 turning 标志的原因。

关于Java Swing 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37864040/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com