以下是一個簡單的Java圓形進度條的實現代碼:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class CircleProgressBar extends JComponent {
private int progress;
public CircleProgressBar() {
super();
setPreferredSize(new Dimension(100, 100));
progress = 0;
}
public void setProgress(int progress) {
this.progress = progress;
repaint();
}
@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 diameter = Math.min(width, height);
int x = (width - diameter) / 2;
int y = (height - diameter) / 2;
g2d.setColor(Color.LIGHT_GRAY);
g2d.fillOval(x, y, diameter, diameter);
g2d.setColor(Color.BLUE);
g2d.fillArc(x, y, diameter, diameter, 90, -progress * 360 / 100);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Circle Progress Bar");
CircleProgressBar progressBar = new CircleProgressBar();
frame.getContentPane().add(progressBar);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Thread thread = new Thread(() -> {
for (int i = 0; i <= 100; i++) {
progressBar.setProgress(i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
});
}
}
這個實現代碼使用了Java Swing的JComponent類,繼承它可以自定義一個組件。在這個組件上繪制一個圓形進度條,使用了Graphics2D類的fillOval和fillArc方法。在main方法中,我們創建了一個JFrame窗口,將自定義的組件添加到窗口中,并啟動了一個線程來模擬進度條的進度變化。