本文介绍了如何使用JFileChooser在JFrame中上传和显示图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在JFrame
中上传并显示用JFileChooser
选择的图像(即用户要设置他/她的个人资料图片).该怎么做?
I need to upload and display an image selected with the JFileChooser
(i.e the user wants to set his/her profile picture) in a JFrame
.. How should I do it?
这是我选择文件的代码:
Here is my code for choosing the file:
private void UploadImageActionPerformed(java.awt.event.ActionEvent evt) {
int returnVal = fileChosser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChosser.getSelectedFile();
// What to do with the file
// I want code for this part
try {
//code that might create an exception
}
catch (Exception e1) {
e.printStackTrace();
}
}
}
推荐答案
我自己解决了这个问题.我选择了一个图像并显示在JLabel
中.
I solved it myself. I chose an image and displayed in a JLabel
.
这是我的代码:
private void uploadImageActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser filechooser = new JFileChooser();
filechooser.setDialogTitle("Choose Your File");
filechooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
// below code selects the file
int returnval = filechooser.showOpenDialog(this);
if (returnval == JFileChooser.APPROVE_OPTION)
{
File file = filechooser.getSelectedFile();
BufferedImage bi;
try {
// display the image in a Jlabel
bi = ImageIO.read(file);
jLabel1.setIcon(new ImageIcon(bi));
} catch(IOException e) {
e.printStackTrace(); // todo: implement proper error handeling
}
this.pack();
}
}
这篇关于如何使用JFileChooser在JFrame中上传和显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!