图像不显示在我的JLabel
问题描述:
调用此方法,以我的主窗体类,将选择该文件,但难道不显示图像.. 片段图像不显示在我的JLabel
p
ublic class imageSending {
public static File setpix(File k) throws IOException {
// throw new UnsupportedOperationException("Not supported yet.");
JFileChooser choose=new JFileChooser();
choose.setDialogTitle("Browse Image");
choose.setFileSelectionMode(2);
int a=choose.showOpenDialog(null);
if (a==0){
File file=new File(choose.getSelectedFile().getPath());
BufferedImage img=ImageIO.read(file);
ImageIcon o = new ImageIcon(img.getScaledInstance(300, 300, 300));
}return k;
}
}
答
这是上面简单地说你的方法
public static File setpix(File k) throws IOException {
// do lots of busy work that accomplishes nothing
// and then return k:
return k;
}
就是这样。如果你想在GUI中实际显示图像,你应该改为:
- 获取从JFileChooser获得的文件。只需拨打
getSelectedFile()
无需将其转换为一个字符串,然后得到一个文件 - 从文件中获取您的BufferedImage并将其转换为一个ImageIcon
- 有方法返回的ImageIcon
- 别的地方,请拨打方法并通过
setIcon(...)
将Icon插入到JLabel中。
例如(代码未测试)
public Icon getIcon() throws IOException {
JFileChooser choose = new JFileChooser();
choose.setDialogTitle("Browse Image");
// choose.setFileSelectionMode(2); // no "Magic" numbers
choose.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); // Better
int a = choose.showOpenDialog(null);
if (a == 0) {
File file = choose.getSelectedFile();
BufferedImage img=ImageIO.read(file);
Icon o = new ImageIcon(img.getScaledInstance(300, 300, 300));
return o;
} else {
// throw an exception here
// or return null if that's what the program expects
// or return some "default" icon
}
}
然后别处:
Icon icon = getIcon();
myLabel.setIcon(icon);
// or
JOptionPane.showMessageDialog(null, icon);
没有什么在该代码,将显示图像。如果您有其他图像显示代码,请显示它,并请详细解释您的问题。 –
还有,1)JFileChooser,'getSelectedFile()'返回一个文件 - 为什么你通过获取路径使它变得更复杂,然后得到一个带路径的文件? 2)你回来的是什么? 3)你正在创建一个BufferedImage,然后用这个创建一个ImageIcon,但对你创建的图标无所作为 - 为什么? –
啊,我看到'k'是参数 - 为什么该方法甚至采用参数,然后简单地返回它?就好像方法主体中的所有代码都只是忙于工作而程序将被忽略,所以这变得更加令人困惑 - 请通过解释此代码应该做什么来帮助我们解决问题。 –