我想实现一个"查找菜单"在我在Java中的简单记事本应用程序中

时间:2014-08-25 03:13:16

标签: java swing find indexof

我想实现一个"查找菜单"在我在java中的简单记事本应用程序中但是当我找到某个单词时,它只是跳到JTextArea中的第二个相似单词,任何人都可以指出我错在哪里以及如何提供它?我不想使用荧光笔,只需使用select()方法..我将不胜感激任何帮助。我刚刚开始编程。

/**
 *
 * @author aLwAyz
 */
 public class FindDemo extends javax.swing.JDialog {

/**
 * Creates new form FindDemo
 */
public FindDemo(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    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() {

    dlgFind = new javax.swing.JDialog();
    btnFind = new javax.swing.JButton();
    txtInput = new javax.swing.JTextField();
    jScrollPane1 = new javax.swing.JScrollPane();
    txaField = new javax.swing.JTextArea();
    btnOpenFindDialog = new javax.swing.JButton();

    dlgFind.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

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

    txtInput.setMinimumSize(new java.awt.Dimension(400, 100));

    javax.swing.GroupLayout dlgFindLayout = new javax.swing.GroupLayout(dlgFind.getContentPane());
    dlgFind.getContentPane().setLayout(dlgFindLayout);
    dlgFindLayout.setHorizontalGroup(
        dlgFindLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, dlgFindLayout.createSequentialGroup()
            .addContainerGap(77, Short.MAX_VALUE)
            .addComponent(txtInput, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(63, 63, 63)
            .addComponent(btnFind)
            .addGap(96, 96, 96))
    );
    dlgFindLayout.setVerticalGroup(
        dlgFindLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(dlgFindLayout.createSequentialGroup()
            .addGap(27, 27, 27)
            .addGroup(dlgFindLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(btnFind)
                .addComponent(txtInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addContainerGap(28, Short.MAX_VALUE))
    );

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setModalExclusionType(null);
    setModalityType(null);

    txaField.setColumns(20);
    txaField.setRows(5);
    jScrollPane1.setViewportView(txaField);

    btnOpenFindDialog.setText("Find");
    btnOpenFindDialog.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnOpenFindDialogActionPerformed(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()
            .addContainerGap()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
            .addContainerGap())
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(btnOpenFindDialog)
            .addGap(72, 72, 72))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(22, 22, 22)
            .addComponent(btnOpenFindDialog)
            .addGap(35, 35, 35)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)
            .addContainerGap())
    );

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

private void btnOpenFindDialogActionPerformed(java.awt.event.ActionEvent evt) {                                                  
    // TODO add your handling code here:
   dlgFind.pack();
   dlgFind.setLocationRelativeTo(null);
   dlgFind.show();
}                                                 

private void btnFindActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
    String text = txtInput.getText();
   String txa = txaField.getText();
   int length = text.length();
   String selected = txaField.getSelectedText();
   int selIn = 0;
   if (txaField.getSelectedText() != null) selIn = txa.indexOf(selected);
   int inSelected = selIn + length;
   if (txaField.getSelectedText() == null) inSelected = 0;
   int index = txa.indexOf(text, inSelected);

   if (txa.contains(text)) {
       txaField.select(index, index + length);          
   }   
}                                       

/**
 * @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(FindDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(FindDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(FindDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(FindDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the dialog */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            FindDemo dialog = new FindDemo(new javax.swing.JFrame(), true);
            dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                @Override
                public void windowClosing(java.awt.event.WindowEvent e) {
                    System.exit(0);
                }
            });
            dialog.setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton btnFind;
private javax.swing.JButton btnOpenFindDialog;
private javax.swing.JDialog dlgFind;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea txaField;
private javax.swing.JTextField txtInput;
// End of variables declaration                   
}

这是我的代码。对不起,如果有很多裁员,因为像我所说的那样,我只是编程的新手。谢谢。 - 顺便说一句,我使用的是NetBeans IDE 8.0 - 如果花了我一些时间,请小心

1 个答案:

答案 0 :(得分:2)

  

当我找到某个单词时,它只是跳到JTextArea中的第二个相似单词,

当我尝试代码时,第一次按“查找”时,它会选择第一次出现的单词。然后,如果再次按“查找”,则会选择该单词的第二次出现。如果再次按“查找”,它将保留在第二次出现的单词上。

正如我在评论中建议的那样,你需要摆脱你的“选择逻辑”,并首先使基本搜索正常工作。

通常,当您进行搜索时,您将从插入符号位置开始搜索。这将允许您不断按“查找”按钮继续下一个单词的出现。这是有效的,因为当您“选择”找到的单词时,插入符将移动到单词的末尾,因此当您按下“查找”时,下次在单词的末尾设置插入符号位置时,准备搜索下一个字。