简体   繁体   中英

JFrame background color will not change

I have viewed many answers here and changed my code accordingly but it still does not work correctly. Can someone help me fix it please?

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

public class LoginGUI extends JFrame {



    LoginGUI() { 

        Container c = getContentPane();
        c.setBackground(Color.BLACK);
        JPanel p = new JPanel();
        JLabel title = new JLabel("HTML Generator");
        title.setForeground(Color.black);
        p.add(title);
        c.add(p);
        title.setOpaque(true);

        setSize(400, 400);
        setVisible(true);
    }

    public static void main(String[] args) { 
        new LoginGUI();
    }

}

JPanel 's opaque property is true by default, and JFrame default layout is BorderLayout . Adding only one component (the JPanel ) to the frame, will stretch it the full size of the frame, as that's what BorderLayout will do. So, an opaque panel covering the entire frame, that explains the results you are getting.

Three simple fixes. Either set the JPanel opaque property to false, or just set the background on the JPanel , or set the layout of the frame to GridBagLayout or FlowLayout

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