I have been working on a main menu screen. I use a card layout because I have a splash screen that shows up before the main menu screen. Once the user clicks the "Continue" button on the splash screen, they are brought to the main menu screen.
I can't add a screenshot because I don't have a high enough reputation but as of now the buttons are pushed off to the side, I assume because of the card layout.
Is there any way that I can place the button on top of the main menu screen image?
Here is my code for the window:
package edu.ycp.cs.Main;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Window {
JPanel cards; // a panel that uses CardLayout
final static String SPLASHSCREEN = "SplashScreen";
final static String MAINMENU = "MainMenu";
public void addComponentToWindow(Container pane) {
// Put the JComboBox in a JPanel to get a nicer look.
JPanel gameWindow = new JPanel(); // use FlowLayout
// Create the "cards".
JPanel card1 = new JPanel();
JButton continueButton = new JButton("Continue");
continueButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout) (cards.getLayout());
cl.show(cards, MAINMENU);
}
});
card1.add(new SplashScreen());
card1.add(continueButton);
JPanel card2 = new JPanel();
JButton menuButton1 = new JButton("PLAY!");
JButton menuButton2 = new JButton("HIGH SCORES");
card2.add(new MainMenuScreen());
card2.add(menuButton1);
card2.add(menuButton2);
cards = new JPanel(new CardLayout());
cards.add(card1, SPLASHSCREEN);
cards.add(card2, MAINMENU);
pane.add(gameWindow, BorderLayout.PAGE_START);
pane.add(cards, BorderLayout.CENTER);
}
}
Any suggestions on how to get the button on top of the image?
Your
JPanel
that contains your 2menuButton
andMenuScreen
doesn't have a layout. Use one likeGridBagLayout
and set the buttons on top. You could use another layout, that's up to you.I used buttons only to show you a simple example for
GridBagLayout
and suggest you check Oracle's page on that layout if you wish to use it.If your splash screen only has that one button, you could try making your entire splash image a button, as in this example: Java: using an image as a button
You could edit your existing splash screen image to add a Continue Button inside the image itself. Of course the user would be able to click anywhere (as it would be one huge image button).
Sounds cheesy, I know. But it might be a quick-and-dirty way to get close enough to what you want.
A JPanel use a FlowLayout. So when you add two components to it they are just painted beside each other.
You want the component to be painted on top of each other so you need to do something like: