简体   繁体   中英

Setting the background color of JFrame isn't working

I've spent a fair bit of time researching how to change the background color of JFrame, but haven't managed to make anything work. My code in its current state looks like this:

final ImageIcon cardIcon = new ImageIcon("cardImages/aceSpades.gif");

JPanel panel = new JPanel()
    {

        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            cardIcon.paintIcon(this, g, 20, 20);
            }
    };

JFrame window = new JFrame("Deck of Cards");
window.add(panel);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setPreferredSize(new Dimension(200,200));
window.pack();
window.getContentPane().setBackground(Color.green);
window.setVisible(true);

This is the result of all of the searches I've done on stackoverflow, so some help would be appreciated. I know I need to change the content pane instead of the actual frame, but all of my efforts seem to result in the default grey background. Thanks in advance.

edit: panel is for an image that's being loaded in. edit 2: Sounds like panel is blocking the background from changing.

The JPanel you're adding to the frame is blocking the background color. Either set the panel's background color via panel.setBackground or make the panel transparent by setting panel.setOpaque(false) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM