溫馨提示×

Java進度條的動畫效果怎樣實現(xiàn)

小樊
81
2024-10-15 04:09:47
欄目: 編程語言

在Java中,可以使用Swing庫中的Timer類來實現(xiàn)進度條的動畫效果。以下是一個簡單的示例:

  1. 首先,創(chuàng)建一個JFrame窗口并設(shè)置其基本屬性:
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);
    }
}
  1. 接下來,創(chuàng)建一個自定義的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);
    }
}
  1. 最后,將自定義的JPanel添加到JFrame中:
frame.add(new ProgressBarPanel(), BorderLayout.CENTER);

現(xiàn)在運行程序,你將看到一個簡單的進度條動畫效果。你可以根據(jù)需要調(diào)整進度條的樣式和動畫速度。

0