I was wondering how I could position my button to the center of the JPanel. As of now the button is located on top of my "mms" (used as my background image) but centered at the upper edge of the panel. How could I position this button to be in the center of my image?
//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);
Just use the default constraints:
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();
}
});
}
}
In the future post an SSCCE with your question to show exactly what you have tried.