日期:2014-05-20 浏览次数:20851 次
package com.hss.chap13; import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Scanner; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class Chap13_03 { /** * @param args */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable(){ public void run() { ZipFrame zf = new ZipFrame(); zf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); zf.setVisible(true); } }); } } class ZipFrame extends JFrame{ public ZipFrame(){ this.setBounds(200, 200, 500, 400); this.setLayout(new BorderLayout()); //工具栏布局 JMenuBar jmb = new JMenuBar(); JMenu jm = new JMenu("file"); JMenuItem jmi1 = new JMenuItem("open"); JMenuItem jmi2 = new JMenuItem("exit"); jm.add(jmi1); jm.add(jmi2); jmb.add(jm); this.setJMenuBar(jmb); //添加处理事件 jmi1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { JFileChooser jfc = new JFileChooser(); jfc.setCurrentDirectory(new File(".")); int r = jfc.showOpenDialog(ZipFrame.this); if(r==JFileChooser.APPROVE_OPTION){ zipname=jfc.getSelectedFile().getPath(); try { scannerFile(); } catch (IOException e1) { e1.printStackTrace(); } } } }); jmi2.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { System.exit(0); } }); //添加textarea jta = new JTextArea(); jsc = new JScrollPane(jta); //添加combobox fileCombo = new JComboBox(); fileCombo.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { try { loadFile((String)fileCombo.getSelectedItem()); } catch (Exception e1) { e1.printStackTrace(); } } }); this.add(jsc,BorderLayout.CENTER); this.add(fileCombo,BorderLayout.SOUTH); } public void scannerFile() throws IOException{ //先将combox清空 fileCombo.removeAllItems(); ZipInputStream zis = new ZipInputStream(new FileInputStream(zipname)); ZipEntry ze ; while((ze=zis.getNextEntry())!=null){ fileCombo.addItem(ze.getName()); zis.closeEntry(); } zis.close(); } public void loadFile(String filename) throws Exception{ //先将显示区域清空 jta.setText(""); ZipInputStream zis = new ZipInputStream(new FileInputStream(zipname)); ZipEntry ze; while((ze=zis.getNextEntry())!=null){ System.out.println(ze.getName()+"---"+filename); if(ze.getName().equals(filename)){ Scanner in = new Scanner(zis); while(in.hasNextLine()){ String s = in.nextLine(); jta.append(s); jta.append("\n"); } } zis.closeEntry(); } zis.close(); } private String zipname; private JTextArea jta; private JScrollPane jsc; private JComboBox fileCombo; }