Inline Code Example Here

class MainMenu extends JPanel {

public MainMenu() {

    this.setLayout(null);

    JButton newGame = new JButton("New Game");
    JButton loadGame = new JButton("Load Game");
    JButton scoreGame = new JButton("High Score");
    JButton exitGame = new JButton("Exit Game");

    this.add(newGame);
    newGame.setBackground(Color.white);
    newGame.setPreferredSize(new Dimension(180, 50));
    newGame.setFont(new Font("Fixedsys", 1, 25));

    this.add(loadGame);
    loadGame.setBackground(Color.white);
    loadGame.setPreferredSize(new Dimension(180, 50));
    loadGame.setFont(new Font("Fixedsys", 1, 25));



    this.add(scoreGame);
    scoreGame.setBackground(Color.white);
    scoreGame.setPreferredSize(new Dimension(180, 50));
    scoreGame.setFont(new Font("Fixedsys", 1, 25));




    this.add(exitGame);
    exitGame.setBackground(Color.white);
    exitGame.setPreferredSize(new Dimension(180, 50));
    exitGame.setFont(new Font("Fixedsys", 1, 25));


    Insets insets = this.getInsets();

    Dimension size = newGame.getPreferredSize();
    newGame.setBounds(450 + insets.right, 80 + insets.top,
            size.width, size.height);

    size = loadGame.getPreferredSize();
    loadGame.setBounds(450 + insets.left, 130 + insets.top,
            size.width, size.height);


    size = scoreGame.getPreferredSize();
    scoreGame.setBounds(450 + insets.left, 180 + insets.top,
            size.width, size.height);

    size = exitGame.getPreferredSize();
    exitGame.setBounds(450 + insets.left, 230 + insets.top,
            size.width, size.height);

}

public void paint(Graphics g) {
    Image img1 = Toolkit.getDefaultToolkit().getImage("snake.jpg");
    g.drawImage(img1, 0, 0, this);
}

public static void main(String[] args) {
    MainMenu game = new MainMenu();
    JFrame frame = new JFrame();
    frame.setSize(655, 338);
    frame.add(game);
    frame.setVisible(true);
    frame.setTitle("Snake");
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}}

I´m new at java. And i want to know how to put Jbuttons in JPanel in mainMenu. When i compilate this gui i see image but the buttons are hidden behind image.

kubiak
Deleted Member

Its tricky to get the buttons to be drawn after you draw the image. One thing you should override the paintComponent method for swing classes.

other than that you could use an overlayLayout
1) create a JPanel and set its layout to OverlayLayout
2) create a new JPanel and add the image to this then add this JPanel to the JPanel created in 1
3) create another JPanel and add your buttons here then add this JPanel to the JPanel created in 1
4) add the JPanel created in 1 to the JFrame.

quickly example of that JPanels...zeroliken? please :)

This article has been dead for over six months. Start a new discussion instead.