I am making code for the game connect four. I create a JPanel with a 2 dimensional array of JButtons and use pack() to put it into the JFrame. When i set the size of the JFrame in the main method, the JPanel remains small. How do I get this to work? thanks
here's the constructor
public ConnectFour(int boardsize, int winlength){
super();
boardSize = boardsize;
winLength = winlength;
Container c = getContentPane();
JPanel board = new JPanel(new GridLayout(boardSize, boardSize));
button = new JButton[boardSize][boardSize];
//loop creates a 2 dimensional JButton array
for(int i =0; i%26lt;boardSize; i++)
{
for(int j =0; j%26lt;boardSize; j++)
{
button[j][i] = new JButton();
board.add(button[j][i]);
button[j][i].addActionListener(this);
}
}
c.add(board);
pack();
-------------------------
this.setVisible(true);
this.setSize(700,700);
c.setSize(700,700);
JPanel size issue in java?
GridLayout does not honor component size or use any sizing rules (doesn't call getPreferredSize() on the contained components, etc.). Your JButtons don't have any content either (no String or Icon), so they are also very small.
Try putting your board inside another JPanel that has a FlowLayout (default will work), as FlowLayout will attempt to preserve preferred size. Then add the enclosing JPanel to the content pane, vice the board.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment