无法将JPanel添加到JFrame

时间:2015-02-10 13:55:00

标签: java swing

我正在创建一个TicTacToe游戏。我已将所有后端与ActionListeners放在按钮上,将按钮添加到面板,设置框架等。

然而,当我运行该程序时,我的JPanel似乎没有添加到JFrame中。我尝试过使用不同的布局,仔细检查我是否确实将.add行放入了所有内容中,所有以前的帖子似乎都会导致我认为已经涵盖的内容。

如果这是非常直接的话,我会事先道歉。

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;
    }
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

添加面板后调用这两种方法:

frame.pack();
frame.setVisible(true);
相关问题