Position Components in a circle

I want to place 10 JPanels in a circle. Each panel is the same size, and the length between the two panels must be the same. Thus, the easiest way is to capture the null layout and calculate the bounding box manually through the coordinate fields:

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;
}

But it does not work! Some objects are in a circle, some of them are pixels ... I have no idea why ?! I also cannot find a LayoutManager that can do this for me, and what should I do?

+5
source share
2 answers

Your code is good, but you missed one very important information - trigonometric functions expect angles in radians not .

phi Math.toRadians(double), .

( , , - , )

+5

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 , .

+6

All Articles