Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

java - How to use JFileChooser to display image in a JFrame or JPanel

I have created a program that can change the format of an image. Everything is working, but when I open an image through JFileChooser I am getting java.lang.ClassCastException. Please can somebody help me. I think I am making a mistake when using the file chooser. I am beginner, please can somebody help me as soon as possible?

 package helloWorld;

   import java.io.*;
   import java.util.TreeSet;
   import java.awt.*;
   import java.awt.event.*;
   import java.awt.geom.AffineTransform;
   import java.awt.image.*;
   import javax.imageio.*;
   import javax.swing.*;
   import javax.swing.filechooser.FileNameExtensionFilter;

   public class SaveImage extends Component implements Action Listener {

    String descs[] = {
    "Original", 
        "Convolve : LowPass",
        "Convolve : Sharpen", 
        "LookupOp",
    };

    int opIndex;
    private BufferedImage bi, biFiltered;
    private BufferedImage temp;
    int w, h;

    public static final float[] SHARPEN3x3 = { // sharpening filter kernel
        0.f, -1.f,  0.f,
       -1.f,  5.f, -1.f,
        0.f, -1.f,  0.f
    };

    public static final float[] BLUR3x3 = {
        0.1f, 0.1f, 0.1f,    // low-pass filter kernel
        0.1f, 0.2f, 0.1f,
        0.1f, 0.1f, 0.1f
    };

    public SaveImage()

    {

        try {
            bi = ImageIO.read(new File("")); // yahan kisi image ka path daal de
            w = bi.getWidth(null);
            h = bi.getHeight(null);
            if (bi.getType() != BufferedImage.TYPE_INT_RGB) {
                BufferedImage bi2 =
                    new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
                Graphics big = bi2.getGraphics();
                big.drawImage(bi, 0, 0, null);
                biFiltered = bi = bi2;
            }
        } catch (IOException e) {
            System.out.println("Image could not be read");
            System.exit(1);
        }
    }


    public void setimg( String path){}


    public Dimension getPreferredSize() {
        return new Dimension(w, h);
    }

    String[] getDescriptions() {
        return descs;
    }

    void setOpIndex(int i) {
        opIndex = i;
    }

    public void paint(Graphics g) {
        filterImage();
        g.drawImage(biFiltered, 0, 0, null);
    }

    int lastOp;
    public void filterImage() {
        BufferedImageOp op = null;

        if (opIndex == lastOp) {
            return;
        }
        lastOp = opIndex;
        switch (opIndex) {

        case 0: biFiltered = bi; /* original */
                return; 
        case 1:  /* low pass filter */
        case 2:  /* sharpen */
            float[] data = (opIndex == 1) ? BLUR3x3 : SHARPEN3x3;
            op = new ConvolveOp(new Kernel(3, 3, data),
                                ConvolveOp.EDGE_NO_OP,
                                null);

            break;

        case 3 : /* lookup */
            byte lut[] = new byte[256];
            for (int j=0; j<256; j++) {
                lut[j] = (byte)(256-j); 
            }
            ByteLookupTable blut = new ByteLookupTable(0, lut); 
            op = new LookupOp(blut, null);
            break;
        }


        biFiltered = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        op.filter(bi, biFiltered);
    }

    /* Return the formats sorted alphabetically and in lower case */
    public String[] getFormats() {
        String[] formats = ImageIO.getWriterFormatNames();
        TreeSet<String> formatSet = new TreeSet<String>();
        for (String s : formats) {
            formatSet.add(s.toLowerCase());
        }
        return formatSet.toArray(new String[0]);
    }


     public void actionPerformed(ActionEvent e) {

         if (e.getActionCommand()=="browse")
         {
             //yahan pe bhundd h browse ka
             JFileChooser file = new JFileChooser();
            file.setCurrentDirectory(new File(System.getProperty("user.home")));
            FileNameExtensionFilter filter = new             FileNameExtensionFilter("*.Images","jpg", "gif", "png" );
            file.addChoosableFileFilter(filter);
            int result = file.showSaveDialog(null);
            if (result==JFileChooser.APPROVE_OPTION)
            {
                File selectedFile = file.getSelectedFile();
                String Path = selectedFile.getAbsolutePath();
            try{
                setimg(Path);// bi = ImageIO.read(new File(Path));
            //  temp = new BufferedImage(Path);//       label.setIcon(ResizeImage(Path));
                //}
            //  catch(IOException e1){
                    System.out.println("file not found");
                //}
            }
            else if(result== JFileChooser.CANCEL_OPTION)
            {
            //  ImageIcon Mimage = new      ImageIcon("C:\Users\Hasnain\Downloads\1.jpg");
                System.out.println("No file choosed");
                //label.setIcon(Mimage);
            }    
         }

         JComboBox cb = (JComboBox)e.getSource();
         if (cb.getActionCommand().equals("SetFilter")) {
             setOpIndex(cb.getSelectedIndex());
             repaint();
         } else if (cb.getActionCommand().equals("Formats")) {
             /* Save the filtered image in the selected format.
              * The selected item will be the name of the format to use
              */
             String format = (String)cb.getSelectedItem();
             /* Use the format name to initialise the file suffix.
              * Format names typically correspond to suffixes
              */
             File saveFile = new File("savedimage."+format);
             JFileChooser chooser = new JFileChooser();
             chooser.setSelectedFile(saveFile);
             int rval = chooser.showSaveDialog(cb);
             if (rval == JFileChooser.APPROVE_OPTION) {
                 saveFile = chooser.getSelectedFile();
                 /* Write the filtered image in the selected format,
                  * to the file chosen by the user.
                  */
                 try {
                     ImageIO.write(biFiltered, format, saveFile);
                 } catch (IOException ex) {
                 }
             }
         }
    };

    public static void main(String s[]) {
        JButton button = new JButton("Browse");
        button.setBounds(300, 300, 100, 40);

        JFrame f = new JFrame("Save Image Sample");
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);}
        });
        SaveImage si = new SaveImage();
        f.add("Center", si);
        JComboBox choices = new JComboBox(si.getDescriptions());
        choices.setActionCommand("SetFilter");
        choices.addActionListener(si);
        JComboBox formats = new JComboBox(si.getFormats());
        formats.setActionCommand("Formats");
        formats.addActionListener(si);
        JPanel panel = new JPanel();
        panel.add(button);
        button.setEnabled(true);

        panel.add(choices);
        panel.add(new JLabel("Save As"));
        panel.add(formats);
        f.add("South", panel);
        f.pack();
        f.setVisible(true);
        button.addActionListener(si);
        button.setActionCommand("browse");
    }
}  
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

this is a demo of file chooser

 import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.filechooser.FileFilter;

 public class JFileChooserDemo extends JPanel {

 private JTextArea textArea;

 public JFileChooserDemo() {
  super(new BorderLayout());
   createPanel();
   }

 private void createPanel() {
JButton openFileChooser = new JButton("Apri File");
JButton saveFileChooser = new JButton("Salva File");
openFileChooser.addActionListener(new OpenFileChooser());
saveFileChooser.addActionListener(new SaveFileChooser());
textArea = new JTextArea(10, 20);
add(new JScrollPane(textArea), BorderLayout.CENTER);
JPanel panelButton = new JPanel();
panelButton.add(openFileChooser);
panelButton.add(saveFileChooser);
 add(panelButton, BorderLayout.SOUTH);
  }

   private class OpenFileChooser implements ActionListener {

   public void actionPerformed(ActionEvent e) {
  try {
    textArea.setText("");
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileFilter(new TxtFileFilter());
    int n = fileChooser.showOpenDialog(JFileChooserDemo.this);
    if (n == JFileChooser.APPROVE_OPTION) {
      File f = fileChooser.getSelectedFile();
      BufferedReader read = new BufferedReader(new FileReader(f));
      String line = read.readLine();
      while(line != null) {
        textArea.append(line);
        line = read.readLine();
      }
      read.close();
    }
   } catch (Exception ex) {}
   }
 }

  private class SaveFileChooser implements ActionListener {

 public void actionPerformed(ActionEvent e) {
  try {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileFilter(new TxtFileFilter());
    int n = fileChooser.showSaveDialog(JFileChooserDemo.this);
    if (n == JFileChooser.APPROVE_OPTION) {
      File f = fileChooser.getSelectedFile();
      BufferedWriter write = new BufferedWriter(new FileWriter(f));
      write.append(textArea.getText());
      write.flush();
      write.close();
    }
  } catch (Exception ex) {}
  }
 }

 private class TxtFileFilter extends FileFilter {

public boolean accept(File file) {
  if (file.isDirectory()) return true;
    String fname = file.getName().toLowerCase();
    return fname.endsWith("txt");
}

  public String getDescription() {
  return "File di testo";
  }
}

 public static void main(String[] argv) {
JFrame frame = new JFrame("JFileChooserDemo");
JFileChooserDemo demo = new JFileChooserDemo();
frame.getContentPane().add(demo);
frame.pack();
frame.setVisible(true);
 }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...