Adding buttons dynamically to JFrame or a layeredPane
public ChessGameDemo(){
Dimension boardSize = new Dimension(600, 600);
// Using a Layered Pane
layeredPane = new JLayeredPane();
add(layeredPane);
layeredPane.setPreferredSize(new Dimension(700,700));
//Create a reset button that will reset the game
JButton button = new JButton("Reset");
button.setPreferredSize(new Dimension(50,50));
add(button,BorderLayout.EAST);
//Add the chessboard to the Layered Pane
chessBoard = new JPanel();
layeredPane.add(chessBoard, JLayeredPane.DEFAULT_LAYER);
chessBoard.setLayout( new GridLayout(8, 8) );
chessBoard.setPreferredSize( boardSize );
chessBoard.setBounds(0, 0, boardSize.width, boardSize.height);
for (int i = 0; i < 64; i++) {
JPanel square = new JPanel( new BorderLayout() );
chessBoard.add( square );
int row = (i / 8) % 2;
if (row == 0)
square.setBackground( i % 2 == 0 ? Color.blue : Color.white );
else
square.setBackground( i % 2 == 0 ? Color.white : Color.blue );
}
As you can see here, I am creating a chess board in a panel and adding
that to a layered pane, which in turn is part of the frame. The idea is to
have a menu bar and a couple of buttons to make it all look more
presentable. But when I try to add the button it captures the entire
height of the frame ignoring the dimension I have specified. I just see
one tall button stretching the entire height of the window/frame. What is
the mistake here? How do I add normal sized buttons dynamically here? that
sits well next to the chessboard?
No comments:
Post a Comment