3.3 标签
label
new JLabel("xxx");
图标 ICON
package GUI.Swing;
import javax.swing.*;
import java.awt.*;
public class IconFemo extends JFrame implements Icon {
private int width;
private int height;
public IconFemo(){
//无参构造
}
public IconFemo(int width,int height){
this.width = width;
this.height = height;
}
public void init(){
IconFemo iconFemo = new IconFemo(15, 15);
//图标可以放在标签上,也可以放在按钮上
JLabel label = new JLabel("icontest", iconFemo, SwingConstants.CENTER);//设置这个标签放在正中间
Container container = getContentPane();
container.add(label);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//关闭
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {//放的位置 画笔来画 图标的大小 x,y
g.fillOval(x,y,width,height);
}
@Override
public int getIconWidth() {
return this.width;
}
@Override
public int getIconHeight() {
return this.height;
}
public static void main(String[] args) {
new IconFemo().init();
}
}
图片ICON
package GUI.Swing;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class ImageIconDemo extends JFrame {
public ImageIconDemo(){
//获取图片的地址
JLabel label = new JLabel("ImageIcon");
URL url = ImageIcon.class.getResource("bei.jpg");
ImageIcon imageIcon = new ImageIcon(url);//命名不要和Image重名
label.setIcon(imageIcon);
label.setHorizontalAlignment(SwingConstants.CENTER);
Container container = getContentPane();
container.add(label);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setBounds(200,200,200,200);
}
public static void main(String[] args) {
new ImageIconDemo();
}
}