Java window not setting background color?

丶灬走出姿态 提交于 2019-12-06 08:40:01
mKorbel

1) JFrame can't do that, you have to change Color for content pane e.g.

JFrame.getContentPane().setBackground(myColor)

2) You need to wrap GUI related code (in main method) to the invokeLater

For example:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class GUI {

    public GUI() {
        JFrame frame = new JFrame();
        frame.setTitle("Test Background");
        frame.setLocation(200, 100);
        frame.setSize(600, 400);
        frame.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        frame.getContentPane().setBackground(Color.BLUE);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                GUI gUI = new GUI();
            }
        });
    }
}

Instead of

f.setBackground(Color.RED);

call

f.getContentPane().setBackground(Color.RED);

The content pane is what is displayed.

As a side note, here's a JFrame tip: you can call f.add(child) and the child will be added to the content pane for you.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!