Java GUI中根据文件类型获取文件的图标

package cn.edu.hactcm;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.filechooser.FileSystemView;

import sun.awt.shell.ShellFolder;

@SuppressWarnings("serial")
public class FileIconExtractor extends JFrame implements ActionListener {
 private JButton getIconBtn = new JButton("get Icon");
 private JPanel iconPanel = new JPanel();
 private JTextField extField = new JTextField();
 private JLabel smallIconLabel = new JLabel("small Icon here");
 private JLabel bigIconLabel = new JLabel("big Icon here");

 public FileIconExtractor() {
  this.setSize(200, 150);
  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  this.setLayout(new BorderLayout());
  getIconBtn.setActionCommand("GETICON");
  getIconBtn.addActionListener(this);
  iconPanel.setLayout(new BoxLayout(iconPanel, BoxLayout.Y_AXIS));
  iconPanel.add(smallIconLabel);
  iconPanel.add(bigIconLabel);
  this.add(extField, BorderLayout.NORTH);
  this.add(iconPanel, BorderLayout.CENTER);
  this.add(getIconBtn, BorderLayout.SOUTH);
  this.setVisible(true);
 }
 
 /*
 static{
  FileSystemView view = FileSystemView.getFileSystemView();
      try {
   ShellFolder shellFolder = ShellFolder.getShellFolder(new File("xx.gif"));
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } 
 }*/

 public void actionPerformed(ActionEvent e) {
  if (e.getActionCommand().equals("GETICON")) {
   String ext = extField.getText();
   File file;
   try {
    file = File.createTempFile("icon", "." + ext);
    FileSystemView view = FileSystemView.getFileSystemView();
    Icon smallIcon = view.getSystemIcon(file);
    ShellFolder shellFolder = ShellFolder.getShellFolder(file);
    Icon bigIcon = new ImageIcon(shellFolder.getIcon(true));
    setIconLabel(smallIcon, bigIcon);
    file.delete();
   } catch (IOException ioe) {
    ioe.printStackTrace();
   }
  }
 }

 private void setIconLabel(Icon smallIcon, Icon bigIcon) {
  smallIconLabel.setIcon(smallIcon);
  bigIconLabel.setIcon(bigIcon);
 }

 public static void main(String[] args) {
  FileIconExtractor fie = new FileIconExtractor();
 }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值