2

I would like to implement a "Find Menu" in my simple notepad application in java but when I find a certain word,It just jumps up to the second similar word in the JTextArea, can anyone point out where I am wrong and how to furnish it? and I dont want to use Highlighter, just the select() method .. I would appreciate any help you can do. Im just new to programming.

/**
 *
 * @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                   
}

That is my code. Im sorry if there are many redundancies because like I've said, im just new to programming. Thank You. -By the way, I am using NetBeans IDE 8.0 -Sorry if it took me time

  • 3
    Consider providing a [runnable example](https://stackoverflow.com/help/mcve) which demonstrates your problem. This will result in less confusion and better responses – MadProgrammer Aug 25 '14 at 03:18
  • Also, is the problem when searching normal text or selected text? Keep the code simple and get the searching for normal text first. Then move on to getting the search for selected text. – camickr Aug 25 '14 at 03:20
  • Also, as [an example](http://stackoverflow.com/questions/13437865/java-scroll-to-specific-text-inside-jtextarea/13438455#13438455) – MadProgrammer Aug 25 '14 at 03:21
  • oh ok sir.. sorry.. give me some time – Edmar Andang Aug 25 '14 at 03:22
  • @camickr when searching normal text sir. – Edmar Andang Aug 25 '14 at 03:37
  • @EdmarAndang, then the `MCVE` should show that code to keep the MCVE simple. – camickr Aug 25 '14 at 03:39
  • @MadProgrammer ignore first my edited post sir.. Please give me some time, Ill just build a demo of what Im really trying to say. – Edmar Andang Aug 25 '14 at 03:40
  • @camickr please give me some time sir , Ill just build a demo of what Im trying to say, I hope you can really help me , as it took me days already to figure this things out. – Edmar Andang Aug 25 '14 at 03:42
  • 1
    @camickr Finished my runnable Find Demo of my problem sir.. I hope you can test it and tell which exactly is my problem.. thank you in advance – Edmar Andang Aug 25 '14 at 04:10
  • @MadProgrammer Finished my runnable Find Demo of my problem sir.. I hope you can test it and tell which exactly is my problem.. thank you in advance – Edmar Andang Aug 25 '14 at 04:11
  • @EdmarAndang: Instead of using `digFind.show()` use `digFind.setVisible(true/false)' for JDK 1.5+, since the former as been deprecated, since that version release. – nIcE cOw Aug 25 '14 at 05:39
  • I appreciate all of your answers. Thanks for your concerns. I have found my own way to get it done and I can move to every word in my text area now. :) – Edmar Andang Aug 25 '14 at 06:32

1 Answers1

2

when I find a certain word,It just jumps up to the second similar word in the JTextArea,

When I try the code, the first time you press "Find" it selects the first occurrence of the word. Then if you press Find again it selects the second occurrence of the word. If you press "Find" again it stays on the second occurrence of the word.

So as I suggested in my comment you need to get rid of your "selection logic" and get the basic search working properly first.

Normally when you do a search you start the search from the caret position. This will allow you to continually press the "Find" button to move on to the next occurrence of the word. This works because when you "select" the found word, the caret is moved to the end of the word, so when you press "Find" the next time the caret postion is set at the end of the word, ready to search for the next word.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Thanks for your answer sir, but I have found my way now to get it done, and it works now.. But still, you have my gratitude :) – Edmar Andang Aug 25 '14 at 06:33