Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }

}
like image 592
user2980816 Avatar asked Jan 30 '26 11:01

user2980816


1 Answers

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.

like image 120
camickr Avatar answered Feb 01 '26 02:02

camickr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!