user2980816
user2980816

Reputation: 61

How to add a JPanel to a JFrame?

I am creating a minefield game. I need to add two buttons, Clear and Done in their own separate JPanel below the grid and cannot figure out how. Below is the code for the game grid. Thanks!

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MineField extends JPanel implements ActionListener{

    public static void main(String[] args) {
        MineField g = new MineField();
        JFrame frame = new JFrame("Mine Field");
        frame.add(g);
        frame.setSize(400,400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    private JButton squares[][];

    public MineField(){
        this.setSize(400,400);
        this.setLayout(new GridLayout(5,5));
        squares = new JButton[5][5];
        buildButtons();
    }

    int [][] num = new int [5][5];

    private void buildButtons(){
        for(int i=0;i<5;i++){
            for(int j=0;j<5;j++){
                squares[i][j] = new JButton();
                squares[i][j].setSize(400,400);
                this.add(squares[i][j]);
            }
        }
    }

    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
    }

}

Upvotes: 3

Views: 21944

Answers (3)

BilalDja
BilalDja

Reputation: 1092

You should modify your code a litte bit, well you can add those few lines :

JPanel thePanel = (JPanel)frame.getContentPane(); // this variable will manage the JFrame content

thePanel.setLayout(new BorderLayout()); // BorderLayout to seperat the Frame on 5 section Center, North, South, Est, West

JPanel btnPanel = new JPanel(new FlowLayout(FlowLayout.Right)); // this JPanel made to contain the buttons
btnPanel.add(clearBtn);
btnPanel.add(doneBtn);

thePanel.add(g, BorderLayout.CENTER);
thePanel.add(btnPanel, BorderLayout.SOUTH);

hope that helps, Salam

Upvotes: 0

Tdorno
Tdorno

Reputation: 1571

We can add components to each other by using the .add() method.

Two practical usages of this would be:

mainPanel.add(topPanel); //panel to panel

or as Quincunx said

JFrame.add(Component c); //component to jframe

Upvotes: 0

camickr
camickr

Reputation: 324098

By default a JFrame uses a BorderLayout.

So currently your MineField class is added to the CENTER of the border layout.

If you want another panel on the frame you can use:

JPanel south = new JPanel();
south.add(clearButton);
south.add(doneButton);
frame.add(south, BorderLayout.SOUTH);

Read the section from the Swing tutorial on How to Use BorderLayout for more information and examples to better understand how layout managers work.

Upvotes: 7

Related Questions