JPanel 实现背景图片

JAVA 实现背景图片

 JPanel 实现背景图片必须要重写paintComponet()方法

 import  java.awt.*;

import  java.Swing.*;

 

public class JFrameDemo extends JFrame{

       java.net.URL imageURL = getClass().getResourse("bg.jpg");

       ImageIcon im = new ImageIcon(imageURL);

         NewPanel newPanel = new NewPanel(im);

this.add(newPanel);

this.setSize(800,600);

this.setVisuable(true);

this.setLocation(100, 50);
    this.setTitle("测试背景");
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);

 

    public static void main (String[]args){

            JFrameDemo jf =new JFrameDemo();

}

class NewPanel extends JPanel{

   ImageIcon im ;
            public NewPanel (ImageIcon icon){
                this.im = icon;
                int width = Toolkit.getDefaultToolkit().getScreenSize().width;
                int height = Toolkit.getDefaultToolkit().getScreenSize().height;
                this.setSize(width,height);
                
            }

 

public void paintComponent(Graphics g){
                super.paintComponent(g);
                int x=0,y=0;
                java.net.URL imageURL=getClass().getResource("bg.jpg");
                ImageIcon icon=new ImageIcon(imageURL);
                g.drawImage(icon.getImage(), x,y, getSize().width, getSize().height, this);
                while(true){
                    g.drawImage(icon.getImage(), x, y, this);
                    if(x>getSize().width&&y>getSize().height)
                        break;
                    if(x>getSize().width){
                        x=0;
                        y+=icon.getIconHeight();
                        
                    }else{
                        x+=icon.getIconWidth();
                    }
                }
                
            }
        }


 

}

 

posted @ 2016-01-15 19:05  张劳斯  阅读(798)  评论(0编辑  收藏  举报