【标签组件与图标 3.3】

1.图片图标。

SWing 利用javax.swing.ImageIcon 类根据现有图片创建图标,ImageIcon类实现了Icon接口,同时Java支持多种图片格式。

  1. public ImageIcon():该构造方法创建了一个通用的ImageIcon对象,当正真需要设置图片时在使用ImageIcon对象调用setImage(Image image)
  2. public ImageIcon(Image image):可以直接从图片源创建图标
  3. public ImageIcon(Image image,string description):除了可以从图片源创建图标之外,还可以添加简单的描述,但是描述不会出现在图标上,可以使用getDescription()方法获取这个描述。
  4. public ImageIcon(URL url):用于计算机网络上的图像文件创建图标。
    1. 实例在项目组中创建实现Icon接口的DrawIcon类,该类实现自定义的图标类。
  5.  1 package 常用窗体;
     2 
     3 import java.awt.BorderLayout;
     4 import java.awt.Color;
     5 import java.awt.Container;
     6 
     7 import javax.print.DocFlavor.URL;
     8 import javax.swing.Icon;
     9 import javax.swing.ImageIcon;
    10 import javax.swing.JFrame;
    11 import javax.swing.JLabel;
    12 import javax.swing.SwingConstants;
    13 import javax.swing.WindowConstants;
    14 
    15 public class MyImageIcon extends JFrame{
    16     
    17     
    18     private boolean ture;
    19     public MyImageIcon() {
    20     Container container=getContentPane();
    21     JLabel jl=new JLabel("This is a new JFrame window",JLabel.CENTER);//to create a label or jl.setText("乖乖猫猫");
    22     
    23     setTitle("使用标签组件");
    24     setBounds(100,100,300,200);
    25     
    26     getContentPane().add(jl,BorderLayout.NORTH);
    27     java.net.URL url=MyImageIcon.class.getResource("imageButton.jpg");//get the picture's url
    28     Icon icon =new ImageIcon(url);//make a real icon example
    29     
    30     jl.setIcon(icon);;//setting the picture for the label
    31     jl.setHorizontalAlignment(SwingConstants.CENTER);//set the constants in the center
    32     //container.setBackground(Color.blue);
    33     jl.setOpaque(ture);//不透明状态
    34     container.add(jl);
    35     setSize(200,150);
    36     setVisible(true); 
    37     setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    38     }
    39     public static void main(String[] args) {
    40         new  MyImageIcon();
    41         // TODO Auto-generated method stub
    42 
    43     }
    44 
    45 }

原文地址:https://www.cnblogs.com/yitou13/p/8506473.html