我们开始给我们的项目添加交互效果,首先我们添加键盘的交互。
实现效果:
我们通过空格键可以暂停小球,再按一次继续运动。
修改AlgoVisualizer类
添加isAnimated侦听动画是否执行
import java.awt.*; import java.awt.event.*; public class AlgoVisualizer{ private Circle[] circles; private AlgoFrame frame; private boolean isAnimated = true;//动画是否执行 public AlgoVisualizer(int sceneWidth, int sceneHeight, int N){ // 初始化数据 circles = new Circle[N]; int R = 50; for(int i = 0 ; i < N ; i ++ ) { int x = (int)(Math.random()*(sceneWidth-2*R)) + R; int y = (int)(Math.random()*(sceneHeight-2*R)) + R; int vx = (int)(Math.random()*11) - 5; int vy = (int)(Math.random()*11) - 5; circles[i] = new Circle(x, y, R, vx, vy); } // 初始化视图 EventQueue.invokeLater(() -> { frame = new AlgoFrame("Welcome", sceneWidth, sceneHeight); frame.addKeyListener(new AlgoKeyListener());//添加侦听事件 new Thread(() -> { run(); }).start(); }); } public void run(){ while(true){ // 绘制数据 frame.render(circles); AlgoVisHelper.pause(20); // 更新数据 if( isAnimated) for(Circle circle: circles) circle.move(0, 0, frame.getCanvasWidth(), frame.getCanvasHeight()); } } private class AlgoKeyListener extends KeyAdapter{//键盘侦听 @Override public void keyReleased(KeyEvent event){ if(event.getKeyChar() == ' ') isAnimated = !isAnimated; } } public static void main(String[] args) { int sceneWidth = 800; int sceneHeight = 800; int N = 10; AlgoVisualizer vis = new AlgoVisualizer(sceneWidth, sceneHeight, N); } }