如何在不使用 NullLayout 的情况下以循环方式在 JPanel 上定位对象?

How to position objects on JPanel in a circular fashion without using NullLayout?

所以我的问题是:我有一个 class 扩展 JProgressBar 基本上它看起来像一个闪烁的圆圈(它也会根据分配给该指标的任务数量分成多个部分每次将指示器切换到下一个任务时我都需要使用 setUI,这很糟糕,但现在可以了)。我需要将这些圆圈中的 37 个放在 JPanel 上,以便它们形成自己的圆圈。现在我是这样做的:

private void addToPane(JPanel pane){
        pane.setLayout(null);
        Insets insets = pane.getInsets();
        int width = pane.getWidth();
        int height = pane.getHeight();
        Dimension size = new Dimension(30, 30);
        //Dimension mid = new Dimension(width/2, height/2);
        Dimension mid = new Dimension(200, 250);
        int r = 210;
        double revox, revoy, angle = -Math.PI/2;
        double revangle = 2*Math.PI/37;
        for(int i=1; i<38; i++){
            FlashingIndicator templabel = new FlashingIndicator();
            templabel.setPreferredSize(size);
            templabel.setUI(new ProgressIndicator(flash, 0, false));
            templabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
            indicate.add(templabel);
            revox = r*Math.cos(angle);
            revoy = r*Math.sin(angle);
            indicate.get(i - 1).setBounds(insets.left + mid.width + (int) revox, insets.top + mid.height + (int) revoy, size.width, size.height);
            pane.add(indicate.get(i - 1));
            angle-=revangle;
        }
    }

不用说:这很糟糕。我想根据面板的大小定位它们,但是当在 createUIComponents() 中调用函数时(我使用 IntelliJ Idea 的 GUI 生成器)- 面板尚未正确创建,所以 getWidth() 只是returns 0. 由于显而易见的原因,使用 200 和 250 这样的随机数是不好的。似乎普遍的共识是:空布局不好,我不应该使用它。那么问题来了:

我应该使用哪个 LayoutManager 来正确定位指标?我能想到的就是GridLayout,但是我现在这样做的方式指标很好地重叠了一点,使用网格会使它看起来很粗糙。如果我不能为此使用管理器 - 我怎样才能让它依赖于面板的大小?

现在看起来像这样:

重写 paintDeterminate() method in a custom BasicProgressBarUI to render your indicator; a related example is seen here. You can scale the rendering, as shown here, in a way that fills the component; this will obviate the need for a custom layout manager internal to your component. Override getPreferredSize(), as discussed here,以便您的自定义进度指示器能够与封闭布局一起正常工作。