添加头像
import java.awt.Color;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class NewFile extends JFrame{
private JLabel jl = new JLabel();
public NewFile(){
this.setLayout(null);
jl.setBounds(30, 30, 100, 150);
jl.setBorder(BorderFactory.createLineBorder(Color.black));
this.add(jl);
JButton addButton = new JButton("添加头像");
addButton.setBounds(30, 190, 100, 20);
this.add(addButton);
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
JFileChooser jfc = new JFileChooser();
int index = jfc.showOpenDialog(null);
if(index == 0){
File f = jfc.getSelectedFile();
Image img = new ImageIcon(f.getAbsolutePath()).getImage();
img = img.getScaledInstance(100, 150, 10);
jl.setIcon(new ImageIcon(img));
File fs = new File("image");
if(fs.exists()==false){
fs.mkdir();
}
String fileName = System.currentTimeMillis()+f.getName().substring(f.getName().lastIndexOf("."));
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(f);
out = new FileOutputStream("image/"+fileName);
byte[] by = new byte[1024];
int len = 0;
while((len = in.read(by))!= -1){
out.write(by, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
this.setSize(400, 300);
this.setVisible(true);
this.setDefaultCloseOperation(3);
this.setLocationRelativeTo(null);
}
public static void main(String[] args) {
NewFile nf = new NewFile();
}
}