如何将使用 JFileChooser 拍摄的图像图标放在标签上?
嘿,我刚刚尝试将使用 JFileChooser 拍摄的图像放在标签上;但它没有按照我想要的方式工作。这是我尝试过的代码;
import java.io.*;
import javax.swing.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
JFileChooser chooser = new JFileChooser();
JFrame frame = new JFrame("My Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
chooser.showOpenDialog(null);
File file = chooser.getSelectedFile();
ImageIcon icon = new ImageIcon(file.getName());
JLabel label = new JLabel(icon);
// JLabel label2 = new JLabel("try try catch it");
panel.add(label);
// panel.add(label2);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
有什么建议吗?
Hey there, i have just tried to put an image that is taken with JFileChooser on a label; but it did not work the way i want to. Here is the code that i tried;
import java.io.*;
import javax.swing.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
JFileChooser chooser = new JFileChooser();
JFrame frame = new JFrame("My Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
chooser.showOpenDialog(null);
File file = chooser.getSelectedFile();
ImageIcon icon = new ImageIcon(file.getName());
JLabel label = new JLabel(icon);
// JLabel label2 = new JLabel("try try catch it");
panel.add(label);
// panel.add(label2);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
Any suggestion?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
关闭。
您会注意到,当您查看
file.getName()
时,您会发现它将为您提供所选文件的名称。您正在寻找路径而不是文件名。看看是否可以在
File
的 API 中查找如何获取路径。Close.
You will notice that when you look at
file.getName()
you see that it will give you the name of the file that you selected. You're looking for the path instead of the name of the file.See if you can look in the API for
File
for how to get the path.您应该使用
file.getPath()
而不是file.getName()
。您还应该在东部时间进行绘画工作。You should be using
file.getPath()
instead offile.getName()
. You should also be doing your painting work in the EDT.