Daryl Beaumont
Daryl Beaumont

Reputation: 23

Having trouble adding a JPanel to a JFrame

I'm creating a TicTacToe game. I've put all the back end with the ActionListeners on buttons, adding the buttons to a panel, setting the frame up etc.

Yet, when I run the program my JPanel doesn't appear to be added to the JFrame. I've tried using different layouts, double checking that I've definitely put the .add line in for everything, and all previous posts seem to lead to things I believe I have covered.

I apologize in advance if this is something really straight forward.

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;      
import javax.swing.*;    

public class BasicGUI {
    private String piece="O";
    protected static Boolean player=true;
    private static final JFrame frame = new JFrame("BasicGUI");
    private static final JPanel panel=new JPanel(new GridLayout(4,3));
    protected static final JButton[] cells= new JButton[9];
    private static final JButton exitButton=new JButton("Exit");
    private static final JButton restartButton=new JButton("Restart");

    public static void main(String[] args){
        createWindow();
        createButtons();
    }

    //Set up frame
    private static void createWindow(){
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(450, 600);
        //Tried adding panel here and below
        //frame.add(panel, BorderLayout.CENTER);
        frame.setVisible(true);
        //Tried using getContentPane too
        //frame.getContentPane().add(panel, BorderLayout.CENTER);
    }

    //Add action listeners to buttons
    private static void createButtons(){
        for(int i=0; i<9; i++){
            cells[i]=new JButton();
            cells[i].addActionListener(new ButtonHandler());
            panel.add(cells[i]);
        }
        exitButton.addActionListener(new ExitHandler());
        restartButton.addActionListener(new RestartHandler());
        panel.add(exitButton);
        panel.add(restartButton);
        frame.add(panel);
    }

    public String getPiece(){
        return piece;
    }
    protected void setPiece(String s){
        this.piece=s;
    }
}

Thank you for any help.

Upvotes: 2

Views: 62

Answers (1)

aurelius
aurelius

Reputation: 4076

after adding the panel call this two methods:

frame.pack();
frame.setVisible(true);

Upvotes: 2

Related Questions