brent_mb
brent_mb

Reputation: 337

Background color not working JPanel inside JFrame

I am trying to do a very simple thing.. set the background color on the JPanel inside my JFrame. I have not used swing very much so I am still learning. However, I have read up on doing something as basic as setting the background color quite a bit, and I do not know why what I have is not working.

I have my JFrame set up in my Main class.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.WindowConstants;

public class Main extends JFrame {
    private static Screen screen;
    private static int WIDTH = 600;
    private static int HEIGHT = 600;

    public Main() {
        screen = new Screen();
        setTitle("Asteroid");
        setSize(WIDTH, HEIGHT);
        setLayout(new BorderLayout());
        add(screen, BorderLayout.CENTER);
        setBackground(Color.BLACK);
        setResizable(false);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    @Override
    public void paint(Graphics g) {
    }

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

And then I have my JPanel set up in a Screen class

import java.awt.Color;
import java.awt.Dimension;

import javax.swing.JPanel;

public class Screen extends JPanel {
    private static int WIDTH = 600;
    private static int HEIGHT = 600;
    private Dimension screen = new Dimension(WIDTH, HEIGHT);

    public Screen() {
        setSize(screen);
        setBackground(Color.BLACK);
        setOpaque(true);
    }
}

I am not sure why this is not working properly.

Upvotes: 0

Views: 175

Answers (1)

George Z.
George Z.

Reputation: 6808

The problem is that you @Override paint method (you should not) of your JFrame. In addition you leave it empty, without calling the super paint method. So, if you simply add super.paint(g); to your @Override you will see that background is painted without problems.

However, when you want to do custom painting, you should @Override paintComponent(Graphics g) method, and again, start by calling super.paintComponent(g);.

Upvotes: 1

Related Questions