云服务器免费试用

java圆形进度条怎么实现

服务器知识 0 1337

以下是一个简单的Java圆形进度条的实现代码:

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窗口,将自定义的组件添加到窗口中,并启动了一个线程来模拟进度条的进度变化。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942@qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: java圆形进度条怎么实现
本文地址: https://solustack.com/31114.html

相关推荐:

网友留言:

我要评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。