我试图更改JFrame
的背景颜色,但它永远不起作用。这是我的代码:
package com.company;
import javax.swing.*;
import java.awt.*;
public class Main extends JPanel
{
private static JFrame frame = new JFrame();
private static int rand = 3;
public static void main(String[] args)
{
frame.getContentPane().add(new Main());
frame.setSize(1960, 1070);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBackground(Color.BLACK);
frame.setVisible(true);
frame.setResizable(false);
}
}
您需要通过getContentPane
来更改框架的背景颜色:
frame.getContentPane().setBackground(Color.BLACK);
更改要添加的 JPanel 的颜色,而不是 JFrame。如果你在它上面添加一个白色的JPanel,你不会看到黑色的JFrame!
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ChangeColor extends JPanel {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createGUI();
}
});
}
public static void createGUI() {
JFrame frame = new JFrame();
ChangeColor c = new ChangeColor();
c.setBackground(Color.BLACK);
frame.add(c);
frame.setSize(1960, 1070);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setResizable(false);
}
}