Java关键字搜索工具中的错误

时间:2014-07-08 08:10:29

标签: java docx wordsearch

我修补了包含e.printStackTrace()的代码。选择文件夹并点击查找按钮后,它不显示之前在catch部分中的错误屏幕。但是,当我点击查找按钮时没有任何反应。这是修补后的代码:

 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Main.java
 *
 * Created on Jul 4, 2014, 8:19:21 AM
 */
/**
 *
 * @author Yağız
 */
public class Main extends javax.swing.JFrame {

    Boolean check = true;
    File[] filelist;
    /** Creates new form Main */
    public Main() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        jFrame1 = new javax.swing.JFrame();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();
        label1 = new java.awt.Label();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
        jFrame1.getContentPane().setLayout(jFrame1Layout);
        jFrame1Layout.setHorizontalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jFrame1Layout.setVerticalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jFrame1, org.jdesktop.beansbinding.ELProperty.create("CV Search"), this, org.jdesktop.beansbinding.BeanProperty.create("title"));
        bindingGroup.addBinding(binding);

        label1.setText("Keyword:");

        jButton1.setText("Find");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Select Folder");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 56, Short.MAX_VALUE)
                        .addComponent(jButton1))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(29, 29, 29))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton1))
                .addGap(37, 37, 37))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        //Select Folder Button
        try{
            JFileChooser fc = new JFileChooser();
            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            fc.showOpenDialog(null);
            //File folder = new File(fc.getSelectedFile().getPath());
            //filelist = folder.listFiles();
            //if(fc.getSelectedFile()==null){
            //    check = false;
            //}
            if(fc.getSelectedFile()==null){
                check = false;
            } 
            else 
            {
                File folder = new File(fc.getSelectedFile().getPath());
                filelist = folder.listFiles();
                if( filelist.length == 0 ){
                // dialog: folder is empty
                    check = false;
                }
                else
                {
                    check = true;
                }
             }
        }catch(Exception e){
                    JOptionPane.showMessageDialog(null, "Select a Folder!");
                    e.printStackTrace();
                }

    }                                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        //Find button for finding the word in word documents in the selected folder
        String keyword = jTextField1.getText();
        if (! check ) {
            JOptionPane.showMessageDialog(null, "Select a Folder!");
            return;
        }    
        ArrayList result = new ArrayList();
        try
        {
            for( int i=0; i < filelist.length; i++){
                // maybe also .doc?
                if( filelist[i].getName().endsWith( ".docx" ) ) continue;

                //...
                XWPFDocument input = new XWPFDocument(new FileInputStream(filelist[i]));
                XWPFWordExtractor extract = new XWPFWordExtractor(input);
                Scanner scan = new Scanner(extract.getText());
                while(scan.hasNext())
                {
                    String word = scan.next();
                    if( keyword.equals(word) ) {
                        result.add(filelist[i].getName());
                    break;
                    }
                }
            }
                //...
                if(result.isEmpty()){
                    JOptionPane.showMessageDialog(null,"No match was found!");
                }
                else {
                    StringBuilder sb = new StringBuilder();
                    for( int j = 0; j < result.size(); j++){
                        sb.append( result.get(j) ).append( "\n" );
                    }
                    JOptionPane.showMessageDialog( null, sb.toString() );
                }

            }
         catch(Exception e){
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "No keyword was found!");
        }
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Main().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JFrame jFrame1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JTextField jTextField1;
    private java.awt.Label label1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration                   
}

1 个答案:

答案 0 :(得分:0)

尝试将我的发现修补到代码中:

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {       
//...

fc.showOpenDialog(null);
if(fc.getSelectedFile()==null){
    check = false;
} else {
    File folder = new File(fc.getSelectedFile().getPath());
    filelist = folder.listFiles();
    if( filelist.size() == 0 ){
        // dialog: folder is empty
        check = false;
    } else {
        check = true;
    }
}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    String keyword = jTextField1.getText();
    if (! check ) {
        JOptionPane.showMessageDialog(null, "Select a Folder!");
        return;
    }    
    ArrayList<String> result = new ArrayList<>();
    try
    {
        for( int i=0; i < filelist.length; i++){
            // maybe also .doc?
            if( ! filelist.get( i ).getName().endsWith( ".docx" ) ) continue;

            //...
            String word = scan.next();
            if( keyword.equals(word) ) {
                result.add(filelist[i].getName());
                break;
            }
            //...

         else {
            StringBuilder sb = new StringBuilder();
            for( int i = 0; i < result.size(); i++){
                sb.append( result.get(i) ).append( "\n" );
            }
            JOptionPane.showMessageDialog( null, sb.toString() );

在catch块中添加e.printStackTrace()。