Java swing 背景图片



import java.awt.*;
import javax.swing.*;

public class BackgroundImg extends JFrame{
 public static void main(String[] args){
  new BackgroundImg();
 }
 JPanel jp_window;//添加所有组件的面板
 JLabel lable_img;//图片标签
 private static final ImageIcon bgimg = new ImageIcon("image/Scenery.jpg");//背景图片
 public BackgroundImg(){
  JLabel lable_img = new JLabel(bgimg);//把背景图片显示在一个标签里面
  //把标签的大小位置设置为图片刚好填充整个面板
  lable_img.setBounds(0,0,bgimg.getIconWidth(),bgimg.getIconHeight());
  
  //把内容窗格转化为JPanel,否则不能用方法setOpaque()来使内容窗格透明
  jp_window = (JPanel)this.getContentPane();
  jp_window.setOpaque(false);//设置面板的透明度
  
  //内容窗格默认的布局管理器为BorderLayout
  /*
   * 所有组件直接添加到jp_window 面板中就可以了
   * */
  jp_window.setLayout(new FlowLayout());
  jp_window.add(new JPanel().add(new JButton("测试按钮")));
  jp_window.add(new JLabel("测试标签"));
  
  //用于实现窗口背景图片
  this.getLayeredPane().setLayout(null);
  
  //把背景图片添加到分层窗格的最底层作为背景
  this.getLayeredPane().add(lable_img,new Integer(Integer.MIN_VALUE));
  
  /*
   * 这里不清楚原因,得不到图片的正确高度,但是方法没有错:getIconHeight()
   * 建议根据图片的大小设置窗口大小
   * */
  this.setSize(bgimg.getIconWidth(),bgimg.getIconHeight());//得到图片的宽和高
  
  //this.setResizable(false);//设置窗口的不可最大化
  this.setLocationRelativeTo(null);
  this.setDefaultCloseOperation(EXIT_ON_CLOSE);
  this.setVisible(true);
 }
}


测试截图:




  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值