java中swing界面上怎么给jpanel上添加背景图片
展开全部
//重写JPanel的这个方法就可以了
@Override
public void paintComponent(Graphics gs) {
Graphics2D g = (Graphics2D) gs;
super.paintComponent(g);
//画背景图片
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource(imgPath));
g.drawImage(image, 0, 0,width,height, this);
}
一个完整的代码:
package test;
import java.awt.Graphics;
import java.awt.Image;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
//为窗口添加背景图片
public class JFrameBackground {
private JFrame frame = new JFrame("带背景图片的JFrame");
private JPanel imagePanel;
private ImageIcon backgroundimg;
public JFrameBackground() {
imagePanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
URL location = this.getClass().getResource("grapes.gif");
backgroundimg = new ImageIcon(location);
Image img = backgroundimg.getImage();
g.drawImage(img, 0, 0, backgroundimg.getIconWidth(),
backgroundimg.getIconHeight(),
backgroundimg.getImageObserver());
frame.setSize(backgroundimg.getIconWidth(),
backgroundimg.getIconHeight());
}
};
frame.add(imagePanel);
frame.setVisible(true);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JFrameBackground();
}
}
这是运行的一个截图:
参考网址:
http://www.linuxidc.com/Linux/2011-08/41689.htm 两种设置背景的方法
http://blog.csdn.net/one_and_only4711/article/details/6594770 动态改变背景大小
展开全部
import javax.swing.JPanel;
import java.awt.Image;
import javax.swing.ImageIcon;
import java.awt.Graphics;
class GetPanel extends JPanel {
private static final long serialVersionUID = 1L;
int width = 0, hight = 0;
String imgpath = "";
public GetPanel(int width, int hight, String file) {
this.width = width;
this.hight = hight;
imgpath = file;
}
protected void paintComponent(Graphics g) {
ImageIcon icon = new ImageIcon(imgpath);
Image img = icon.getImage();
g.drawImage(img, 0, 0, width, hight, this);
}
}
GetPanel继承了JPanel,同时又加入了paintComponent()方法。
JPanel jContentPane = new GetPanel(500,375,"login.png");
这样就可以给面板加上背景图片了
import java.awt.Image;
import javax.swing.ImageIcon;
import java.awt.Graphics;
class GetPanel extends JPanel {
private static final long serialVersionUID = 1L;
int width = 0, hight = 0;
String imgpath = "";
public GetPanel(int width, int hight, String file) {
this.width = width;
this.hight = hight;
imgpath = file;
}
protected void paintComponent(Graphics g) {
ImageIcon icon = new ImageIcon(imgpath);
Image img = icon.getImage();
g.drawImage(img, 0, 0, width, hight, this);
}
}
GetPanel继承了JPanel,同时又加入了paintComponent()方法。
JPanel jContentPane = new GetPanel(500,375,"login.png");
这样就可以给面板加上背景图片了
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询