zoukankan      html  css  js  c++  java
  • JFrame背景

    1.引言

    在了解了JFrame面板的相关知识后,我们可以选择在RootPane根面板或LayeredPane面板中设置背景图案。

    2.方法

    对于大小固定的窗口背景设置如下:

     1      //导入图案
     2 
     3      ImageIcon img = new ImageIcon("image url");   
     4 
     5      // 图片缩放为窗口大小
     6 
     7      Image image = img.getImage().getScaledInstance(frame.getWidth(), frame.getHeight(), Image.SCALE_FAST);
     8 
     9      //将缩放好的图片实例化
    10 
    11      ImageIcon newimg = new ImageIcon(image);
    12 
    13      //将图案放入标签(不能直接将image放入标签)
    14 
    15      JLabel imgLabel = new JLabel();
    16 
    17      imgLabel.setIcon(newimg);
    18 
    19      //设置标签位置和大小(覆盖面板)
    20 
    21      imgLabel.setBounds(0, 0,  frame.getWidth(), frame.getHeight());
    22 
    23      //将标签添加到Layered面板或RootPane面板( LayeredPane也有若干层,这里放在最底层)
    24 
    25      frame.getLayeredPane().add( imgLabel, new Integer(Integer.MIN_VALUE));
    26 
    27      //将ContentPane设置为透明
    28 
    29     JPanel content=(JPanel) frame.getContentPane();
    30 
    31     content.setOpaque(false);

    3.实例

     1 import java.awt.Image;
     2 import javax.swing.ImageIcon;
     3 import javax.swing.JFrame;
     4 import javax.swing.JLabel;
     5 import javax.swing.JPanel;
     6 public class SetBack1 {
     7     JFrame frame = new JFrame("picture test");
     8     JLabel label=new JLabel();   
     9     public SetBack1(){
    10         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    11         frame.setSize(500, 400);    
    12         //导入图片
    13         ImageIcon img = new ImageIcon("D:\7.jpg");
    14         // 图片缩放为适合Frame大小
    15         Image image = img.getImage().getScaledInstance(frame.getWidth(), frame.getHeight(), Image.SCALE_FAST); 
    16         //将缩放好的图片实例化
    17         ImageIcon newimg = new ImageIcon(image);
    18         //在标签中添加图片
    19         label.setIcon(newimg);
    20         //设置标签大小为全屏
    21         label.setBounds(0, 0, frame.getWidth(), frame.getHeight());        
    22         //LayeredPane也是分层的,这里将JLabel放置在了LayeredPane最底层
    23         frame.getLayeredPane().add( label, new Integer(Integer.MIN_VALUE));
    24         //将ContentPane透明化
    25         JPanel cp= (JPanel)  frame.getContentPane();            
    26         cp.setOpaque(false);
    27         frame.setVisible(true);
    28     }    
    29     public static void main(String[] args) {
    30         new SetBack1();
    31     }
    32 }

    效果如下:

  • 相关阅读:
    python并行编程学习之绪论
    flask学习之解决Internal Server Error问题的方式之一
    mysql ERROR 1045 (28000): Access denied for user 'ODBC'@'localhost' (using password: NO)错误解决办法
    python之numpy矩阵库的使用(续)
    python常用序列list、tuples及矩阵库numpy的使用
    计算机网络学习之概述篇
    C++数据结构学习之顺序表
    python-networkx学习(1)
    Html&CSS学习笔记03---CSS介绍、CSS语法、CSS与HTML的结合、CSS选择器、CSS常用样式
    Html&CSS学习笔记02---HTML标签的介绍
  • 原文地址:https://www.cnblogs.com/jfl-xx/p/4733940.html
Copyright © 2011-2022 走看看