سؤال

Im trying to create the so called "15 game" , which is like a slide puzzle with 16 buttons, 15 of them with numbers 1-15 and a empty one. Clicking on a button next to the empty one will switch position with the clicked button and the empty one. BUt now I am trying to set up the gui, which is made with Swing, gridlayout and 16 buttons. BUt i cant make it to work, here is my code:

package game;

import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JPanel;



public class TheGame{



public static void main(String[] args){

    TheGame game = new TheGame();

}


public TheGame(){

    JMenuBar menubar = new JMenuBar();
    JFrame frame = new JFrame("15Game");
    GridLayout grid = new GridLayout(4,4,3,3);
    JPanel panel = new JPanel();

    Cell cell1 = new Cell("1");
    Cell cell2 = new Cell("2");
    Cell cell3 = new Cell("3");
    Cell cell4 = new Cell("4");
    Cell cell5 = new Cell("5");

    Cell cell6 = new Cell("6");
    Cell cell7 = new Cell("7");
    Cell cell8 = new Cell("8");
    Cell cell9 = new Cell("9");
    Cell cell10 = new Cell("10");

    Cell cell11 = new Cell("11");
    Cell cell12 = new Cell("12");
    Cell cell13 = new Cell("13");
    Cell cell14 = new Cell("14");
    Cell cell15 = new Cell("15");

    Cell cellEmpty = new Cell("");

    panel.add(cell1);
    panel.add(cell2);
    panel.add(cell3);
    panel.add(cell4);
    panel.add(cell5);

    panel.add(cell6);
    panel.add(cell7);
    panel.add(cell8);
    panel.add(cell9);
    panel.add(cell10);

    panel.add(cell11);
    panel.add(cell12);
    panel.add(cell13);
    panel.add(cell14);
    panel.add(cell15);

    panel.add(cellEmpty);

    panel.setLayout(grid);
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);

}

}

And here is Cell:

package game;

import javax.swing.JButton;

public class Cell extends JButton {

//Variables

public Cell(String s){

    this.setText(s);

}

When i create this, it only pop up a small empty gui window, with no buttons at all. Why is that, and what am I doing wrong?

هل كانت مفيدة؟

المحلول

You need to add the panel that contains the buttons to the frame

frame.add(panel);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top