目录
- 1、前言:
- 2、图片的展示以及自动关闭:
- 3、动画的连续展示:
1、前言:
要实现动画的流畅展示需要在能展示图片的基础上对图片进行关闭,再切换下一张图片,这要关闭窗口,与延时函数以及while函数的配合使用
2、图片的展示以及自动关闭:
图片的展示以及关闭代码如下:
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
water w = new water("C:\\Users\\86153\\Pictures\\Saved Pictures\\微信图片_20220211134809.jpg");
try {
Robot r = new Robot();
r.delay(3000);
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
w.dispatchEvent(new WindowEvent(w, WindowEvent.WINDOW_CLOSING));//关闭窗口
}
}
class water extends JFrame{//打印图片类
water(String PATH){
//图片大小设置
this.setSize(1000, 1000);
//手动关闭窗口程序自动结束
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//加载图片
ImageIcon imageIcon = new ImageIcon(PATH);
//创建的JLabel设置其图标为上方加载的图片
JLabel label = new JLabel(imageIcon);
//将label添加到窗口中
this.getContentPane().add(label);
//图片居中
this.setLocationRelativeTo(null);
//窗口显示
this.setVisible(true);
}
}
Java中使用frame.dispose()时,该行代码被标记了横线,可能是因为该方法被标记为过时方法(deprecated method)所以取而代之使用 w.dispatchEvent(new WindowEvent(w, WindowEvent.WINDOW_CLOSING));方法
3、动画的连续展示:
以上述图为例,理论上从0出发可以到达任意的其他三个点且有多种路径,若上述0,1,2,3分别代表一张图的话,配合随机数的生成理论上可以产生不同变换且流畅的动画
将上述图转成矩阵有路径的坐标分别为(0,1)、(1,3)、(1,2)、(2,3)、(2,0)、(3,0)
变换成01矩阵入下:
[
0,1,0,0
0,0,1,1
1,0,0,1
1,0,0,0
]
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.WindowEvent;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main {
public static String path[] = {
"C:\\Users\\86153\\Pictures\\Saved Pictures\\0.jpg",
"C:\\Users\\86153\\Pictures\\Saved Pictures\\1.jpg",
"C:\\Users\\86153\\Pictures\\Saved Pictures\\2.jpg",
"C:\\Users\\86153\\Pictures\\Saved Pictures\\3.jpg"
};
public static void main(String[] args) {
int index = 0;//初始化变量
while(true) {//死循环
int next = Math.abs(new Random().nextInt()) % 4;
while(a[index][next] != 1) next = Math.abs(new Random().nextInt()) % 4;
// System.out.println(index + " " + next);
Water w = new Water(path[next]);
index = next;
try {
new Robot().delay(500);
//w.dispatchEvent(new WindowEvent(w, WindowEvent.WINDOW_CLOSING));//关闭窗口
} catch (Exception e) {
}
}
}
public static int a[][] = {
{0, 1, 0, 0},
{0, 0, 1, 1},
{1, 0, 0, 1},
{1, 0, 0, 0}
};
}
class Water extends JFrame{//打印图片类
Water(String PATH){
//图片大小设置
this.setSize(2000, 2000);
//手动关闭窗口程序自动结束
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//加载图片
ImageIcon imageIcon = new ImageIcon(PATH);
//创建的JLabel设置其图标为上方加载的图片
JLabel label = new JLabel(imageIcon);
//将label添加到窗口中
this.getContentPane().add(label);
//图片居中
this.setLocationRelativeTo(null);
//窗口显示
this.setVisible(true);
}
}
能够切换但不够丝滑