java制作显示一段动画
时间: 2023-11-24 17:31:45 浏览: 39
在 Java 中,您可以使用 Swing 组件库来制作简单的动画。下面是一个使用 Swing 组件库制作动画的示例:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleAnimation extends JFrame {
private Timer timer;
private int x = 0;
private int y = 100;
public SimpleAnimation(String title) {
super(title);
// Setup UI
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.setPreferredSize(new Dimension(500, 300));
// Create animation panel
JPanel animationPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillOval(x, y, 50, 50);
}
};
mainPanel.add(animationPanel, BorderLayout.CENTER);
// Create start button
JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Create and start timer
timer = new Timer(10, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Move the circle
x += 5;
if (x > getWidth()) {
x = -50;
}
animationPanel.repaint();
}
});
timer.start();
}
});
mainPanel.add(startButton, BorderLayout.SOUTH);
// Add main panel to frame
setContentPane(mainPanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(640, 480);
setVisible(true);
}
public static void main(String[] args) {
// Create and show the animation
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new SimpleAnimation("Simple Animation");
}
});
}
}
```
在这个示例中,我们创建了一个 JPanel,然后在这个 JPanel 中使用 paintComponent 方法绘制了一个红色的圆形。我们还创建了一个 Timer 对象,以便每隔一段时间就移动这个圆形。在“Start”按钮被单击时,我们启动 Timer 对象,并在 actionPerformed 方法中更新圆形的位置。每次圆形位置更新时,我们调用 animationPanel.repaint() 方法来重新绘制圆形。这样就实现了一个简单的动画效果。
注意,在实际应用中,可能需要使用更高级的动画库来实现更复杂的动画效果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)