1

When I run this program the color doesn't change to blue. How do I change the color in this context? Code:

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

public class Test extends JPanel {
 static void test() {
  JFrame f = new JFrame("Test");
  f.getContentPane().setBackground(Color.blue);
  f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  f.getContentPane().add(new Test());
  f.setExtendedState(JFrame.MAXIMIZED_BOTH);
  f.setVisible(true);
}

public static void main(String[] args) {
  SwingUtilities.invokeLater(new Runnable() {
     public void run() {
        test();
     }
  });
 }
}
splungebob
  • 5,357
  • 2
  • 22
  • 45
  • instead of using the getContentPane(), just do setBackground(Color.BLUE); * may be setBackgroundColor, can't remember, but use caps for the color.* – user2277872 Feb 12 '14 at 18:12

3 Answers3

1

I think your new Test() is overlapping the background color.

Try to change the jpanels background color.

danielbathke
  • 105
  • 5
1

The setBackground works fine. The problem is with the default BorderLayout of the JFrame. The only component you add is the Test JPanel which get expanded the size of the JFrame, due the BorderLayout, which ultimately covers up background color. If you take out the Test JPanel you will see the background color.

You can also see the affect, below, of setting the layout to GridBagLayout to the frame and setting a preferredSize to theJPanel`

enter image description here

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import javax.swing.*;
import javax.swing.border.TitledBorder;

public class Test extends JPanel {
    public Test() {
        setBorder(new TitledBorder("Panel size 300, 300"));
        setBackground(Color.YELLOW);
    }

    @Override 
    public Dimension getPreferredSize() {
        return new Dimension(300, 300);
    }

    static void test() {
        JFrame f = new JFrame("Test");
        f.setLayout(new GridBagLayout());
        f.getContentPane().setBackground(Color.blue);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(new Test());
        f.setExtendedState(JFrame.MAXIMIZED_BOTH);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                test();
            }
        });
    }
}

The reason GridbagLayout works is because it respects the preferredSize of child components. As you can see from this answer, some Layout Managers respect the preferred sizes and some don't

enter image description here

Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
1

Set layout to JFrame

f.setLayout(new FlowLayout());

AJ.
  • 4,526
  • 5
  • 29
  • 41