1、标签组件JLabel
构造方法
说明
JLabel()
不带图标和文本的标签
JLabel(Icon icon)
带图标
JLabel(Icon icon,int aligment)
带图标,水平对齐方式
JLabel(String text,int aligment)
带文本,水平对齐方式
JLabel(String text,Icon icon,int aligment)
带文本,图标,标签内容的水平对齐方式
2、图标ImageIcon
package Eleven;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import java.awt.Container;
import java.net.URL;
public class MyImageIcon extends JFrame{
public MyImageIcon(){
Container container = getContentPane();
/*javax.swing.JLabel.JLabel(String text, int horizontalAlignment)
Creates a JLabel instance with the specified text and horizontal alignment.
The label is centered vertically in its display area.
Parameters:
text The text to be displayed by the label.
horizontalAlignment One of the following constants defined in SwingConstants: LEFT, CENTER, RIGHT, LEADING or TRAILING.*/
JLabel jLabel = new JLabel("带图标的标签组件",JLabel.CENTER);
//URL java.lang.Class.getResource(String name)
URL url = MyImageIcon.class.getResource("watermelon.jpg");
//javax.swing.ImageIcon.ImageIcon(URL location)
Icon icon = new ImageIcon(url);
/*void javax.swing.JLabel.setIcon(Icon icon)
Defines the icon this component will display.
If the value of icon is null, nothing is displayed.
The default value of this property is null.
This is a JavaBeans bound property.
Parameters:
icon */
jLabel.setIcon(icon);
jLabel.setHorizontalAlignment(SwingConstants.CENTER);
jLabel.setOpaque(true);//不透明
container.add(jLabel);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(186,168);
}
public static void main(String[] args){
new MyImageIcon();
}
}