利用JFileChooser选择图片文件并在面板中显示

来源:互联网 发布:上海公交实时查询软件 编辑:程序博客网 时间:2024/05/03 20:57

缺点:需要点击刷一下才可以显示图片,比如最大最小化再看方可显示

Code:
  1. import java.awt.*;   
  2. import java.io.File;   
  3. import java.awt.event.*;   
  4. import javax.swing.filechooser.*;   
  5. import javax.swing.*;   
  6.   
  7. public class Test4 {   
  8.     public static void main(String[] args) {   
  9.         FileChooser fc = new FileChooser();   
  10.     }   
  11. }   
  12.   
  13. class FileChooser extends JFrame implements ActionListener {   
  14.     Container p;   
  15.     static int i = 0;   
  16.     JPanel imgPane;   
  17.     JLabel labeImag;   
  18.     JToolBar tb = new JToolBar();   
  19.     JButton btn = new JButton("O");   
  20.     public FileChooser() {   
  21.         p = getContentPane();   
  22.         btn.setToolTipText("打开以选择图片"); //按钮提示   
  23.         btn.setForeground(Color.red);   
  24.         btn.addActionListener(this);   
  25.         imgPane = new JPanel();   
  26.         tb.add(btn);   
  27.         p.add(tb, BorderLayout.NORTH);   
  28.         setBounds(100100800600);   
  29.         setDefaultCloseOperation(EXIT_ON_CLOSE);   
  30.         setVisible(true);   
  31.     }   
  32.        
  33.     public void actionPerformed(ActionEvent e) {   
  34.         if(e.getSource()==btn) {   
  35.             JFileChooser chooseFile = new JFileChooser();   
  36.             chooseFile.addChoosableFileFilter(new FileCanChoose());   
  37.             int returnVal = chooseFile.showOpenDialog(null);   
  38.       if(returnVal == chooseFile.APPROVE_OPTION) {   
  39.         if(i!=0) {   
  40.             imgPane.remove(labeImag); //移除之前的图片   
  41.         }   
  42.         i++;   
  43.         File f = chooseFile.getSelectedFile();   
  44.         String fname = f.getAbsolutePath();   
  45.         labeImag = new JLabel();   
  46.                 labeImag.setIcon(new ImageIcon(fname));   
  47.         labeImag.setHorizontalAlignment(JLabel.CENTER); //设置图片居中显示   
  48.         imgPane.add(labeImag,BorderLayout.CENTER);   
  49.                 p.add(imgPane,BorderLayout.CENTER);   
  50.         }   
  51.         }   
  52.     }   
  53. }   
  54.   
  55. class FileCanChoose extends FileFilter { //文件过滤器,设置选择对应类型的文件   
  56.         public boolean accept(File file) {      
  57.        String name = file.getName();      
  58.        return(name.toLowerCase().endsWith(".gif")||   
  59.                 name.toLowerCase().endsWith(".jpg")||   
  60.                 name.toLowerCase().endsWith(".bmp")||   
  61.                 name.toLowerCase().endsWith(".png")||   
  62.                 name.toLowerCase().endsWith(".jpeg"));   
  63.    }   
  64.    public String getDescription() {   
  65.     return "图片文件:.gif、 .jpg、 .bmp、 .png、 .jpeg";   
  66.    }   
  67. }  

原创粉丝点击