So I’ trying to create a tictactoe board, however it isn’t showing up with anything.
(There is a main class but it just creates a “GameBoard” )
Any help will be greatly appreciated, thank you in advance.
So I added the components can’t believe I forgot that, I must be tired.
However now all I get is one red square.
public GameBoard()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(0, 0, 195, 215);
frame.setSize(new Dimension (300, 400));
int count = 1;
Rectangle board[][] = new Rectangle[3][3];
for (int row = 0; row < board.length; row++){
for (int col = 0; col < board[row].length; col++){
if (count == 2){
board[row][col] = new Rectangle(1,1,1,1);
board[row][col].setBackground(Color.RED);
frame.add(board[row][col]);
count--;
} else {board[row][col] = new Rectangle(1,1,1,1);
board[row][col].setBackground(Color.BLACK);
frame.add(board[row][col]);
count++;
}
}}
frame.pack();
frame.setVisible(true);
}}
Rectangle Class:
public class Rectangle extends JComponent {
public Rectangle(int x, int y, int w, int h) {
super();
setBounds(x, y, w, h);
setBackground(Color.black);
}
public void paint(Graphics g) {
g.setColor( getBackground() );
g.fillRect(0, 0, getWidth()-1, getHeight()-1);
paintChildren(g);
}
}
Logically, you are missing the step to actually add the boards onto your JFrame:
in your for-loop, so you are creating the JFrame and the Rectangles, but never adding the rectangles to your JFrame.
As @AmitD pointed out, JFrame.add() doesn’t accept Rectangles, so you’ll need to write a class that extends JComponent to paint the Rectangles inside its
paintComponent()method.To address the display problem (only seeing red):
You’ll need to set a Layout Manager for your
JFrame; I thinkGridLayoutwould be most appropriate in your case: