• Swing控件(JPanel,Container等)设置背景图片


    Swing控件有直接设置背景颜色的方法,但没有直接设置背景图片的方法。这里不解的是为什么Swing默认不提供这个方法呢?既然它不提供我们就自己写一个吧,也不难,你要你知道Swing容器的图片都是用protected void paintComponent(Graphics g) 画上去的就可以了。

    我们写一个类提供一个public void setBackground(Icon wallpaper) 方法,然后在这个方法里,我们保存传入的图片,然后利用repaint()方法去重绘控件,这是系统会自动调用控件的protected void paintComponent(Graphics g) 方法。 于是我们就达到了设置背景的目的。下面是完整的代码。附件是一个完整的例子。

    import java.awt.Graphics;
    import java.awt.Image;
    
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JPanel;
    
    public class ZPanel extends JPanel {
    
        private static final long serialVersionUID = 6702278957072713279L;
        private Icon wallpaper;
    
        public ZPanel() {
        }
    
        protected void paintComponent(Graphics g) {
            if (null != wallpaper) {
                processBackground(g);
            }
            System.out.println("f:paintComponent(Graphics g)");
        }
    
        public void setBackground(Icon wallpaper) {
            this.wallpaper = wallpaper;
            this.repaint();
        }
    
        private void processBackground(Graphics g) {
            ImageIcon icon = (ImageIcon) wallpaper;
            Image image = icon.getImage();
            int cw = getWidth();
            int ch = getHeight();
            int iw = image.getWidth(this);
            int ih = image.getHeight(this);
            int x = 0;
            int y = 0;
            while (y <= ch) {
                g.drawImage(image, x, y, this);
                x += iw;
                if (x >= cw) {
                    x = 0;
                    y += ih;
                }
            }
        }
    }
  • 相关阅读:
    数据库——Oracle(7)
    数据库——Oracle(6)
    数据库——Oracle(5)
    数据库——Oracle(4)
    数据库——Oracle(3)
    数据库——Oracle(2)
    Java 学习笔记之 Synchronized锁对象
    Java 学习笔记之 线程安全
    Java 学习笔记之 实例变量非线程安全
    Java 学习笔记之 方法内的临时变量是线程安全
  • 原文地址:https://www.cnblogs.com/langtianya/p/3110702.html
Copyright © 2020-2023  润新知