XSeven
XSeven

Reputation: 11

Can't change background color of JFrame or JPanel

I can't get the JPanel to change color. I also can't get the JFrame to change color. I've looked online... and I have another program that has almost identical code for setting up JPanel and JFrame. I just can't get it to work.

Here is my main method:

public static void main(String[] args){
    JFrame frame = new JFrame("title");
    frame.getContentPane().setBackground(Color.WHITE);
    Drawing drawing = new Drawing(2);
    drawing.setBackground(Color.CYAN);
    frame.add(drawing);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500, 500);
    ...

EDIT: later in my main method are

    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

Here is the constructor for the JPanel:

public class Drawing extends JPanel {
    // instance variables
    public Drawing(int n){
        setOpaque(true);
        setPreferredSize(new Dimension(300, 300));
        setBackground(Color.PINK);
        ...

And background color stays the default gray.

Upvotes: 0

Views: 4131

Answers (1)

Simon Jensen
Simon Jensen

Reputation: 486

I had no issues making a quick window builders application using eclipse as well as setting the colors.

A few things that I did notice is you do frame.add(drawing) and not frame.getContentPane().add(drawing).
You also never set the frame visible with frame.setVisible(true).

Here is the code I used:

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                MainWindow window = new MainWindow();
                window.frame.setVisible(true);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public MainWindow() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.getContentPane().setBackground(Color.GREEN);
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JPanel panel = new JPanel();
    panel.setBackground(Color.CYAN);
    panel.setBounds(10, 171, 128, 81);
    frame.getContentPane().add(panel);
}  

EDIT: added picture illustration of your code working

enter image description here

Upvotes: 2

Related Questions