I'm making a menu for my game. I want the background to be animated. Therefore I use a JLabel with a gif. On top of this I want my buttons. But, I want some air between the buttons and the left side of the window. That gives me trouble.
This is my result. It's pretty good! But I can't get the gray bar to disappear! Also, it looks like my background JLabel is being pushed a tad to the right.
I have three classes:
1 The launcher that creates the JFrame
public class Launcher extends JFrame{
public int speed = 0;
int c = 0;
public final static int WIDTH = 1200;
public final static int HEIGHT = 800;
Game game;
JFrame frame;
public static void main(String[] args) throws IOException{
new Launcher();
}
public Launcher() throws IOException{
game = new Game();
JFrame frame = new JFrame("PingPong!");
frame.add(game);
frame.setFocusable(true);
frame.setPreferredSize(new Dimension(WIDTH, HEIGHT) );
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
}
}
2 The Game that creates a JPanel with OverlayLayout
public class Game extends JPanel implements Runnable{
public State menuState;
public Game() throws IOException{
this.removeAll();
this.setLayout(new OverlayLayout(this));
menuState = new MenuState(this, handler);
}
}
3 And finally my MenuState that creates a JPanel with BoxoLayout where I add the elements
public class MenuState extends State{
JPanel menuPanel;
JLabel background;
private Icon backgroundIcon;
private Icon newgameIcon;
private Icon loadgameIcon;
private JButton newGame;
private JButton loadGame;
Border border;
public MenuState(Game game, Handler handler) {
super(game, handler);
init();
}
public void init(){
menuPanel = new JPanel();
menuPanel.setLayout(new BoxLayout(menuPanel, BoxLayout.PAGE_AXIS));
menuPanel.setBackground(Color.green);
menuPanel.add(Box.createHorizontalStrut(100));
menuPanel.setVisible(true);
menuPanel.setOpaque(false);
Box left = Box.createVerticalBox();
backgroundIcon = new ImageIcon("res/images/menu/back.gif");
background = new JLabel(backgroundIcon);
newGame = new JButton("New Game");
loadGame = new JButton("Load Game");
game.add(menuPanel);
menuPanel.add(newGame);
left.add(newGame);
left.add(Box.createRigidArea(new Dimension(0, 40)));
left.add(loadGame);
left.add(Box.createRigidArea(new Dimension(0, 300)));
left.setOpaque(false);
menuPanel.add(left);
background.setSize(1200, 800);
game.add(background);
}
}
I have tried different order of adding the components. I have tried Opacity true and false.
I wish I could just set newGame.setLocation(100, 500)
and the box would be placed where I wanted it.