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);
}
}
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:
pack()
the frame before making the frame visible. This will ensure all components are displayed at their preferred sizes.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.
Este artículo se recopila de Internet, indique la fuente cuando se vuelva a imprimir.
En caso de infracción, por favor [email protected] Eliminar
Déjame decir algunas palabras