圈中的组件

时间:2012-01-13 22:50:14

标签: java swing jpanel layout-manager

我想在一个圆圈中放置10个JPanel。每个小组的大小相同,两个小组之间的长度应相同。因此,我认为最简单的方法是获取null-Layout并通过polarcoordiantes手动计算边界框:

JPanel panel = new JPanel(null);

int r = 100;
int phi = 90;

for (int i = 0; i < 10; i++) {
    JPanel x = new JPanel();
    x.setBackground(Color.red);
    x.setBounds((int) (r * Math.sin(phi)) + 100, (int) (r * Math.cos(phi)) + 100, 4, 4);

    panel.add(x);
    phi = (phi + 36) % 360;
}

但那不起作用!有些项目在圈子上,其中一些是像素关闭...我有一个不知道为什么?! 我也找不到可以为我做的那个LayoutManager,那该怎么办?

2 个答案:

答案 0 :(得分:6)

虽然X-Zero给出了正确答案(他的帖子中有1+),但我创建了一个SSCCE:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.*;

public class PanelsOnCircle extends JPanel {
   private static final int RADIUS = 100;
   private static final int GAP = 20;
   private static final int PREF_W = 2 * RADIUS + 2 * GAP;
   private static final int PREF_H = PREF_W;
   private static final int SLICES = 10;
   private static final int SIDE = 4;

   public PanelsOnCircle() {
      JPanel panel = new JPanel(null);

      for (int i = 0; i < SLICES; i++) {
         double phi = (i * Math.PI * 2) / SLICES; 
         JPanel smallPanel = new JPanel();
         smallPanel.setBackground(Color.red);
         int x = (int) (RADIUS * Math.sin(phi) + RADIUS - SIDE / 2) + GAP;
         int y = (int) (RADIUS * Math.cos(phi) + RADIUS - SIDE / 2) + GAP;
         smallPanel.setBounds(x, y, SIDE, SIDE);

         panel.add(smallPanel);
      }

      setLayout(new BorderLayout());
      add(panel);
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   private static void createAndShowGui() {
      PanelsOnCircle mainPanel = new PanelsOnCircle();

      JFrame frame = new JFrame("PanelsOnCircle");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

请接受X-Zero的答案,因为他是第一个。

答案 1 :(得分:5)

您的代码很好,但您错过了一条非常重要的信息 - 三角函数预计弧度 的角度

phi中包含对Math.toRadians(double)的评价,您将获得所期望的布局。

(旁注,我一直在考虑如何做这样的事情,谢谢你的例子)

相关问题