java swing setting frame background color not working

Gabriele

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);
    }
}
camickr

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:

  1. Don't use setBounds() on a component. The layout manager will determine the size/location of each component.
  2. You should only invoke the setVisible(...) method AFTER all components have been added to the frame.
  3. You should pack() the frame before making the frame visible. This will ensure all components are displayed at their preferred sizes.
  4. 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.

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

Editado en
0

Déjame decir algunas palabras

0Comentarios
Iniciar sesiónRevisión de participación posterior

Artículos relacionados

Vaadin setting background not working

Custom UIButton background color not working

CSS td conditional background color setting

Chart.js tooltip background color setting

Esquema de color modular Java Swing

Tkinter button background color is not working in mac os

Bottom Tab bar background color not working

background-color css property not working in table

Not able to change the Background color of Frame inside CollectionView in Xamarin forms

java, swing - Adding a JlayeredPane in JScrollPane only shows a blank background

How to draw a animation upon a background image in Java Swing

Why it is showing error while setting background color using Colors.color_name[value] in flutter?

Java - Swing configurando el color del texto en JTextArea

CSS background-color transition not working in specific browsers (desktop + mobile)

Angular background-color in global styles.css not working

Swing - Dispose a frame

Swing - Dispose a frame

Java Swing - ScheduledExecutor Service Stops working upon UserInput

PWA manifest.json - "theme_color" and "background_color" not working, splash screen not showing on android device

Android Studio 4.1 bordered Button loses border setting background color in kotlin code

Splitting page vertically in xslfo region-body and setting background color for one section

Java Swing | Ключевой слушатель вообще не отвечает

Java Swing рисует прямоугольник

Панель меню Java не отображается в графическом интерфейсе Swing, несмотря на установку кадра

Транспортировка значений в массивах в пределах области видимости в Swing - java

Реализовать эффект флуктуации для спрайта в Java Swing

Фокус окна диалога Java Swing

Несколько прослушивателей действий Java Swing

Рекомендуемые макеты Java Swing для использования для двух таблиц одинакового размера и кнопок