java吧 关注:1,259,583贴子:12,756,435

回复:Java 不完全教程

只看楼主收藏回复


}
模拟田径赛跑 – 裁判鸣枪
import java.util.Random;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String[] args) {
final CountDownLatch startLatch = new CountDownLatch(1);
final CountDownLatch endLatch = new CountDownLatch(3);
for (int i = 0; i < 3; i++) {
new Thread(new Runnable() {
public void run() {
try {
startLatch.await();
System.out.println(Thread.currentThread().getName()+" 起跑,冲刺");
Thread.sleep(new Random().nextInt(3000)+1000);
System.out.println(Thread.currentThread().getName()+" 到达终点");
endLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(3000);
System.out.println("裁判,鸣枪开始!");
startLatch.countDown();
endLatch.await();
System.out.println("裁判,比赛结束,宣布结果!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
线程之间交换数据 – 买卖双方约定交易地点交易
import java.util.Random;
import java.util.concurrent.Exchanger;
public class ExchangerDemo {
public static void main(String[] args) {
final Exchanger<String> exchanger = new Exchanger<String>();
new Thread(new Runnable() {
public void run() {
try {
System.out.println("买家拿钱出发");
Thread.sleep(new Random().nextInt(5000)+1000);
System.out.println("买家到达交易地点,等待卖家");
System.out.println("买家拿到了"+exchanger.exchange("钱"));
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
try {
System.out.println("卖家拿货出发");
Thread.sleep(new Random().nextInt(5000)+1000);
System.out.println("卖家到达交易地点,等待买家");
System.out.println("卖家拿到了"+exchanger.exchange("货"));
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}


IP属地:北京23楼2013-03-01 08:53
回复

    第七章 常用类
    Object类
    finalize()
    垃圾回收器
    toString()
    返回该对象字符串表示
    equals(obj)
    比较两个对象是否相等
    System类
    gc()
    运行垃圾回收器
    currentTimeMillis()
    返回当前时间(毫秒)
    arraycopy(s,sP,d,dP,l)
    源数组复制到另一个数组
    getProperties()
    获取系统属性
    Thread类
    currentThread()
    当前线程
    getName()
    获取名称
    setName(name)
    设置名称
    sleep(millis)
    等待线程
    setDaemon(on)
    守护线程
    join()
    加入线程
    Math类
    PI
    圆周率
    abs(a)
    绝对值
    max(a, b)
    比较最大值
    min(a, b)
    比较最小值
    pow(a, b)
    n次幂
    sqrt(a)
    求平方根
    cbrt(a)
    求立方根
    floor(a)
    向下取整
    ceil(a)
    向上取整
    round(a)
    最接近的整数
    random()
    随机值
    String类
    getBytes()
    转换字节数组
    charAt(index)
    获取下标上的字符
    compareTo(obj)
    比较字符串
    endsWith(s)
    结尾是否包含
    replace(a, b)
    替换字符串
    contains(s)
    是否包含
    startsWith(p)
    开头是否包含
    concat(str)
    连接字符串
    indexOf(ch)
    出现的下标位置
    length()
    字符串长度
    split(regex)
    正则拆分
    substring(int)
    切割字符串
    toCharArray()
    转换为字符数组
    toLowerCase()
    转换为小写
    toUpperCase()
    转换为小写
    trim()
    忽略空格
    StringBuffer类
    append(obj)
    追加
    insert(offset, obj)
    插入
    reverse()
    反转字符串
    delete(start, end)
    删除
    Collection接口 -> ArrayList -> Vector -> LinkedList -> HashSet -> TreeSet
    add(obj)
    添加元素
    size()
    元素数量
    get(index)
    获取元素
    clear()
    清空所有元素
    remove(obj)
    删除指定元素
    iterator()
    **迭代
    Map接口 -> HashMap -> Hashtable
    put(key,value)
    添加元素
    get(key)
    根据键返回值
    keySet()
    返回所有的键
    entrySet()
    返回键值对
    values()
    返回所有的值
    Arrays类
    sort(obj[])
    排序
    binarySearch(obj[],key)
    二分查找
    copyOf(obj[],Leng)
    拷贝并创建一个新长度数组
    copyOfRange(obj[],s,e)
    拷贝截取创建新的数组
    fill(obj[],val)
    填充数组
    asList(T..)
    数组转成list
    Collections类
    sort(list)
    排序
    inarySearch(list,key)
    二分查找
    swap(list,i,j)
    交换**中的元素
    synchronizedCollection
    使**线程安全
    BigDecimal类
    add(augend)
    加法/减法
    remainder(divisor)
    取模
    multiply(multiplicand)
    乘法
    divide(divisor)
    除法
    File类
    exists()
    判断文件是否存在
    createNewFile()
    创建新文件
    getParentFile()
    获得文件所在的目录
    mkdirs()
    创建目录
    getAbsoluteFile()
    获取文件绝对路径
    getPath()
    获得文件参数路径
    getName()
    获得文件/文件夹名称
    isDirectory()
    判断路径是否是目录
    isFile()
    判断路径是否是文件
    lastModified()
    返回文件最后修改时间
    listFiles()
    列出所有文件
    delete()
    删除文件
    第八章 Eclipse and MyEclipse


    IP属地:北京25楼2013-03-01 08:54
    回复
      2025-05-15 07:55:01
      广告

      第八章 Eclipse and MyEclipse
      显示视图
      Window -> Show View -> Console || Package Explorer
      创建项目
      File -> New -> Java Project
      打开项目
      src -> Class -> Package || Name -> Finish
      修改字体
      Windows 7 -> 控制面板 -> 外观和个性化 -> 字体 -> Courier New -> 常规 -> 显示
        Preferences -> General -> Appearance -> Colors and Fonts -> Basic -> Text Font -> Courier New
      导入项目
      File -> Import -> Existing Projects into Workspace -> Browse || Copy projects into workspace -> Finish
      快捷方式
      Ctrl+1
      代码错误解决
      Ctrl+2,L
      代码返回值自动补全
      Alt+/
      代码自动补全
      Ctrl+Shift+O
      自动导入相关包
      Alt+↓
      选择代码下移
      Ctrl+Alt+↓
      复制选择行
      Ctrl+D
      删除选择行
      Ctrl+Alt+Enter
      插入空行
      Ctrl+/
      单行注释
      Ctrl+Alt+/,\
      多行注释,取消多行注释
      Ctrl+Shift+F
      格式化代码
      Ctrl+F11
      运行程序
      Shift+Alt+C,O,S,R,V
      自动生成代码
      Shift+Alt+Z
      环绕代码
      Shift+Alt+R
      重构代码
      Shift+Alt+M
      抽取方法
      Shift+Alt+L
      抽取变量
      F3
      查看源代码
      优化程序
      关闭启动项
      Window -> Preferences -> General -> Startup and Shutdown
      þ Aptana Core
      þ MyEclipse QuickSetup
      þ MyEclipse EASIE Tomcat 6
      þ MyEclipse Memory Monitor
      þ MyEclipse Tapestry Integration
      þ MyEclipse JSP Debug Tooling
      þ MyEclipse File Creation Wizards
      þ MyEclipse Backward Compatibility
      þ MyEclipse Perspective Plug-in
      关闭自动验证
      Windows -> Perferences -> Myeclipse -> Validation -> Build
      关闭拼写检查
      Windows -> Perferences -> General -> Editors -> Text Editors -> Spelling -> Enable spell checking
      默认Jsp编辑
      Window -> perferences -> General -> Editors -> File Associations -> *.jsp -> MyEclipse JSP Editor
      Java自动补全
      Windows -> Perferences -> Java -> Editor -> Content Assist -> Auto activation triggers for Java
      XML打开错误
      Window -> perferences -> General -> Editors -> File Associations -> *.xml -> MyEclipse XML Editor
      Build.xml编译错误
      项目 -> Perferences -> Builders -> Error -> Remove
      更改快捷键
      Window -> perferences -> General -> Keys -> Content Assist ->  Alt+/
      Window -> perferences -> General -> Keys -> Word Completion ->  Ctrl+Alt+/
      禁止Maven更新
      Windows -> Perferences -> Myeclipse -> Maven4Myeclipse -> Maven -> Download repository index updates on startup
      更改非堆内存 - eclipse.ini
      -XX:PermSize=512M -XX:MaxPermSize=512M
      关闭在线API
      项目 -> Perferences -> Java Build Path -> Libraries -> JRE System Library -> rt.jar -> Javadoc location -> Remove
      设置虚拟机的版本
      Window -> Perferences -> Java -> Compiler -> 6.0
      设置工程编译环境
      项目 -> Perferences -> Java Build Path -> Libraries
      设置JRE环境
      Window -> Perferences -> Java -> Installed JREs -> Add -> Next -> Directory -> Finish
      设置Tomcat编译环境
      Windows -> Perferences -> Myeclipse -> Servers -> Tomcat -> Tomcat 6.x -> JDK


      IP属地:北京26楼2013-03-01 08:54
      回复

        第九章 字符串和时间
        获取文件扩展名
        public static void main(String[] args) {
        String str = "文件.txt";
        String[] suffix = str.split("\\.");
        str = suffix[suffix.length-1];
        System.out.println(str);
        }
        查找字符串出现的位置
        private static void findAll(String a,String b) {
        int index = 0;
        while(true) {
        int find = a.indexOf(b,index);
        if (find==-1) {
        break;
        }
        System.out.println(find);
        index = find+1;
        }
        }
        判断数组中指定位置上的字节是否是中文的前一半
        private static boolean isCnBegin(byte[] arr,int index) {
        boolean flag = false;
        for (int i=0;i<=index;i++){
        flag=!flag&&arr[i]<0;
        }
        return flag;
        }
        时间
        import java.text.DateFormat;
        import java.text.SimpleDateFormat;
        import java.util.Calendar;
        import java.util.Date;
        public class dateDemo {
        public static void main(String[] args) throws Exception {
        Date date = new Date();
        //格式化时间
        String pattern = "yyyy-MM-dd HH:mm:ss";
        DateFormat sdf = new SimpleDateFormat(pattern);
        String str = sdf.format(date);
        System.out.println(str);
        date = sdf.parse(str);
        //判断2月有多少天
        Calendar c = Calendar.getInstance();
        c.set(2013, 2, 1);
        c.add(c.DAY_OF_YEAR, -1);
        System.out.println(c.get(c.DAY_OF_MONTH));
        //重现开始往后100天排除周末周日
        c.setTime(new Date());
        for (int i = 1; i <= 100; i++) {
        int week = c.get(c.DAY_OF_WEEK);
        if(week==1||week==7) {
        i--;
        }
        c.add(c.DAY_OF_YEAR, 1);
        }
        System.out.println(c.get(c.DAY_OF_YEAR)-Calendar.getInstance().get(c.DAY_OF_YEAR));
        //打印时间
        System.out.println(c.get(c.YEAR)+
        "-"+(c.get(c.MONTH)+1)+
        "-"+c.get(c.DAY_OF_MONTH)+
        " "+c.get(c.HOUR_OF_DAY)+
        ":"+c.get(c.MINUTE)+
        ":"+c.get(c.SECOND));
        }
        }


        IP属地:北京27楼2013-03-01 08:54
        回复

          第十章 **
          ArrayList<String> arrayList = new ArrayList<String>();
          Vector vector = new Vector();
          LinkedList linkedList = new LinkedList();
          HashSet hashSet = new HashSet();
          TreeSet treeSet = new TreeSet();
          LinkedHashSet linkedHashSet = new LinkedHashSet();
          HashMap hashMap = new HashMap();
          TreeMap treeMap = new TreeMap();
          Hashtable hashtable = new Hashtable();
          LinkedHashMap linkedHashMap = new LinkedHashMap();
          Properties properties = new Properties();
          equals() //比较对象是否相等
          hashCode() //比较hashCode相等
          compareTo() //对象进行排序
          自定义带泛型**类
          public class MyCollection<T> {
          private int len = 10;
          private int pos = 0;
          private Object[] t = new Object[len];
          public void add(T obj) {
          if (pos==len) {
          this.len+=10;
          T[] newT = (T[]) new Object[this.len];
          for (int i = 0; i < t.length; i++) {
          newT[i] = (T) t[i];
          }
          this.t = newT;
          }
          t[pos++] = obj;
          }
          public T get(int index) {
          return (T) this.t[index];
          }
          public int size(){
          return pos;
          }
          }
          **出列游戏
          import java.util.Iterator;
          import java.util.LinkedList;
          public class Game {
          public static void main(String[] args) {
          LinkedList<String> boys = new LinkedList<String>();
          boys.add("张三");
          boys.add("李四");
          boys.add("王五");
          boys.add("赵六");
          boys.add("孙七");
          int count = 0;
          Iterator iterator = boys.iterator();
          while (boys.size()>1) {
          count++;
          String boy = (String)iterator.next();
          if (count==3) {
          System.out.println("出列是:"+boy);
          iterator.remove();
          count = 0;
          }
          if (!iterator.hasNext()) {
          iterator = boys.iterator();
          }
          }
          System.out.println("幸运者:"+boys.get(0));
          }
          }
          统计字符串中字符出现的次数
          import java.util.Comparator;
          import java.util.HashMap;
          import java.util.Iterator;
          import java.util.Map.Entry;
          import java.util.Set;
          import java.util.TreeSet;
          public class CountCharNum {
          public static void main(String[] args) {
          String str = "absadsadlihsaodlsa";
          HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();
          char[] chars = str.toCharArray();
          for (char c : chars) {
          if (hashMap.containsKey(c)) {
          hashMap.put(c, hashMap.get(c)+1);
          }else{
          hashMap.put(c, 1);
          }
          }
          TreeSet treeSet = new TreeSet(new Comparator<Entry<Character, Integer>>(){
          public int compare(Entry<Character, Integer> o1, Entry<Character, Integer> o2) {
          Character c1 = o1.getKey();
          Character c2 = o2.getKey();
          Integer v1 = o1.getValue();
          Integer v2 = o2.getValue();
          Integer num = v1-v2;
          return num!=0?num:c1-c2;
          }
          });
          Set entrySet = hashMap.entrySet();
          Iterator iterator = entrySet.iterator();
          while (iterator.hasNext()) {
          Entry entry = (Entry) iterator.next();
          treeSet.add(entry);
          }
          System.out.println(treeSet);
          }
          }


          IP属地:北京28楼2013-03-01 08:55
          回复

            复制.java文件并重新替换后缀名
            import java.io.File;
            import java.io.FileInputStream;
            import java.io.FileOutputStream;
            import java.io.InputStream;
            import java.io.OutputStream;
            public class FileInputStreamDemo {
            public static void main(String[] args) throws Exception {
            File dir = new File("d:\\");
            listAllJavaFiles(dir);
            }
            private static void listAllJavaFiles(File dir) throws Exception {
            File[] files = dir.listFiles();
            if (files!=null) {
            for (File file : files) {
            if (file.isDirectory()) {
            listAllJavaFiles(file);
            } else if (file.getName().endsWith(".java")) {
            copyFile(file);
            }
            }
            }
            }
            private static void copyFile(File file) throws Exception {
            File target = new File("c:\\jad",file.getName().replaceAll("\\.java$", ".jad"));
            InputStream in = new FileInputStream(file);
            OutputStream out = new FileOutputStream(target);
            byte[] buffer = new byte[1024];
            int len;
            while ((len=in.read(buffer))!=-1) {
            out.write(buffer, 0, len);
            }
            in.close();
            out.close();
            }
            }
            显示目录树形图
            import java.io.File;
            public class DiskTree {
            private static File root;
            public static void main(String[] args) {
            File dir = new File(".");
            root = dir;
            listAllFile(dir);
            }
            private static void listAllFile(File dir) {
            System.out.println(getSpace(dir)+dir.getName());
            if(dir.isDirectory()){
            File[] files = dir.listFiles();
            if(files==null) return;
            for (File file : files) {
            listAllFile(file);
            }
            }
            }
            private static String getSpace(File file) {
            if(file.equals(root)) return "";
            String space = getParentSpace(file.getParentFile());
            if(isLastSubFile(file)) {
            space += "└——";
            }else{
            space += "├——";
            }
            return space;
            }
            private static String getParentSpace(File parentFile) {
            if(parentFile.equals(root)) return "";
            String space = getParentSpace(parentFile.getParentFile());
            if(isLastSubFile(parentFile)){
            space += "    ";
            }else{
            space += "│   ";
            }
            return space;
            }
            private static boolean isLastSubFile(File file) {
            File[] files = file.getParentFile().listFiles();
            if(file.equals(files[files.length-1])){
            return true;
            }
            return false;
            }
            }
            图片分割
            import java.io.File;
            import java.io.FileInputStream;
            import java.io.FileOutputStream;
            import java.io.InputStream;
            import java.io.OutputStream;
            public class SplitImage {
            public static void main(String[] args) throws Exception {
            File file = new File("a.jpg");
            cutFile(file);
            }
            private static void cutFile(File file) throws Exception {
            int num = 1;
            InputStream in = new FileInputStream(file);
            OutputStream out = new FileOutputStream(new File("jpg/a" + num + ".jpg"));
            byte[] buffer = new byte[1024];
            int len;
            int count = 0;
            while ((len = in.read(buffer)) != -1) {
            if (count == 100) {
            out.close();
            out = new FileOutputStream(new File("jpg/a" + ++num + "jpg"));
            count = 0;
            }
            out.write(buffer, 0, len);
            count++;
            }
            in.close();
            out.close();
            }
            }


            IP属地:北京30楼2013-03-01 08:58
            回复
              要 要 (切克闹)


              IP属地:山东31楼2013-03-01 08:58
              回复

                缓冲流 - 比自定义缓冲数组效率低
                import java.io.BufferedInputStream;
                import java.io.BufferedOutputStream;
                import java.io.FileInputStream;
                import java.io.FileOutputStream;
                import java.io.InputStream;
                import java.io.OutputStream;
                public class BufferedStreamTest {
                public static void main(String[] args) throws Exception {
                InputStream bis = new BufferedInputStream(new FileInputStream("a.jpg"));
                OutputStream bos = new BufferedOutputStream(new FileOutputStream("b.jpg"));
                int ch;
                while ((ch=bis.read())!=-1) {
                bos.write(ch);
                }
                bis.close();
                bos.close();
                }
                }
                序列流 - 用于合并文件
                import java.io.FileInputStream;
                import java.io.FileOutputStream;
                import java.io.InputStream;
                import java.io.OutputStream;
                import java.io.SequenceInputStream;
                public class SequenceInputStreamTest {
                public static void main(String[] args) throws Exception {
                InputStream in1 = new FileInputStream("a.txt");
                InputStream in2 = new FileInputStream("b.txt");
                InputStream in = new SequenceInputStream(in1, in2);
                OutputStream out = new FileOutputStream("c.txt");
                byte[] buffer = new byte[1024];
                int len;
                while ((len=in.read(buffer))!=-1) {
                out.write(buffer, 0, len);
                }
                in.close();
                out.close();
                }
                }
                合并图片
                import java.io.FileInputStream;
                import java.io.FileOutputStream;
                import java.io.InputStream;
                import java.io.OutputStream;
                import java.io.SequenceInputStream;
                import java.util.ArrayList;
                import java.util.Enumeration;
                import java.util.Iterator;
                import java.util.List;
                public class WithPicture {
                public static void main(String[] args) throws Exception {
                List<InputStream> inList = new ArrayList<InputStream>();
                for (int i = 1; i <= 5; i++) {
                inList.add(new FileInputStream("gif/a"+i+".gif"));
                }
                final Iterator<InputStream> it = inList.iterator();
                InputStream in = new SequenceInputStream(new Enumeration<InputStream>() {
                public boolean hasMoreElements() {
                return it.hasNext();
                }
                public InputStream nextElement() {
                return it.next();
                }


                IP属地:北京32楼2013-03-01 09:00
                回复
                  2025-05-15 07:49:01
                  广告
                  });
                  OutputStream out = new FileOutputStream("b.gif");
                  byte[] buffer = new byte[1024];
                  int len;
                  while ((len=in.read(buffer))!=-1) {
                  out.write(buffer, 0, len);
                  }
                  in.close();
                  out.close();
                  }
                  }
                  对象序列化流 - 对象序列号和反序列化
                  import java.io.FileInputStream;
                  import java.io.FileOutputStream;
                  import java.io.ObjectInputStream;
                  import java.io.ObjectOutputStream;
                  public class ObjectStreamTest {
                  public static void main(String[] args) throws Exception {
                  ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("a.txt"));
                  out.writeObject("aaa");
                  out.close();
                  ObjectInputStream in = new ObjectInputStream(new FileInputStream("a.txt"));
                  System.out.println(in.readObject());
                  in.close();
                  }
                  }
                  字节数组流 - 读取内存字节数组
                  import java.io.ByteArrayInputStream;
                  import java.io.ByteArrayOutputStream;
                  import java.util.Arrays;
                  public class ObjectStreamTest {
                  public static void main(String[] args) throws Exception {
                  byte[] buffer = {1,2,3,4};
                  ByteArrayInputStream bain = new ByteArrayInputStream(buffer);
                  int ch;
                  while ((ch=bain.read())!=-1) {
                  System.out.println(ch);
                  }
                  ByteArrayOutputStream baout = new ByteArrayOutputStream();
                  baout.write("hello".getBytes());
                  baout.close();
                  System.out.println(Arrays.toString(baout.toByteArray()));
                  }
                  }


                  IP属地:北京33楼2013-03-01 09:00
                  回复

                    第十二章 GUI
                    简单GUI例子 - 添加删除按钮
                    import java.awt.Button;
                    import java.awt.FlowLayout;
                    import java.awt.Frame;
                    import java.awt.event.MouseAdapter;
                    import java.awt.event.MouseEvent;
                    import java.awt.event.WindowAdapter;
                    import java.awt.event.WindowEvent;
                    public class EasyGUI {
                    public static void main(String[] args) {
                    Frame frame = new Frame("标题");
                    frame.setSize(800, 600);
                    frame.setLocation(300, 100);
                    frame.setLayout(new FlowLayout());
                    Button btn = new Button("按钮");
                    frame.add(btn);
                    frame.setVisible(true);
                    frame.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                    e.getWindow().dispose();
                    }
                    });
                    btn.addMouseListener(new MouseAdapter() {
                    public void mouseClicked(MouseEvent e) {
                    Frame frame = (Frame) e.getComponent().getParent();
                    Button newBtn = new Button("按钮");
                    frame.add(newBtn);
                    frame.setVisible(true);
                    newBtn.addMouseListener(new MouseAdapter() {
                    public void mouseClicked(MouseEvent e) {
                    Button btn = (Button) e.getComponent();
                    btn.getParent().remove(btn);
                    }
                    });
                    }
                    });
                    }
                    }


                    IP属地:北京36楼2013-03-01 09:03
                    回复

                      资源管理器
                      import java.awt.BorderLayout;
                      import java.awt.Button;
                      import java.awt.Frame;
                      import java.awt.List;
                      import java.awt.Panel;
                      import java.awt.TextField;
                      import java.awt.event.ActionEvent;
                      import java.awt.event.ActionListener;
                      import java.awt.event.WindowAdapter;
                      import java.awt.event.WindowEvent;
                      import java.io.File;
                      import java.io.IOException;
                      public class Explorer {
                      private static TextField input = new TextField(20);
                      private static Button go = new Button("转到");
                      private static Button back = new Button("后退");
                      private static List display = new List();
                      private static class MyWindow extends Frame {
                      public MyWindow(){
                      this.setSize(800,600);
                      this.setLocation(300, 100);
                      this.setTitle("资源管理器");
                      this.setVisible(true);
                      Panel p = new Panel();
                      p.add(back);
                      p.add(input);
                      p.add(go);
                      this.add(p, BorderLayout.NORTH);
                      this.add(display, BorderLayout.CENTER);
                      handleEvent();
                      }
                      private void handleEvent() {
                      this.addWindowListener(new WindowAdapter() {
                      public void windowClosing(WindowEvent e) {
                      closeWindow();
                      }
                      });
                      go.addActionListener(new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                      openFiles();
                      }
                      });
                      input.addActionListener(new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                      openFiles();
                      }
                      });
                      display.addActionListener(new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                      clickItem();
                      }
                      private void clickItem() {
                      String dir = input.getText();
                      String fileName = display.getSelectedItem();
                      if (dir==null||fileName==null) return;
                      File file = new File(dir,fileName);
                      if (file.isDirectory()) {
                      input.setText(file.getAbsolutePath());
                      openFiles();
                      } else {
                      try {
                      Runtime.getRuntime().exec("cmd /c "+file.getAbsolutePath());
                      } catch (IOException e) {
                      e.printStackTrace();
                      }
                      }
                      }
                      });
                      back.addActionListener(new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                      back();
                      }
                      private void back() {
                      String data = input.getText();
                      if(data=="") return;
                      File file = new File(input.getText());
                      File parentFile = file.getParentFile();
                      if(parentFile==null) return;
                      input.setText(parentFile.getAbsolutePath());
                      openFiles();
                      }
                      });
                      }
                      private void closeWindow() {
                      this.dispose();
                      }
                      private void openFiles() {
                      String data = input.getText();
                      File file = new File(data);
                      if(!file.isDirectory()) return;
                      display.removeAll();
                      File[] files = file.listFiles();
                      for (File f : files) {
                      display.add(f.getName());
                      }
                      }
                      }
                      public static void main(String[] args) {
                      MyWindow myWindow = new MyWindow();
                      }
                      }


                      IP属地:北京40楼2013-03-01 09:12
                      回复
                        噢~~好贴


                        41楼2013-03-01 09:12
                        回复