java 摆动设置框背景颜色不起作用
java swing setting frame background color not working
我正在尝试使用 java swing 创建井字游戏。我创建了一个框架并将其背景设置为一种颜色。问题是框架的背景颜色没有改变,我尝试使用其他颜色但背景颜色始终是白色。
这是代码:
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);
}
}
您试图设置内容窗格的背景:
frame.getContentPane().setBackground(Color.BLACK);
但随后您将“标题面板”添加到框架中:
frame.add(title_panel);
因此您的标题面板完全覆盖了内容面板。
您需要设置标题面板的背景颜色。
代码的其他问题:
- 不要在组件上使用 setBounds()。布局管理器将确定每个组件的size/location。
- 您应该只在所有组件都添加到框架后调用 setVisible(...) 方法。
- 您应该
pack()
框架,然后才能使框架可见。这将确保所有组件都以其首选大小显示。
- 应在
Event Dispatch Thread (EDT)
上创建 GUI。
阅读Swing tutorial。 Concurrency
部分将解释为什么这很重要。本教程中的所有示例都将演示如何确保代码在 EDT 上。
我正在尝试使用 java swing 创建井字游戏。我创建了一个框架并将其背景设置为一种颜色。问题是框架的背景颜色没有改变,我尝试使用其他颜色但背景颜色始终是白色。 这是代码:
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);
}
}
您试图设置内容窗格的背景:
frame.getContentPane().setBackground(Color.BLACK);
但随后您将“标题面板”添加到框架中:
frame.add(title_panel);
因此您的标题面板完全覆盖了内容面板。
您需要设置标题面板的背景颜色。
代码的其他问题:
- 不要在组件上使用 setBounds()。布局管理器将确定每个组件的size/location。
- 您应该只在所有组件都添加到框架后调用 setVisible(...) 方法。
- 您应该
pack()
框架,然后才能使框架可见。这将确保所有组件都以其首选大小显示。 - 应在
Event Dispatch Thread (EDT)
上创建 GUI。
阅读Swing tutorial。 Concurrency
部分将解释为什么这很重要。本教程中的所有示例都将演示如何确保代码在 EDT 上。