将此方法调用到我的主窗体类,它将选择文件,但不会显示图像.. 段
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;
}
}
答案 0 :(得分:0)
简而言之,这是您的方法
public static File setpix(File k) throws IOException {
// do lots of busy work that accomplishes nothing
// and then return k:
return k;
}
那就是它。如果你想在GUI中实际显示图像,你应该改为:
getSelectedFile()
,无需将其转换为String,然后获取文件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);