以JPanel为基础实现一个图像框

代码:

import java.awt.Graphics;

import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class Picture extends JPanel {
    private static final long serialVersionUID = -4437881316229152596L;

    private ImageIcon icon;

    public Picture(java.net.URL imgURL) {
        icon = new ImageIcon(imgURL);
    }

    public void paintComponent(Graphics g) {
        int x = 0, y = 0;

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

使用实例:

Picture picture=new Picture(getClass().getResource("/welcome.jpg"));

效果图:

 

posted @ 2014-04-27 13:42  逆火狂飙  阅读(215)  评论(0编辑  收藏  举报
生当作人杰 死亦为鬼雄 至今思项羽 不肯过江东