以下是一个简单的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窗口,将自定义的组件添加到窗口中,并启动了一个线程来模拟进度条的进度变化。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: java子类怎么访问父类成员