1. 标签
在Swing下使用标签的对象,可以在标签上嵌入图标,实现这个小功能需要使用icon接口。这里的demo是放在标签上,其实也可以将图标放在按钮上,或者是其他东东上,我们这里放在标签上来进行测试。
1.1 实现图标的嵌入
//具体细节,扣在代码注释中
package com.Swing.JFrame;
import javax.swing.*;
import java.awt.*;
public class Test02icon extends JFrame implements Icon {
public static void main(String[] args) {
new Test02icon().init();
}
private int width;
private int height;
public Test02icon(){
}
public Test02icon(int width, int height){
this.width = width;
this.height = height;
}
public void init(){
//实例化标签对象,并通过有参构造设置宽高
Test02icon test02icon = new Test02icon(25,25);
//在这里我们把图标放在标签上,开始进行标签的设置
JLabel label = new JLabel("存放图标的标签", test02icon, SwingConstants.CENTER);
Container contentPane = getContentPane();
contentPane.add(label); //将标签组件放入容器
setVisible(true); //设置可见
setBounds(220,220,600,420);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); //添加关闭事件
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
//Component 是针对容器的,Graphics 是针对画笔的
g.fillOval(x,y,width,height); //传入坐标 xy 和 宽高
}
@Override
public int getIconWidth() {
return this.width;
}
@Override
public int getIconHeight() {
return this.height;
}
}
我们来看一下执行的效果图:
我们可以看到容器中成功添加进去了一个很丑的图标,但只是一个图标,并不是图片,那如果我们想添加自己的图片该怎么做?
1.2 实现图片的嵌入
我们先准备好材料。把准备好的图片放在和练习的java文件同级
准备好之后,我们来创建类,开始写代码
package com.Swing.JFrame;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class Test03ImageIcon extends JFrame {
public static void main(String[] args) {
new Test03ImageIcon();
}
public Test03ImageIcon(){
//我们的练习目标是将图片放在标签中的,所以先创建标签
JLabel jLabel = new JLabel("我是兔C");
//然后开始获取图片资源
URL url = Test03ImageIcon.class.getResource("tc.jpg");
//在Swing下对图片的操作需要用到ImageIcon所以先创建
ImageIcon imageIcon = new ImageIcon(url); //这样就获取到了图片资源
jLabel.setIcon(imageIcon); //将获取到的图片资源放到标签中
jLabel.setHorizontalAlignment(SwingConstants.CENTER); //设置布局
Container contentPane = getContentPane();
contentPane.add(jLabel);
//设置窗体的基本设置
setVisible(true);
setBounds(220,220,600,420);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
这里需要注意获取资源的时候,要用自己当前的类.class.getResource,不然会出现空指针。
我这里我没有放效果图,是因为我没有空指针,但是运行结果图片并没有在容器中加载,我在找问题,还没成功,但是代码没有问题。明天在发文发实现效果。