一、初始化一個常規的JFrame
package GUI.Swing.IconAndImageLabel圖片和圖標標籤;
import javax.swing.*;
import java.awt.*;
public class LabelDemo extends JFrame {
public LabelDemo() {
//use the constructor to unit a Frame
this.setVisible(true);
this.setBounds(100,100,400,200);
Container contentPane = this.getContentPane();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new LabelDemo();
}
}
二、圖片標籤.
1. 得到 圖片的url ,(使用相對的路徑 失敗,這裏使用絕對路徑)
2.將 new ImageIcon(url),使用url 創建圖片.
3.創建標籤,並且導入圖片,(此處有2種方法)
1.第一種是在創建的時候傳入3個參數,“name”,Icon,CENTER(位置) 即可
2.第二種是在創建後
label.setIcon(imageIcon);
label.setHorizontalAlignment(SwingConstants.CENTER);
4.將標籤放入容器中.
package GUI.Swing.IconAndImageLabel圖片和圖標標籤;
import javax.swing.*;
import java.awt.*;
public class LabelDemo extends JFrame {
public LabelDemo() {
//use the constructor to unit a Frame
this.setVisible(true);
this.setBounds(100, 100, 400, 200);
Container contentPane = this.getContentPane();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
//get url 使用 當前類名.class.getResource("");傳入相對地址得到絕對地址.//無法使用,此處使用絕對路徑
String url = "D:/Program Files/JetBrains/test1/Lab/src/GUI/Swing/IconAndImageLabel圖片和圖標標籤/方糖黃.png";
//使用url得到一個 Image 的對象
ImageIcon imageIcon = new ImageIcon(url);
//創建一個label 並將url參數傳遞給label,並居中顯示,查看源碼可以得出有3個參數,String Icon 和對齊方式
JLabel label = new JLabel("方糖黃.png", imageIcon, SwingConstants.CENTER);
//add label to contentPane
contentPane.add(label);
}
public static void main(String[] args) {
new LabelDemo();
}
}
效果
三、圖標標籤(就是自己使用畫一個圖標,不常用)
1.實現Icon 的接口並重寫Override方法,得到寬和高
2.paintIcon ()可以繪畫處icon,這裏出現未知錯誤.
3.將繪製的圖像 new 此類就可以的得到Icon 的對象
4. 創建Label的時候添加icon 對象到label裏
代碼:
package GUI.Swing.IconAndImageLabel圖片和圖標標籤;
import javax.swing.*;
import java.awt.*;
public class IconLabel extends JFrame implements Icon {
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
g.fillRect(x,y,20,20);
}
@Override
public int getIconWidth() {
return 0;
}
@Override
public int getIconHeight() {
return 0;
}
//使用構造方法創建Frame
public IconLabel() throws HeadlessException {
this.setVisible(true);
this.setBounds(100,100,400,400);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
//add Icon to label,注意paintIcon()在new 的時候就會初始化
IconLabel iconLabel = new IconLabel();
JLabel label = new JLabel("圖標label",iconLabel,SwingConstants.CENTER);
//add label to contentPane
Container contentPane = this.getContentPane();
contentPane.add(label);
label.setHorizontalAlignment(SwingConstants.CENTER);
}
public static void main(String[] args) {
new IconLabel();
}
}