0

我想知道如何将我的按钮定位到 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);
4

1 回答 1

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,以准确显示您尝试过的内容。

于 2013-03-16T19:40:43.177 回答