天天看点

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();

}