欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java根据扩展名获取系统图标和文件图标示例

程序员文章站 2024-02-26 16:27:40
复制代码 代码如下:import java.io.file;import java.io.ioexception;import java.awt.borderlayout;...

复制代码 代码如下:

import java.io.file;
import java.io.ioexception;
import java.awt.borderlayout;
import java.awt.event.actionevent;
import java.awt.event.actionlistener;
import javax.swing.icon;
import javax.swing.imageicon;
import javax.swing.jbutton;
import javax.swing.jframe;
import javax.swing.jpanel;
import javax.swing.jtextfield;
import javax.swing.jlabel;
import javax.swing.boxlayout;
import javax.swing.filechooser.filesystemview;
import sun.awt.shell.shellfolder;

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

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