简体   繁体   中英

Java Jpanel, can't set background color

I have a main class that extends a JFrame, which then adds a jpanel to the jframe. Then I try to set the background color of the jpanel, but to no avail. I'm not really sure where the problem is, according to what i've found on google, simply setting setBackground(Color) in the JPanel should fix this but it doesn't seem to work. Also other fixes for this were setOpaque(true) , and setVisible(true) , or form the JFrame using getContentPane().setBackground(Color) But none of these seem to work. Any suggestions would be very appreciated, and if you need more info, or have other advice, please feel free to enlighten me. :) The main class is:

public class main extends JFrame{

    private Content content;

    public main(){

        content = new Content(400, 600);

        this.setTitle("Shooter2.0");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setResizable(false);
        this.getContentPane().add(content);
        this.getContentPane().setBackground(Color.BLACK);
        this.pack();
        this.setVisible(true);
        try{
            Thread.sleep(10000);
        }catch(Exception e){}
    }


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

}

and the Content class is:

public class Content extends JPanel{

    private viewItem ship;

    public Content(int w, int h){
        this.setPreferredSize(new Dimension(w, h));
        this.setLayout(new BorderLayout());     
        this.createBattlefield();
        this.setOpaque(true);
        this.setBackground(Color.BLACK);
        this.repaint();
        this.setVisible(true);
    }

    public void createBattlefield(){
        ship = new viewItem("bubble-field.png", 180, 550, 40, 42);      
    }

    public void paint(Graphics g){
        g.setColor(Color.BLACK);
        this.setBackground(Color.BLACK);
        ship.draw(g);       
    }

}

You're overriding paint without calling

super.paint(g);

This prevents the background and child components from being painted.

For custom painting in Swing override paintComponent instead and take advantage of Swing's optimized paint model, annotate with @Override and invoke super.paintComponent(g) .

Performing Custom Painting

Replace the code block

public void paint(Graphics g){
    g.setColor(Color.BLACK);
    this.setBackground(Color.BLACK);
    ship.draw(g);       
}

By

public void paintComponent(Graphics g){
    super.paintComponent(g);
    g.setColor(Color.BLACK);        
    ship.draw(g);       
}

you are setting the background color of JPanel in constructor so there is no need it in paintComponent(){} method...

try above code it will surely works....

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