JFrame如何设置背景图片

来源:互联网 发布:数据流程图软件 编辑:程序博客网 时间:2024/05/18 21:50
import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;

public class BackGroundSetting
{

    private JFrame frame = new JFrame("背景图片测试");
    
    private JPanel imagePanel ;
    
    private ImageIcon background;
    
    public static void main(String[] args)
    {
        new BackGroundSetting();
    }
    
    public BackGroundSetting()
    {
    BufferedImage image=null;
//     try {
//    
// image=Thumbnails.of("E:\\1.jpg")   
// .size(600, 500)  
// .watermark(Positions.BOTTOM_CENTER, ImageIO.read(new File("E:\\360Downloads\\loopwallpaper\\1.jpg")), 0.7f)   
// .outputQuality(0.8f)
// .asBufferedImage();
// //.toFile("c:/a380_watermark_bottom_right.jpg");
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }  
//  
    try {
image=ImageIO.read(new File("E:\\360Downloads\\loopwallpaper\\1.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
        background = new ImageIcon(image);//背景图片
        JLabel label = new JLabel(background);//把背景图片显示在一个标签里面
//     把标签的大小位置设置为图片刚好填充整个面板
        label.setBounds(0,0,background.getIconWidth(),background.getIconHeight());
//     把内容窗格转化为JPanel,否则不能用方法setOpaque()来使内容窗格透明       
        imagePanel = (JPanel)frame.getContentPane();
        imagePanel.setOpaque(false);
//     内容窗格默认的布局管理器为BorderLayout
        imagePanel.setLayout(new FlowLayout());
        imagePanel.add(new JButton("测试按钮"));
        
        frame.getLayeredPane().setLayout(null);
//     把背景图片添加到分层窗格的最底层作为背景       
        frame.getLayeredPane().add(label,new Integer(Integer.MIN_VALUE));    
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(background.getIconWidth(),background.getIconHeight());
        
        frame.setVisible(true);
    }
0 0
原创粉丝点击