简体   繁体   中英

Can't set background color

For some reason my background just doesn't turn blue. Does anyone know how to solve this with keeping everything inside?

I've been trying to fix this for ages already, but nothing works apparantly..

public static void window() {
    JFrame frame = new JFrame("Sharp");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(
        new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
    JPanel b = new JPanel();
    JLabel label2 = new JLabel("Hello, World!", JLabel.CENTER);
    label2.setAlignmentY(0);
    label2.setAlignmentX(0);
    label2.setText("<html>Made by Julian</html>");
    JPanel a = new JPanel();
    b.add(label2);
    a.setAlignmentX(Component.CENTER_ALIGNMENT);
    a.setPreferredSize(new Dimension(850, 500));
    a.setMaximumSize(new Dimension(850, 850)); // set max = pref


    JToggleButton tb = new JToggleButton("SHARP Instructions");
    tb.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            JToggleButton btn =  (JToggleButton) e.getSource();


            if(btn.isSelected()) {
                Desktop d = Desktop.getDesktop();
                try {
                    d.browse(new URI("https://pastebin.com/nDdGZ0cJ"));
                } catch (IOException | URISyntaxException e2) {
                    e2.printStackTrace();
                } 
            }
        }
    }); 

    frame.setBackground(Color.BLUE);
    a.add(tb);

   // JPanel b = new JPanel();

    frame.add(a, new GridBagConstraints());
    frame.getContentPane().add(a);
    frame.getContentPane().add(b);
    //frame.getContentPane().add(b);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

Your JPanel a is on top of your JFrame , so just:

a.setBackground(Color.BLUE); will fix it.

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