I am trying to create a tic tac toe game using java swing. I created a frame and set its background to a color. The problem is that the background color of the frame is not changing, I tried using other colors but the background color is always white. here is the code:
public class TicTacToe implements ActionListener {
Random random = new Random();
JFrame frame = new JFrame();
JPanel title_panel = new JPanel();
JPanel button_panel = new JPanel();
JLabel textField = new JLabel();
JButton[] button = new JButton[9];
boolean player1_turn;
TicTacToe () {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800,800);
frame.setVisible(true);
frame.setTitle("Tic Tac Toe");
frame.setLayout(new BorderLayout());
frame.getContentPane().setBackground(Color.BLACK);
textField.setBackground(new Color(0x084887));
textField.setForeground(new Color(0xF58A07));
textField.setText("Tic-Tac-Toe");
textField.setFont(new Font("Ink Free",Font.BOLD,75));
textField.setOpaque(true);
textField.setHorizontalAlignment(JLabel.CENTER);
title_panel.setLayout(new BorderLayout());
title_panel.setBounds(0,0,800,100);
title_panel.add(textField, BorderLayout.NORTH);
frame.add(title_panel);
}
}
CodePudding user response:
You attempt to set the background of the content pane:
frame.getContentPane().setBackground(Color.BLACK);
But then you add the "title panel" to the frame:
frame.add(title_panel);
So your title panel completely covers the content pane.
You need to set the background color of your title panel.
Other issues with the code:
- Don't use setBounds() on a component. The layout manager will determine the size/location of each component.
- You should only invoke the setVisible(...) method AFTER all components have been added to the frame.
- You should
pack()
the frame before making the frame visible. This will ensure all components are displayed at their preferred sizes. - The GUI should be created on the
Event Dispatch Thread (EDT)
.
Read the Swing tutorial. The section on Concurrency
will explain why this is important. All example in the tutorial will demonstrate how to make sure code is on the EDT.