天天看點

20年前用Java寫的批量改名小工具

作者:13妖工作室

這個周末在家無意翻到了2004年用Java寫的批量改名小工具,今天分享給大家樂一樂。記得當時還沒有IDE,使用記事本寫的,寫一段用cmd指令運作了看看效果,慢慢調試。這麼多年過去了Java技能徹底被抛之腦後了。感興趣的小夥伴可以複制代碼去運作了看看,選擇對應的檔案夾或者輸入路徑将檔案夾中的所有檔案通過一定的規則進行命名,支援改名後還原的功能。

運作代碼

1.建立一個文本檔案,改名為PLGM.java 複制下面的代碼 儲存

2. cmd 視窗 輸入:

javac PLGM.java
java  PLGM           

運作結果

20年前用Java寫的批量改名小工具
20年前用Java寫的批量改名小工具

具體代碼

/****************************************************************/
/*                      plgm                             */
/*                                                              */
/****************************************************************/
import javax.swing.border.*;
import javax.swing.ListModel;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import javax.swing.tree.*;
import javax.swing.filechooser.*;
import java.io.*;
import java.util.*;
import java.sql.*; 
import java.lang.Exception;
/**
 * Summary description for plgm
 *
 */
@SuppressWarnings("unchecked")
public class PLGM extends JFrame
{
private JTabbedPane jTabbedPane1;
private JPanel contentPane;
//-----
private JLabel jLabel1;
private JCheckBox jcballsel;
//private JCheckBox jcbresel;
  private JTextField jtpath;
private JTree tree;
private JPanel jPanel1;
//-----
private JPanel jpanellist;
//-----
private JLabel  jlname;
// private JCheckBox jcbisdirectory;
private JTextField jtname;
private JButton jbchose;
private JPanel jPanel5;
//-----
private JCheckBox jcbrename;
private JCheckBox jcbreext;
private JCheckBox jcbid;
private JTextField jtrename;
private JTextField jtreext;
private JTextField jtnumber;
private JButton jbchange;
private JButton jbback;
private JPanel jPanel6;
// JDialog
      private JDialog dialog;
//Status Bar
   private JTextField statusbar;
//JCheckBox
  //  Vector checkboxes =new Vector();
    private JButton jbdel;
//-----
FileSystemView  fileSystemView=FileSystemView.getFileSystemView();
    //菜單的定義
    JMenuBar menuBar = new JMenuBar();
    JMenu menuFile1 = new JMenu("檔案");
    JMenu menuFile2 = new JMenu("幫助");
    JMenuItem menuItemExit = new JMenuItem("退出");
    JMenuItem menuaboutus = new JMenuItem("關于我們");
    JMenuItem menuHowUse = new JMenuItem("如何使用");
private ActionListener aListener;
//
// TODO: Add any attribute code to meet your needs here
//
public PLGM()
{
super();
initializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
jcbid.setEnabled(false);
    jtnumber.setEnabled(false);
//
this.setVisible(true);
}
private void initializeComponent()
{
//tree的初始化
FileNode root=new FileNode(fileSystemView.getRoots()[0]);//調用FileNode類得到系統桌面檔案夾getRoots()[0]。數組getRoots()[0]可改變。
DefaultTreeModel treeModel=new DefaultTreeModel(root);//定義JTree 模型
tree = new JTree(treeModel);
tree.setEditable(true);//設定編輯狀态   
tree.setCellRenderer(new MyTreeCellRenderer());//調用setCellRenderer内部類
tree.setSelectionRow(0);//初始時不要展開JTree
tree.setComponentOrientation(ComponentOrientation.UNKNOWN);
//  設定JTree的監聽事件
tree.addTreeExpansionListener(new TreeExpansionListener(){
public void treeCollapsed(TreeExpansionEvent e) {
}//必須寫
public void treeExpanded(TreeExpansionEvent e) {
TreePath path = e.getPath();
FileNode node = (FileNode) path.getLastPathComponent();
jtpath.setText(node.getFile().toString());
//
File tardir=new File(node.getFile().toString());
// SelectFiles(tardir);//調用SelectFiles
jpanellist.removeAll();//清除jpanellist的所有内容
addcheckbox addcb =new addcheckbox();
addcb.addcheckbox(tardir);
//如果節點沒有展開
if( ! node.isExplored()) {
DefaultTreeModel model=(DefaultTreeModel)tree.getModel();
node.explore();
model.nodeStructureChanged(node);
}
}
});
        setJMenuBar(menuBar);
  
        menuFile1.add(menuItemExit);// 加入子菜單
        
        menuFile2.add(menuHowUse);
        menuFile2.add(menuaboutus);
        
        menuBar.add(menuFile1);
        menuBar.add(menuFile2);
 // JDialog
 
 dialog=new JDialog();
 dialog.getContentPane().setLayout(new FlowLayout());
 dialog.setSize(300,300);
 dialog.setModal(true);
 dialog.setTitle("關于我們!");
// dialog.getContentPane().add();
// dialog.setBackground();
// dialog.update("1.jpg");
//增加菜單的單擊事件
 
  
menuItemExit.addActionListener(new ActionListener()  {
    public void actionPerformed(ActionEvent e) {System.exit(0);}
  });
       menuaboutus.addActionListener(new ActionListener()  {
    public void actionPerformed(ActionEvent e) {
    // dialog.show(true);
  JOptionPane.showMessageDialog(null,"");
     }
  });
  
  menuHowUse.addActionListener(new ActionListener()  {
    public void actionPerformed(ActionEvent e) {
    
    JOptionPane.showMessageDialog(null,"本程式實作了檔案的批量改名!"+"n"+"并帶有還原功能!"+"n"+"歡迎使用并指出其中不足!"+"n"+"設計者:13妖"+"n"+"聯系方式 QQ:39464686"+"n"+"Email:[email protected]");
     }
  });
jTabbedPane1 = new JTabbedPane();
contentPane = (JPanel)this.getContentPane();
//-----
jLabel1 = new JLabel();
jcballsel = new JCheckBox();
// jcbresel=new JCheckBox();
jtpath = new JTextField();
jPanel1 = new JPanel();
jpanellist = new JPanel();
//-----
jlname=new JLabel();
// jcbisdirectory = new JCheckBox();
jtname = new JTextField();
jbchose = new JButton();
jbdel=new JButton();
jPanel5 = new JPanel();
//-----
jcbrename = new JCheckBox();
jcbreext = new JCheckBox();
jcbid = new JCheckBox();
jtrename = new JTextField();
    jtreext = new JTextField();
jtnumber = new JTextField();
jbchange = new JButton();
jbback = new JButton();
jPanel6 = new JPanel();
//-----
 JCheckBox cb =new JCheckBox();
 
 //statusbar
  statusbar=new JTextField();
  statusbar.setText("");
  statusbar.setEditable(false);
//  add(statusbar,BorderLayout.SOUTH);
 
aListener = new AListener();
//
// jTabbedPane1
//
jTabbedPane1.addTab("批量改名", jPanel1);
//
// contentPane
//
contentPane.setLayout(null);
addComponent(contentPane, jTabbedPane1, 0,0,720,450);
//
// jLabel1
//
jLabel1.setText("直達路徑");
//
// jcballsel
//
jcballsel.setText("全選");
jcballsel.addActionListener(aListener);
//
addComponent(contentPane, statusbar, 0,450,720,20);
//jcbresel.setText("反選");
//jcbresel.addActionListener(aListener);
//
jbdel.setText("删除");
jbdel.addActionListener(aListener);
// jtpath
//
jtpath.setText("");
jtpath.addActionListener(aListener);
jtpath.addKeyListener(new myKeyAdapter());
//
// tree
//
//
// jPanel1
//
jPanel1.setLayout(null);
addComponent(jPanel1, jLabel1, 224,9,60,18);
addComponent(jPanel1, jcballsel, 224,36,49,24);
//addComponent(jPanel1, jcbresel, 280,36,49,24);
addComponent(jPanel1,jbdel,350,36,59,20);
addComponent(jPanel1, jtpath, 300,8,400,22);
addComponent(jPanel1, new JScrollPane(tree), 3,3,212,413);
//
addComponent(jPanel1, new JScrollPane(jpanellist), 224,67,277,350);//加入滾動條
addComponent(jPanel1, jPanel5, 507,59,200,130);
addComponent(jPanel1, jPanel6, 509,200,200,220);
//
// jpanellist
//
jpanellist.setBorder(BorderFactory.createLineBorder(Color.black));
jpanellist.setLayout(new BoxLayout(jpanellist, BoxLayout.Y_AXIS)); 
 
// jlname
//
jlname.setText("要搜尋的檔案");
//
// jcbext
//
// jcbext.setText("擴充名");
//
// jcbisdirectory
//
// jcbisdirectory.setText("是否需要子檔案夾");
//
// jtname
//
jtname.setText("");
jtname.addActionListener(aListener);
//
// jbchose
//
jbchose.setText("搜尋");
jbchose.addActionListener(aListener);
//
// jPanel5
//
jPanel5.setBorder(new TitledBorder("搜尋"));
jPanel5.setLayout(null);
addComponent(jPanel5, jlname, 8,16,100,25);
// addComponent(jPanel5, jcbisdirectory, 5,70,133,25);
addComponent(jPanel5, jtname, 90,18,100,22);
addComponent(jPanel5, jbchose, 80,100,59,20);
//
// jcbrename
//
jcbrename.setText("檔案名");
jcbrename.addActionListener(aListener);
//
// jcbreext
//
jcbreext.setText("擴充名");
//
// jcbid
//
jcbid.setText("編   号");
//
// jtrename
//
jtrename.setText("");
jtrename.addActionListener(aListener);
//
// jtreext
//
    jtreext.setText("");
jtreext.addActionListener(aListener);
//
// jtnumber
//
jtnumber.setText("");
jtnumber.addActionListener(aListener);
//
// jbchange
//
jbchange.setText("改名");
jbchange.addActionListener(aListener);
//
// jbback
//
jbback.setText("還原");
jbback.addActionListener(aListener);
//
// jPanel6
//
jPanel6.setBorder(new TitledBorder("改名"));
jPanel6.setLayout(null);
addComponent(jPanel6, jcbrename, 5,30,83,25);
addComponent(jPanel6, jcbreext, 5,60,83,25);
addComponent(jPanel6, jcbid, 5,95,83,25);
addComponent(jPanel6, jtrename, 90,30,100,22);
        addComponent(jPanel6, jtreext, 90,60,100,22);
addComponent(jPanel6, jtnumber, 90,95,100,21);
addComponent(jPanel6, jbchange, 20,165,59,20);
addComponent(jPanel6, jbback, 120,165,59,20);
//
// plgm
//
WListener wListener = new WListener();
this.addWindowListener(wListener);
this.setTitle("批量改名系統  設計者:13妖 聯系方式 QQ:39464686 Email:[email protected]");
this.setSize(720,520);
this.setLocation(0,20);
this.setResizable(false);
}
/** Add Component Without a Layout Manager (Absolute Positioning) */
private void addComponent(Container container,Component c,int x,int y,int width,int height)
{
c.setBounds(x,y,width,height);
container.add(c);
}
//
// TODO: Add any appropriate code in the following Event Methods
//
private void jbchose_actionPerformed(ActionEvent e)
{
// FileNode node = (FileNode)tree.getLastSelectedPathComponent();
  //  File tardir=new File(node.getFile().toString());
    File tardir=new File(jtpath.getText().toString());
if(!tardir.exists())
      { 
        JOptionPane.showMessageDialog(null,"指定的目錄不存在!");
        return;   
      }
                   jpanellist.removeAll();
                   jpanellist.repaint();
                   chosefile(tardir);
                   statusbar.setText("");
}
//給檔案改名
private String renamefile(File tardir,int id)
   {
String rename;
    String reext;
    String temp="...";
    File ftemp;
    String str1;
    String str2;
     temp=tardir.getName();
     str1=temp.substring(0,temp.indexOf("."));//得到"."前的檔案名
     str2=temp.substring(temp.indexOf("."));//得到擴充名
     rename=jtrename.getText().toString();
   reext=jtreext.getText().toString();
   if(jcbrename.isSelected())
   {   
         temp=tardir.getParent()+"\\"+rename+str2;
} if(jcbid.isSelected())
   {
    //temp=temp+String.valueOf(id);
    temp=tardir.getParent()+"\\"+rename+String.valueOf(id)+str2;
    }
  if(jcbreext.isSelected()){
//temp=temp+reext;
    temp=tardir.getParent()+"\\"+str1+reext;
}
try{
  ftemp=new File(temp); 
  tardir.renameTo(ftemp);}
catch(Exception exp){System.out.println("改名不成功");}
   return temp;
    }
      
//end給檔案改名
//改名按鈕 
private void jbchange_actionPerformed(ActionEvent e)
{    
   Vector block=new Vector();
    int dizhen=0;//遞增參數初始化等于0
if(jtnumber.isEnabled()&&(jtnumber.getText().toString().length()>0))//如果編号文本框可用并且不為空
    {
dizhen=Integer.parseInt(jtnumber.getText());//将編号文本框的值賦給變量dizhen
}
for(int i=0;i<jpanellist.getComponentCount();++i)
     {   
      
     String temp="";
try{ 
JCheckBox tempjcb= (JCheckBox)jpanellist.getComponent(i);//将jpanellist中元件的類型轉換成JCheckBox
if (tempjcb.isSelected())//如果被選中
{  
File  tardir=new File(tempjcb.getText().trim());   //得到檔案
   if(!tardir.exists()){
        JOptionPane.showMessageDialog(null,"指定的檔案不存在!");
    }
    else
    {
    
    try{
  
        
    temp= renamefile(tardir,dizhen);//調用renamefile函數将變量dizhen傳入函數renamefile
    dizhen++;//變量dizhen進行遞增
    
  block.add(tardir.getPath()+"..."+temp);
 }
catch(Exception exp){JOptionPane.showMessageDialog(null,"可能名稱有重複。無法改名");}
    if (temp!="...")
    {
  tempjcb.setText(temp);  //将jpanellist 中JCheckBox的名稱改為改名後的檔案名
    }
    }
   
   /*   
    
           */
    }
} 
catch(Exception exp )
{
JOptionPane.showMessageDialog(null,"找不到需要的元件!");
}
}
     
write(block);//寫入文本
//read();
}
private void jbback_actionPerformed(ActionEvent e)
{
     back();
}
private void jtpath_actionPerformed(ActionEvent e)
{
// Add any appropriate code here
}
private void jtname_actionPerformed(ActionEvent e)
{
// Add any appropriate code here
}
private void jcbrename_actionPerformed(ActionEvent e)
{
if(jcbrename.isSelected())
   {
     jcbid.setEnabled(true);
     jtnumber.setEnabled(true);
    }
    else
    {jcbid.setEnabled(false);
    jtnumber.setEnabled(false);
   
    }
}
private void jtrename_actionPerformed(ActionEvent e)
{
   
}
private void jtreext_actionPerformed(ActionEvent e)
{
// Add any appropriate code here
}
private void jtnumber_actionPerformed(ActionEvent e)
{
// Add any appropriate code here
}
//全選按鈕
private void jcballsel_actionPerformed(ActionEvent e)
{  
        //   File tardir;
   addcheckbox addcb =new addcheckbox();
       // tardir=new File(jtpath.getText().toString().trim());
     if(jcballsel.isSelected())
     {  
      //jpanellist.removeAll();
     // addcb.addcheckbox(tardir,true);
     addcb.selected(true);
     }
     else
     {
   // jpanellist.removeAll();
   //  addcb.addcheckbox(tardir,false);
     addcb.selected(false);
  
     }
}
//反選按鈕
//private void jcbresel_actionPerformed(ActionEvent e)
//{  
        
//}
//删除檔案
private void delfile(File tardir){
Object[] options={"确定","取消"};
int choose=JOptionPane.showOptionDialog(this,"點選确定将删除:"+tardir.getName(),"警告:如果删除将無法恢複",JOptionPane.OK_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE,null, options, options[0]);
if(choose!=0)
{
return;
}
else
{
tardir.deleteOnExit();
if(tardir.delete()){
   JOptionPane.showMessageDialog(null,"成功删除 "+tardir.getName());
   }
  else
  {
   JOptionPane.showMessageDialog(null,"删除不成功");
   }  
}
}
//增加檔案
private void addfile(File tardir){
try{
tardir=new File("","FO.ini");
System.out.println(tardir.toString());
if(tardir.createNewFile()){
JOptionPane.showMessageDialog(null,"增加成功");
}
}
catch(Exception exp){
JOptionPane.showMessageDialog(null,"增加失敗");
}
}
/**
 *
 *隻能删除一個記錄??????????不能批量删除?????????
 *如果不判斷是否被删除(delete())則可以删除!不過要重新啟動才能有效!
 *解決問題:repaintpanell();的位置擺放!
 */
//删除按鈕事件
private void jbdel_actionPerformed(ActionEvent e)
{  
for(int i=0;i<jpanellist.getComponentCount();++i)
     {   
      
    
JCheckBox tempjcb= (JCheckBox)jpanellist.getComponent(i);//将jpanellist中元件的類型轉換成JCheckBox
if (tempjcb.isSelected())//如果被選中
{  
  
File  tardir=new File(tempjcb.getText().trim());   //得到檔案
     delfile(tardir);
  
} 
    }
 repaintpanell();//重新調整
}
//
// TODO: Add any method code to meet your needs in the following area
//
//jtpath的鍵盤事件
class myKeyAdapter extends KeyAdapter {
public void keyPressed(KeyEvent e)
{
switch(e.getKeyCode())
{
case KeyEvent.VK_ENTER:
       {
// JOptionPane.showMessageDialog(null," 你按了Enter鍵!");
repaintpanell();break;
}
}
}
}
//end
private void repaintpanell(){
File tardir;
        jpanellist.removeAll();
        jpanellist.repaint();
        
tardir=new File(jtpath.getText().toString().trim());
if(tardir.isDirectory()){
addcheckbox add =new addcheckbox();
            add.addcheckbox(tardir);}
}
    //搜尋檔案
   public void chosefile(File tardir)
   {
    String name;
    String strname;
    String str2;
    int count=0;
    File[] list=tardir.listFiles();
     if(list!=null && list.length>0)
      {
       for(int x=0;x<list.length;++x)
      
       {
       if(list[x].isFile()){
       name=jtname.getText().trim();
      // str1=name.substring(0,name.indexOf("."));
       // str2=name.substring(name.indexOf("."));
//        System.out.println(str1);
      //  System.out.println(str2);
      //注意indexof的用法!!!!!!!!!!!
   strname=list[x].getName().toString().trim();
      if(strname.indexOf(name)!=-1 || strname.endsWith(name) ){
       System.out.println(list[x].getPath());
       statusbar.setText("正在搜尋中......");
       statusbar.repaint();
       // statusbar.setText("");
      
           addcheckbox addjcb =new addcheckbox();
               addjcb.addcheckbox(list[x]);  
               // System.out.println("aa");
                 count++;
               // System.out.println("bb");
           
    tardir=new File(list[x].getPath().trim());
    // System.out.println(tardir);
     //
     Vector checkboxes =new Vector();
 JCheckBox jcb=(JCheckBox)jpanellist.add(new JCheckBox());
          
          checkboxes.addElement(jcb); 
          jcb.setText(list[x].getPath().toString());
             //System.out.println("cc");
      }
       }
       else
      {
       chosefile(list[x]);
      }
  
       }
//JOptionPane.showMessageDialog(null,"找到了"+count+"個檔案!");
       }
    
      
      
        
         //
            
        
       
    }
//end 搜尋檔案
//寫入ini檔案
  //寫入整
  private void blockall(Vector a)//定義寫入所有塊函數
  {
   Vector b=new Vector();
     try{
    BufferedWriter mybuff= new BufferedWriter(new FileWriter("FO.ini"));
    System.out.println("size:  "+a.size()); 
  for ( int i=0;i<a.size();i++)
{   try{
  b= (Vector)a.get(i);
  blockwrite(b,mybuff);  //,true
mybuff.write("[...]");
   mybuff.newLine();
}catch(Exception exp){}
}
  mybuff.flush();
  mybuff.close();
}catch(Exception exp){}
}
private void blockwrite(Vector a,BufferedWriter mybuff)//定義塊寫入函數
   { 
   int i;
    String temp;  
   for (i=0;i<=a.size();i++)
   { 
   try{
  
   temp=a.get(i).toString();
   mybuff.write(temp);
   mybuff.newLine();
   }
   catch(Exception exp1){}
   }
}
//寫入檔案
public void write(Vector OldnameToNewname)
{  
    Vector vall= new Vector();//存儲所有塊
    Vector vfo = new Vector();//臨時數組
    String temp,strold;
    int flag=0;
  try{
  BufferedReader mybuffreader =new BufferedReader(new FileReader("FO.ini"));
  
 
   
 
  
  
  temp=mybuffreader.readLine();
if(temp!=null)//如果讀一行不為空
     {  
     strold=temp.substring(0,temp.indexOf("..."));//得到舊檔案名
File path=new File(strold);
if (path.getParent().trim().compareTo(jtpath.getText().trim())==0 )
{
vfo.add(temp);//将temp加入動态數組 vfo
         
        while(true)
        {
       temp=mybuffreader.readLine();
       if(temp==null)//為空就退出
         break;
       else
       {      
       if (temp.compareTo("[...]")!=0)//如果讀到字元串[...]
        { 
         vfo.add(temp);//将temp加入動态數組 vfo
         }        
        else
        {
        vall.add(new Vector(vfo)); //動态增加一個動态數組
        vfo.clear();//将臨時數組清空 
        flag++;//标志位加一
      }      }       }      }
             
       if (flag==10) //如果有十個塊
       vall.remove(0); //清除第一個塊 
           
vall.add(OldnameToNewname);
  }
     else
     {
     vall.add(OldnameToNewname);
     }
     
mybuffreader.close();//關閉
blockall(vall) ; //調用blockall
}
catch(IOException exp){}
}
//end 寫入ini檔案
// 讀出ini檔案進行還原操作。
public void back()
{
Vector vfo=new Vector(); 
Vector vall=new Vector();
String temp;
String strold;
String strnew;
File fold;
File fnew;
    int i;
    int count;
    try{
    BufferedReader myreader =new BufferedReader(new FileReader("FO.ini"));
temp=myreader.readLine();
if(temp==null)//如果檔案為空 
{
JOptionPane.showMessageDialog(null,"不可以再還原了!");
}
else {
//把檔案全部讀入vall,注意上面的temp=myreader.readLine()已經讀取了一行
vfo.add(temp);
while((temp=myreader.readLine())!=null)
{
if(temp.compareTo("[...]")!=0)
  {
         vfo.add(temp);
    }
    else
    {
 vall.add(new Vector(vfo)); //動态增加一個動态數組
               vfo.clear();//清空臨時變量
    }
}
    vfo=(Vector)vall.lastElement();
    count=vfo.size();
    for(int x=0;x<count;x++)
    { 
        temp=vfo.get(x).toString();
     strold=temp.substring(0,temp.indexOf("..."));//得到舊檔案名
        strnew=temp.substring(temp.indexOf("...")+3);//得到新檔案名
      fold=new File(strold);
       fnew=new File(strnew);
       if (fnew.exists())
         fnew.renameTo(fold);
    }  
    
  
    vall.remove(vfo);
        blockall(vall);//将vall寫入FO.ini
        //全部完成重新整理界面
        repaintpanell();
}
}
catch(IOException e)
{}
}
//end讀出檔案進行還原操作。
 //============ Inner Classes below =============//
/************************************************/
/*  Inner Class: AListener                     */
/*                                              */
/************************************************/
private class AListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source == jbchose) jbchose_actionPerformed(e);
else if (source == jbchange) jbchange_actionPerformed(e);
else if (source == jbback) jbback_actionPerformed(e);
            else if(source==jbdel)jbdel_actionPerformed(e);
if (source == jtpath) jtpath_actionPerformed(e);
else if (source == jtname) jtname_actionPerformed(e);
else if (source == jtrename) jtrename_actionPerformed(e);
else if (source == jtreext) jtreext_actionPerformed(e);
else if (source == jtnumber) jtnumber_actionPerformed(e) ;
else if (source == jcbrename) jcbrename_actionPerformed(e) ;
if(source==jcballsel)jcballsel_actionPerformed(e);
   //if(source==jcbresel)jcbresel_actionPerformed(e);
}
}
/************************************************/
/*  Inner Class: WListener                     */
/*                                              */
/************************************************/
private class WListener extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
//
// TODO: Add any code you want implement here,when closing this window
//
//System.exit(0);
}
}
//============================= Testing ================================//
//=                                                                    =//
//= The following main method is just for testing this class you built.=//
//= After testing,you may simply delete it.                            =//
//======================================================================//
public static void main(String[] args)
{
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch (Exception ex)
{
System.out.println("Failed loading L&F: ");
System.out.println(ex);
}
new PLGM();
}
//MyTreeCellRenderer
class MyTreeCellRenderer extends DefaultTreeCellRenderer {
  public MyTreeCellRenderer() {}
  public Component getTreeCellRendererComponent(JTree tree,Object value, boolean sel,boolean expanded,boolean leaf,int row,boolean hasFocus) {super.getTreeCellRendererComponent(tree,value,sel,expanded,leaf,row,hasFocus);
  setIcon(fileSystemView.getSystemIcon(((FileNode)value).getFile()));//得到系統圖示
      return this;
  }
}
//定義一個增加JCheckBoxa的類
class addcheckbox{
 Vector checkboxes =new Vector();
public void addcheckbox(File tardir){
        if (tardir.exists()){
   File[] file=tardir.listFiles();
         if( file!=null && file.length>0)
      {   
         for(int x=0; x<file.length; x++)
        {
          if(!file[x].isDirectory()){
          JCheckBox jcb=(JCheckBox)jpanellist.add(new JCheckBox());
          
          checkboxes.addElement(jcb); 
          jcb.setText(file[x].getPath().toString());
        
        
        }
      }
   }
   }
   
 }
//判斷是否被選擇
public void selected(boolean selected){
for(int i=0;i<jpanellist.getComponentCount();++i)//得到jpanellist中所有元件的數目
{
try{
      JCheckBox tempjcb= (JCheckBox)jpanellist.getComponent(i);//将jpanellist中元件的類型轉換成JCheckBox
        tempjcb.setSelected(selected);
        
  }
  catch(Exception e)
  {
JOptionPane.showMessageDialog(null," 找不到元件! ");
}
}
}
}
//end
}
//end plgm
//定義FileNode
class FileNode extends DefaultMutableTreeNode {
private boolean explored = false, selected = false;
public FileNode(File file) { 
setUserObject(file); 
}
public boolean getAllowsChildren() { return isDirectory(); }//反回是否允許有子節點.是否為目錄
public boolean isLeaf() { return !isDirectory(); }//如果沒有子節點就反回true
public File getFile() { return (File)getUserObject(); }//反回此節點的對象
public void explore() { explore(false); }//展開
public boolean isExplored() { return explored; }//是否展開
public void setSelected(boolean s) { selected = s; }//選擇
public boolean isSelected() { return selected; }//是否被選擇
//定義isDirectory函數檔案是否為目錄
public boolean isDirectory() {
File file = (File)getUserObject();
return file.isDirectory();
}
//定義toString函數
public String toString() {
File file = (File)getUserObject();
String filename = file.toString();
int index = filename.lastIndexOf("\\");
return (index != -1 && index != filename.length()-1)?filename.substring(index+1) : filename;
}
//定義explore函數
public void explore(boolean force) {
if(!isExplored() || force) {
File file = getFile();
File[] children = file.listFiles();//反回此目錄下的所有字子目錄或檔案
for(int i=0; i < children.length; ++i) {
if (children[i].isDirectory())//如果是目錄執行下面的田加語句
add(new FileNode(children[i]));//遞歸增加子目
}
explored = true;
}
}
}
//end            

繼續閱讀