日期:2014-05-20  浏览次数:20707 次

程序可以运行,可是当点击"open"按钮时候,系统有报错了,求高手解答
Java code
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import java.beans.*;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.filechooser.*;
import javax.swing.filechooser.FileFilter;




public class FileChooserTest 
{
    public static void main(String[] args )
    {
        EventQueue.invokeLater(new Runnable()
        {
          public void run()
          {
              ImageViewerFrame frame = new ImageViewerFrame();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setVisible(true);
          }
        
        });
    }
      
}


class ImageViewerFrame extends JFrame
{
    public ImageViewerFrame()
    {
    setTitle("FileChooserTest");
    setSize(300, 400);
    
    
    JMenuBar mbar= new JMenuBar();
    setJMenuBar(mbar);
    
    JMenu fileMenu= new JMenu("File");
    mbar.add(fileMenu);
    

    JMenuItem openItem = new JMenuItem("Open");
    fileMenu.add(openItem);
    openItem.addActionListener(new FileOpenListener());
    
    
    JMenuItem exitItem = new JMenuItem("Exit");
    fileMenu.add(exitItem);
    exitItem.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent event)
        {
            System.exit(0);
            
        }
    });
    
    label = new JLabel();
    add(label);
    
    chooser = new JFileChooser();
    
     FileNameExtensionFilter filter = new FileNameExtensionFilter("Image files","jpg","jpeg","gif");
     chooser.setFileFilter(filter);
     
     chooser.setAccessory(new ImagePreviewer(chooser));
     
     chooser.setFileView(new FileIconView(filter,new ImageIcon("paletee.gif")));


   }
     private JLabel label;
     private JFileChooser chooser=null;
 


 

  private class FileOpenListener implements ActionListener   
 {

    
    public void actionPerformed(ActionEvent event) 
    {
        
        chooser.setCurrentDirectory(new File("."));
        JFileChooser chooser = new JFileChooser();

        int result = chooser.showOpenDialog(ImageViewerFrame.this); 
        
        if (result == JFileChooser.APPROVE_OPTION)
        {
            String filename= chooser.getSelectedFile().getPath();
//            label.setIcon(new ImageIcon(filename));
        
        }
    }
    private JLabel label;
    private Component ImageViewerFrame;

 }
}
 


------解决方案--------------------
得到文件路径后,用第三方的jar(jdom或dom4j)解析这个文件然后显示出来
------解决方案--------------------
把class FileOpenListener 中重复定义的private JLabel label;去掉就可以
然后label.setIcon(new ImageIcon(filename));这个也不用注释掉