【问题标题】:Java Jpanel, can't set background colorJava Jpanel,无法设置背景颜色
【发布时间】:2013-05-27 22:19:00
【问题描述】:

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

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

}

【问题讨论】:

    标签: java swing jpanel


    【解决方案1】:

    你在没有调用的情况下覆盖 paint

    super.paint(g);
    

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

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

    Performing Custom Painting

    【讨论】:

    • paintComponent 使用双缓冲,因此性能更高。
    【解决方案2】:

    替换代码块

    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(){} 方法中不需要它...

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 2012-06-04
      • 2014-03-29
      • 1970-01-01
      • 2014-02-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多