I was wondering why my button does not show up on the panel until AFTER I hover my mouse over where it would be? It also disappears again if I resize the window. The MainMenuScreen is just an image I use as my background 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();
mms.setLayout(new FlowLayout());
card2.add(mms);
card2.add(menuButton1, gbc);
Here is how I setup by background image.
public class MainMenuScreen extends JPanel{
private static final long serialVersionUID = 1L;
private BufferedImage background;
public MainMenuScreen() {
try {
background = ImageIO.read(new File("M&M Arcade.png"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(800, 600);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (background != null) {
int x = (getWidth() - background.getWidth());
int y = (getHeight() - background.getHeight());
g.drawImage(background, x, y, this);
}
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(Color.white);
}
}
The JButton
doesn't show up beacuse you are using the same GridBagConstraints
values for your MainMenuScreen
component and your JButton
menuButton1
, i.e. they exist at the same location. Once the values of gbc
are adjusted, the button will appear. Also better to consistently use the correct overloaded method of add when adding to a container with GridBagLayout
.
Edit:
There have been numerous discussions on how to implement background images on JPanel
containers. A notable one is Background Panel.