swing 组件——在JLabel中添加图片的两种方式

来源:互联网 发布:php 字节数组 编辑:程序博客网 时间:2024/04/30 00:27

方式一:

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);
}
}



0 0
原创粉丝点击