这里想到了两种方式:一种是使用JPanel,另一种使用JLabel来实现。
下面是测试用源码:
1.JPanel(源代码)
package oo;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
publicclass Drawing {
JFrame jframe = new JFrame();
publicstatic JPanel GImage = null;
public Drawing() {
initFrame();
}
// 初始化窗口
publicvoid initFrame() {
// 利用JPanel添加背景图片
GImage = new JPanel() {
protectedvoid paintComponent(Graphics g) {
ImageIcon icon = new ImageIcon("p_w_picpath\\benbenla.jpg");
Image img = icon.getImage();
g.drawImage(img, 0, 0, icon.getIconWidth(),
icon.getIconHeight(), icon.getImageObserver());
jframe.setSize(icon.getIconWidth(), icon.getIconHeight());
}
};
jframe.setTitle("测试背景图片");
jframe.add(GImage);
jframe.pack();
jframe.setVisible(true);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
publicstaticvoid main(String[] args) {
new Drawing();
}
}
2.JLabel源代码
package swing.draw;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
/** 利用JLabel来构建图片 */
publicclass Drawing2 {
JLabel jlpic = new JLabel();
JFrame jframe = new JFrame();
public Drawing2() {
init1Frame();
}
publicvoid init1Frame() {
ImageIcon icon = new ImageIcon("p_w_picpath\\benbenla.jpg");
icon.setImage(icon.getImage().getScaledInstance(icon.getIconWidth(),
icon.getIconHeight(), Image.SCALE_DEFAULT));
System.out.println(icon.getIconHeight() + "" + icon.getIconWidth());
jlpic.setBounds(0, 0, 1366, 768);
jlpic.setHorizontalAlignment(0);
jlpic.setIcon(icon);
jframe.setSize(1366, 768);
jframe.add(jlpic);
jframe.pack();
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setVisible(true);
}
publicstaticvoid main(String args[]) {
new Drawing2();
}
}
转载于:https://blog.51cto.com/zhengjiang/1359672