在Java中,可以使用Swing库中的Timer类来实现进度条的动画效果。以下是一个简单的示例:
- 首先,创建一个JFrame窗口并设置其基本属性:
import javax.swing.*; import java.awt.*; public class ProgressBarAnimation { public static void main(String[] args) { JFrame frame = new JFrame("Progress Bar Animation"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 200); frame.setLayout(new BorderLayout()); frame.setVisible(true); } }
- 接下来,创建一个自定义的JPanel类,用于绘制进度条:
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; class ProgressBarPanel extends JPanel { private int progress = 0; private Timer timer; public ProgressBarPanel() { setPreferredSize(new Dimension(300, 20)); setBackground(Color.GRAY); setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); timer = new Timer(100, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { progress++; if (progress > 100) { progress = 0; } repaint(); } }); timer.start(); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); int width = getWidth(); int height = getHeight(); int progressWidth = (int) (width * (progress / 100.0)); g2d.setColor(getBackground().darker()); g2d.fillRect(0, 0, progressWidth, height); g2d.setColor(getForeground()); g2d.fillRect(progressWidth, 0, width - progressWidth, height); } }
- 最后,将自定义的JPanel添加到JFrame中:
frame.add(new ProgressBarPanel(), BorderLayout.CENTER);
现在运行程序,你将看到一个简单的进度条动画效果。你可以根据需要调整进度条的样式和动画速度。