如何在java swing中创建循环进度组件

时间:2016-04-13 09:50:13

标签: java swing

嘿伙计们我找到了这门课,但我不知道如何使用它。我是JAVA的新手,所以在这里轻松一下就是代码。我尝试过几种方法,但没有任何效果。边缘看起来很光滑。

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.Arc2D;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import javax.swing.JComponent;
import javax.swing.plaf.basic.BasicProgressBarUI;

class ProgressCircleUI extends BasicProgressBarUI {
  @Override public Dimension getPreferredSize(JComponent c) {
    Dimension d = super.getPreferredSize(c);
    int v = Math.max(d.width, d.height);
    d.setSize(v, v);
    return d;
  }
  @Override public void paint(Graphics g, JComponent c) {
    Insets b = progressBar.getInsets(); // area for border
    int barRectWidth  = progressBar.getWidth()  - b.right - b.left;
    int barRectHeight = progressBar.getHeight() - b.top - b.bottom;
    if (barRectWidth <= 0 || barRectHeight <= 0) {
      return;
    }

    // draw the cells
    Graphics2D g2 = (Graphics2D) g.create();
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                        RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setPaint(progressBar.getForeground());
    double degree = 360 * progressBar.getPercentComplete();
    double sz = Math.min(barRectWidth, barRectHeight);
    double cx = b.left + barRectWidth  * .5;
    double cy = b.top  + barRectHeight * .5;
    double or = sz * .5;
    double ir = or * .5; //or - 20;
    Shape inner = new Ellipse2D.Double(cx - ir, cy - ir, ir * 2, ir * 2);
    Shape outer = new Arc2D.Double(
        cx - or, cy - or, sz, sz, 90 - degree, degree, Arc2D.PIE);
    Area area = new Area(outer);
    area.subtract(new Area(inner));
    g2.fill(area);
    g2.dispose();

    // Deal with possible text painting
    if (progressBar.isStringPainted()) {
      paintString(g, b.left, b.top, barRectWidth, barRectHeight, 0, b);
    }
  }
}

事情是我不知道如何让它发挥作用。有什么帮助吗?

2 个答案:

答案 0 :(得分:3)

您需要为组件设置它或将其全局注册为L&amp; F默认值。

myProgressBar.setUI(new ProgressCircleUI());

UIManager.put("ProgressBarUI", ProgressCircleUI.class.getName());

注意:在某些情况下,Swing可以重置由第一种方式设置的UI。因此,如果第一种方法不起作用,请尝试第二种方式。

更新:还有第三种方法:您可以创建JProgressBar的子类并使用它而不是普通的子类。

public class JCircleProgressBar extends JProgressBar {

    public void setUI(ComponentUI newUI) {
        super.setUI(new ProgressCircleUI());
    }
}

答案 1 :(得分:1)

JProgressBar progress = new JProgressBar();
// use JProgressBar#setUI(...) method
progress.setUI(new ProgressCircleUI());
progress.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
progress.setStringPainted(true);
progress.setFont(progress.getFont().deriveFont(24f));
progress.setForeground(Color.ORANGE);

int in = Ingeter.parseInt(nameOfTextField.getValue);   
progress.setValue(in);

您需要创建一个进度条并将该类添加到进度条(progress.setUI(new ProgressCircleUI()); 然后将进度条添加到面板中。您上面的代码是该类 会创建一个圆形进度条。