2

我有一个扩展 JFrame 的主类,然后将 jpanel 添加到 jframe。然后我尝试设置jpanel的背景颜色,但无济于事。我不确定问题出在哪里,根据我在谷歌上找到的内容,只需setBackground(Color)在 JPanel 中设置即可解决此问题,但它似乎不起作用。对此的其他修复是setOpaque(true), and setVisible(true), or form the JFrame usinggetContentPane().setBackground(Color)但是这些似乎都不起作用。任何建议将不胜感激,如果您需要更多信息或有其他建议,请随时赐教。:) 主要课程是:

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();
    }

}

内容类是:

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);       
    }

}
4

2 回答 2

5

paint无需调用即可覆盖

super.paint(g);

这可以防止背景和子组件被绘制。

对于 Swing 中的自定义绘画,请paintComponent 改用覆盖并利用 Swing 的优化绘画模型,使用注释@Override和调用super.paintComponent(g)

执行自定义绘画

于 2013-05-27T22:25:34.610 回答
0

替换代码块

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

经过

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

您在构造函数中设置 JPanel 的背景颜色,因此在 paintComponent(){} 方法中不需要它...

试试上面的代码它肯定会工作....

于 2014-09-09T18:23:44.327 回答