6.21 在panel中设置背景并不覆盖控件--paintComponent

做java小游戏课设时需要在游戏主界面设置背景图片,最初参考的是这个博客:

https://blog.csdn.net/he13733625052/article/details/90177674

但是其是为Frame设置背景:

通过LayeredPane来为背景和控件进行分层,背景图片用为Label设置Imageicon实现,通过Frame.setLayeredPane(Pane)来为窗口设置背景。

而我是想为JPanel设置背景,而不是Frame,这时对JPanel的paintComponent进行重写就能实现不覆盖控件的重绘(而重写paint会覆盖控件)

    protected void paintComponent(Graphics g) {  
        g.drawImage(background, 0, 0, this.getWidth(), this.getHeight(), this);  
    }  

猜你喜欢

转载自www.cnblogs.com/-ifrush/p/13174348.html