Java 如何使用JFileChooser在JFrame或JPanel中显示图像
我创建了一个可以改变图像格式的程序。一切正常,但当我通过JFileChooser打开一个图像时,我得到了Java 如何使用JFileChooser在JFrame或JPanel中显示图像,java,swing,awt,Java,Swing,Awt,我创建了一个可以改变图像格式的程序。一切正常,但当我通过JFileChooser打开一个图像时,我得到了java.lang.ClassCastException。谁能帮帮我吗。我想我在使用文件选择器时犯了一个错误。我是初学者,有人能尽快帮我吗 package helloWorld; import java.io.*; import java.util.TreeSet; import java.awt.*; import java.awt.event.*; imp
java.lang.ClassCastException
。谁能帮帮我吗。我想我在使用文件选择器时犯了一个错误。我是初学者,有人能尽快帮我吗
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");
}
}
包helloWorld;
导入java.io.*;
导入java.util.TreeSet;
导入java.awt.*;
导入java.awt.event.*;
导入java.awt.geom.AffineTransform;
导入java.awt.image.*;
导入javax.imageio.*;
导入javax.swing.*;
导入javax.swing.filechooser.FileNameExtensionFilter;
公共类SaveImage扩展组件实现操作侦听器{
字符串描述[]={
“原件”,
“卷积:低通”,
“卷积:锐化”,
“LookupOp”,
};
int opIndex;
私有缓冲映像bi,双过滤;
专用缓冲区映像温度;
int w,h;
公共静态最终浮点[]锐化3x3={//锐化过滤器内核
0.f,-1.f,0.f,
-1.f,5.f,-1.f,
0.f,-1.f,0.f
};
公共静态最终浮动[]3x3={
0.1f,0.1f,0.1f,//低通滤波器内核
0.1f、0.2f、0.1f、,
0.1f、0.1f、0.1f
};
公共存储映像()
{
试一试{
bi=ImageIO.read(新文件(“”);//yahan kisi图像ka路径daal de
w=bi.getWidth(空);
h=bi.getHeight(空);
if(bi.getType()!=buffereImage.TYPE\u INT\u RGB){
缓冲图像bi2=
新的BuffereImage(w,h,BuffereImage.TYPE_INT_RGB);
Graphics big=bi2.getGraphics();
big.drawImage(bi,0,0,null);
双过滤=bi=bi2;
}
}捕获(IOE异常){
System.out.println(“无法读取图像”);
系统出口(1);
}
}
公共void setimg(字符串路径){}
公共维度getPreferredSize(){
返回新尺寸(w,h);
}
字符串[]getDescriptions(){
返回描述;
}
无效设置索引(int i){
opIndex=i;
}
公共空间涂料(图g){
filterImage();
g、 drawImage(双过滤,0,0,空);
}
int lastOp;
公共无效筛选器映像(){
BufferedImageOp op=null;
如果(opIndex==lastOp){
返回;
}
lastOp=opIndex;
开关(opIndex){
案例0:双过滤=bi;/*原始*/
返回;
情况1:/*低通滤波器*/
案例2:/*锐化*/
float[]数据=(opIndex==1)?模糊3x3:锐化3x3;
op=新卷积op(新内核(3,3,数据),
卷积,边缘,无卷积,
无效);
打破
案例3:/*查找*/
字节lut[]=新字节[256];
对于(intj=0;j这是一个文件选择器的演示
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);
}
}
这是你自己的图像处理课程吗
下面的代码是您的干净代码,我只花了一点努力
package com.tobee.ui.test;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ByteLookupTable;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.awt.image.LookupOp;
import java.io.File;
import java.io.IOException;
import java.util.TreeSet;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter;
public class SaveImage extends Component implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
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(String path) {
try {
bi = ImageIO.read(new File(path));
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) {
System.err.println("....setimg...." + path);
if(bi != null) bi.flush();
bi = null;
try {
bi = ImageIO.read(new File(path)); // yahan kisi image ka path daal de
w = bi.getWidth();
h = bi.getHeight();
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);
}
//choices.setSelectedIndex(0);
//formats.setSelectedIndex(0);
}
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) {
String command = e.getActionCommand();
System.out.println("Command...." + command);
if ( command.equalsIgnoreCase("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();
else if( command.equalsIgnoreCase("SetFilter")) {
System.out.println("..SetFilter..." + choices.getSelectedIndex() + "::" + choices.getSelectedItem().toString());
setOpIndex(choices.getSelectedIndex());
repaint();
} else if (command.equalsIgnoreCase("Formats")) {
System.out.println("..Formats..." + formats.getSelectedIndex() + "::" + formats.getSelectedItem().toString());
int opt = JOptionPane.showConfirmDialog(null, "Do you want to save it?", "save image",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null);
switch(opt)
{
case JOptionPane.CANCEL_OPTION:
return;
}
/*
* Save the filtered image in the selected format. The selected item
* will be the name of the format to use
*/
String format = (String) formats.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(formats);
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) {
}
}
}
};
final static Runnable doRun = new Runnable()
{
@Override
public void run() {
JOptionPane.showMessageDialog(null, "You must choose file first", "choose file", JOptionPane.INFORMATION_MESSAGE, null);
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);
String Path = null;
switch(result)
{
case JFileChooser.APPROVE_OPTION:
Path = file.getSelectedFile().getAbsolutePath();
break;
case JFileChooser.CANCEL_OPTION:
return;
}
JFrame f = new JFrame("Save Image Sample");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JPanel panel = new JPanel();
System.setProperty("user.home", Path);
SaveImage si = new SaveImage(Path);
JComboBox<String> choices = new JComboBox<String>(si.getDescriptions());
choices.setActionCommand("SetFilter");
choices.addActionListener(si);
JComboBox<String> formats = new JComboBox<String>(si.getFormats());
formats.setActionCommand("Formats");
formats.addActionListener(si);
si.setChoiceComponent(choices);
si.setFormatComponent(formats);
JButton button = new JButton("Browse");
button.setActionCommand("browse");
button.addActionListener(si);
button.setBounds(300, 300, 100, 40);
button.setEnabled(true);
panel.add(button);
panel.add(choices);
panel.add(new JLabel("Save As"));
panel.add(formats);
f.add("Center", si);
f.add("South", panel);
f.pack();
f.setVisible(true);
}
};
public static void main(String s[]) {
SwingUtilities.invokeLater(doRun);
}
private JComboBox<String> choices;
private JComboBox<String> formats;
protected void setFormatComponent(final JComboBox<String> formats) {
this.formats = formats;
}
protected void setChoiceComponent(final JComboBox<String> choices) {
this.choices = choices;
}
}
包com.tobee.ui.test;
导入java.awt.Component;
导入java.awt.Dimension;
导入java.awt.Graphics;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.awt.event.WindowAdapter;
导入java.awt.event.WindowEvent;
导入java.awt.image.buffereImage;
导入java.awt.image.BufferedImageOp;
导入java.awt.image.ByteLookupTable;
导入java.awt.image.ConvolveOp;
导入java.awt.image.Kernel;
导入java.awt.image.LookupOp;
导入java.io.File;
导入java.io.IOException;
导入java.util.TreeSet;
导入javax.imageio.imageio;
导入javax.swing.JButton;
导入javax.swing.JComboBox;
导入javax.swing.JFileChooser;
导入javax.swing.JFrame;
导入javax.swing.JLabel;
导入javax.swing.JOptionPane;
导入javax.swing.JPanel;
导入javax.swing.SwingUtilities;
导入javax.swing.filechooser.FileNameExtensionFilter;
公共类SaveImage扩展组件实现ActionListener{
/**
*
*/
私有静态最终长serialVersionUID=1L;
字符串descs[]={“原始”、“卷积:低通”、“卷积:锐化”、“LookupOp”,};
int opIndex;
私有缓冲映像bi,双过滤;
//专用缓冲区映像温度;
int w,h;
公共静态最终浮点[]锐化3x3={//锐化过滤器内核
0.f,-1.f,0.f,-1.f,5.f,-1.f,0.f,-1.f,0.f};
公共静态最终浮点[]BLUR3x3={0.1f,0.1f,0.1f,//低通滤波器
//内核
0.1f、0.2f、0.1f、0.1f、0.1f、0.1f};
公共存储映像(字符串路径){
试一试{
bi=ImageIO.read(新文件(路径));
w=bi.getWidth(空);
h=bi.getHeight(空);
if(bi.getType()!=buffereImage.TYPE\u INT\u RGB){
BuffereImage bi2=新的BuffereImage(w,h,BuffereImage.TYPE_INT_RGB);
Graphics big=bi2.getGraphics();
big.drawImage(bi,0,0,null);
双过滤=bi=bi2;
}
}捕获(IOE异常){
System.out.println(“无法读取图像”);
系统出口(1);
}
}
公共void setimg(字符串路径){
System.err.println(“..setimg..”+路径);
如果(bi!=null)bi.flush();
bi=null;
试一试{
bi=ImageIO.read(新文件(路径));//yahan kisi图像ka路径daal de
w=bi.getWidth();
h=bi.getHeight();
if(bi.getType()!=buffereImage.TYPE\u INT\u RGB){
BuffereImage bi2=新的BuffereImage(w,h,BuffereImage.TYPE_INT_RGB);
Graphics big=bi2.getGraphics();
big.drawImage(bi,0,0,null);
双过滤=bi=bi2;
}
}捕获(IOE异常){
系统退出。