JButton使用GBC / GBL定位在JPanel上

时间:2013-03-16 19:26:06

标签: java swing jpanel layout-manager gridbaglayout

我想知道如何将按钮放在JPanel的中心。截至目前,按钮位于我的“mms”(用作我的背景图像)的顶部,但是以面板的上边缘为中心。如何将此按钮定位在图像的中心?

//MainMenu setup
JPanel card2 = new JPanel();
card2.setLayout(new GridBagLayout());       
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(2,2,2,2);
gbc.anchor = GridBagConstraints.CENTER;
MainMenuScreen mms = new MainMenuScreen();
card2.add(mms, gbc);
mms.add(menuButton1, gbc);

1 个答案:

答案 0 :(得分:1)

只需使用默认约束:

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

public class SSCCE extends JPanel
{
    public SSCCE()
    {
        setLayout( new GridBagLayout() );

        JButton button = new JButton("Centered");
        add(button, new GridBagConstraints());
    }

    private static void createAndShowUI()
    {
        JFrame frame = new JFrame("SSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new SSCCE() );
        frame.pack();
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

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

将来发布SSCCE并提出问题,以准确显示您尝试过的内容。