您可以通过中心而不是左上角来绑定 JComponent 吗?

Can you bound a JComponent by the center instead of the upper left?

我正在尝试定位一些 JButton 对象,但我需要坐标来根据按钮的中心定位它们,而不是默认的左上角,有没有办法去做这个?

        //Button L1 (Left 1)
   buttonL1 = new JButton( "Button L1" ); 
   buttonL1.setBounds( 150, 140, (int) rWidth, (int) rHeight );
   c.add( buttonL1);

   //Button L2 (Left 2)
   buttonL2 = new JButton( "Button L2" ); 
   buttonL2.setBounds( 150, 340, (int) rWidth, (int) rHeight); 
   c.add( buttonL2 );

   //Button R3 (Right 3)
   buttonR3 = new JButton( "Button R3" ); 
   buttonR3.setBounds( 580, 140, (int) rWidth, (int) rHeight); 
   c.add( buttonR3 );

   //Button R4 (Right 4)
   buttonR4 = new JButton( "Button R4" ); 
   buttonR4.setBounds( 580, 340, 20, 20 ); 
   c.add( buttonR4 );

可以使用一系列容器来实现此布局,其中 GridBagLayout 使按钮居中 – 每个容器都位于 GridLayout 内,以将按钮对齐到列和行中。

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class CenteredButtons {

    private JComponent ui = null;

    CenteredButtons() {
        initUI();
    }

    public void initUI() {
        if (ui!=null) return;

        // adjust numbers to need for minimum size/padding etc.
        ui = new JPanel(new GridLayout(0,2,40,10));
        ui.setBorder(new EmptyBorder(30,30,30,30));
        Insets margin = new Insets(10, 15, 10, 15);

        for (int i=1; i<5; i++) {
            JPanel p = new JPanel(new GridBagLayout());
            JButton btn = new JButton("Button " + i);
            btn.setMargin(margin);
            p.add(btn);
            ui.add(p);
        }
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception useDefault) {
                }
                CenteredButtons o = new CenteredButtons();

                JFrame f = new JFrame("Centered Buttons");
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.setLocationByPlatform(true);

                f.setContentPane(o.getUI());
                f.pack();
                f.setMinimumSize(f.getSize());

                f.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}