你能用中心而不是左上角绑定一个JComponent吗?

时间:2015-03-24 00:34:23

标签: java swing jbutton layout-manager

我试图定位一些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 );

For example, the bottom right button is positioned in terms of the top left hand corner, I need the coordinates I've given all my buttons to be the centre of where they get positioned

1 个答案:

答案 0 :(得分:3)

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

enter image description here enter image description here enter image description here

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