【发布时间】:2017-06-08 10:05:45
【问题描述】:
我有一个 JPanel 名称“imagePanel”和一个按钮名称“browseBtn”。全部包含在一个 JFrame 类中。当按下browseBtn时,会打开一个文件选择器,选择PNG图像文件后,图像将直接出现在imagePanel中。
这是browseBtn的动作事件
private void browseBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (accept(file)) {
try {
ImageIcon image = new ImageIcon(file.getPath());
JLabel l = new JLabel(image);
imagePanel.add(l);
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error reading file !");
}
}
else {
JOptionPane.showMessageDialog(this, "Choose png file only !");
}
}
}
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}
我选择了正确的 .png 文件,但我不明白为什么图像没有显示在 imagePanel 中。你能解释一下吗? 干杯。
【问题讨论】:
-
1) 对于初学者来说,
new ImageIcon(file.getPath());最好是new ImageIcon(file);2) 动态添加组件很棘手。我建议改为在启动时添加JLabel,然后只需调用l.setIcon(..)。 -
但在使用 ImageIcon(file) 时会抛出错误:"no suitable constructor found for ImageIcon(File)"
-
哦!我的(和甲骨文的)不好。当某些东西应该代表
File路径时,它们应该为File提供构造函数(该死!)。 -
是的,但我做到了。我用标签代替面板来代替,它工作得很好。无论如何,谢谢,先生!选择分辨率比边框大的图片只有一个问题,好像有点大,怎么控制。
标签: java image swing file java-io