swing 組件——在JLabel中添加圖片的兩種方式

方式一:

import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;


import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class picSwing {
public static void main(String args[]) {
JFrame frame = new JFrame("Picture Swing");
String picPath = "E:"+File.separator+"圖片(臨時)"+File.separator+"owner"+File.separator+"自定義頭像_1.jpg";
System.out.println("路徑:"+picPath);
File file= new File(picPath);
InputStream input = null;
byte b[] = new byte[(int) file.length()];
try {
input = new FileInputStream(file);
input.read(b);
input.close();
} catch (Exception e) {
e.printStackTrace();
}
Icon icon = new ImageIcon(b);
JLabel jLabel = new JLabel("GuFeng",icon,JLabel.CENTER);
jLabel.setBackground(Color.blue);
jLabel.setForeground(Color.BLACK);
frame.add(jLabel);
frame.setSize(500,500);
frame.setBackground(Color.WHITE);
frame.setLocation(600,500);
frame.setVisible(true);
}
}

方式二:

import java.awt.Color;
import java.io.File;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class picSwing_2 {
public static void main(String args[]) {
JFrame frame = new JFrame("Picture Swing");
String picPath = "E:"+File.separator+"圖片(臨時)"+File.separator+"owner"+File.separator+"自定義頭像_1.jpg";
System.out.println(picPath);
Icon icon = new ImageIcon(picPath);
JLabel jLabel = new JLabel("GuFeng",icon,JLabel.CENTER);
jLabel.setBackground(Color.blue);
jLabel.setForeground(Color.BLACK);
frame.add(jLabel);
frame.setSize(500,500);
frame.setBackground(Color.WHITE);
frame.setLocation(600,500);
frame.setVisible(true);
}
}



發佈了27 篇原創文章 · 獲贊 17 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章