Java 如何使用JFileChooser在JFrame中上载和显示图像
我需要上传并在Java 如何使用JFileChooser在JFrame中上载和显示图像,java,jfilechooser,Java,Jfilechooser,我需要上传并在JFrame中显示使用JFileChooser选择的图像(即用户希望设置其个人资料图片)。。我该怎么做 以下是我选择文件的代码: private void UploadImageActionPerformed(java.awt.event.ActionEvent evt) { int returnVal = fileChosser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION)
JFrame
中显示使用JFileChooser
选择的图像(即用户希望设置其个人资料图片)。。我该怎么做
以下是我选择文件的代码:
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
中
这是我的密码:
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();
}
}
由于您已将您的方法命名为UploadImageActionPerformed,请阅读以下内容。方法名称应在开头用小写字符书写。