以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"));
效果图: