Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2003-2007 the original author or authors.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package groovy.ui.text;
 
 
 
 
 
 

Author(s):
Evan "Hippy" Slatis
 
 public final class FindReplaceUtility {
     
     public static final String FIND_ACTION_COMMAND = "Find";
     
     public static final String REPLACE_ACTION_COMMAND = "Replace";
     
     public static final String REPLACE_ALL_ACTION_COMMAND = "Replace All";
     
     public static final String CLOSE_ACTION_COMMAND = "Close";
     
     public static final Action FIND_ACTION = new FindAction();
     
     private static final JDialog FIND_REPLACE_DIALOG = new JDialog();
         
     private static final JPanel TEXT_FIELD_PANEL = new JPanel(new GridLayout(2, 1));
         
     private static final JPanel ENTRY_PANEL = new JPanel();
     
     private static final JPanel FIND_PANEL = new JPanel();
     private static final JLabel FIND_LABEL = new JLabel("Find What:    ");
     private static final JComboBox FIND_FIELD = new JComboBox();
     
     private static final JPanel REPLACE_PANEL = new JPanel();
     private static final JLabel REPLACE_LABEL = new JLabel("Replace With:");
     private static final JComboBox REPLACE_FIELD = new JComboBox();
 
     private static final JPanel BUTTON_PANEL = new JPanel();
     private static final JButton FIND_BUTTON = new JButton();
     private static final JButton REPLACE_BUTTON = new JButton();
     private static final JButton REPLACE_ALL_BUTTON = new JButton();
     private static final JButton CLOSE_BUTTON = new JButton();
     
     private static final Action CLOSE_ACTION = new CloseAction();
     private static final Action REPLACE_ACTION = new ReplaceAction();
 
     private static final JPanel CHECK_BOX_PANEL = new JPanel(new GridLayout(3, 1));
     private static final JCheckBox MATCH_CASE_CHECKBOX = new JCheckBox("Match Case      ");
     private static final JCheckBox IS_BACKWARDS_CHECKBOX = new JCheckBox("Search Backwards");
     private static final JCheckBox WRAP_SEARCH_CHECKBOX = new JCheckBox("Wrap Search     ");
     
     private static JTextComponent textComponent;
     private static AttributeSet attributeSet;
    
    private static int findReplaceCount;
    private static String lastAction;
    
    private static final EventListenerList EVENT_LISTENER_LIST = new EventListenerList();
    
    // the document segment
    private static final Segment SEGMENT = new Segment();
 
    private static final FocusAdapter TEXT_FOCUS_LISTENER = new FocusAdapter() {
        public void focusGained(FocusEvent fe) {
             = (JTextComponent)fe.getSource();
             =
                .getDocument().getDefaultRootElement().getAttributes();
        }
    };
    static {
        .setResizable(false);
        // is next line needed at all?
        /* KeyStroke keyStroke = */ KeyStroke.getKeyStroke("enter");
        KeyAdapter keyAdapter = new KeyAdapter() {            
            public void keyTyped(KeyEvent ke) {
                if (ke.getKeyChar() == .) {
                    .doClick();
                }
            }
        };
        .add();
        .add();
        .addItem("");
        .setEditable(true);
        .getEditor().getEditorComponent().addKeyListener(keyAdapter);
        Dimension d = .getPreferredSize();
        d.width = 225;
        .setPreferredSize(d);
        
        .setEditable(true);
        
        
        
        
                
        d = .getPreferredSize();
        
        .setPreferredSize(d);
        JPanel panel = new JPanel();
        panel.add();
        .add(panel);
        
        panel = new JPanel();
        panel.add();
        .add(panel);
        
        panel = new JPanel();
        panel.add();
        .add(panel);
        
        .setPreferredSize(d);
        panel = new JPanel();
        panel.add();
        .add(panel);
        
        JRootPane rPane = .getRootPane();
        rPane.getInputMap(.).put(stroke"exit");
        rPane.getActionMap().put("exit");
    }
    // Singleton
    private FindReplaceUtility() {
    }
    
    public static void addTextListener(TextListener tl) {
        .add(TextListener.classtl);
    }
    
    private static void fireTextEvent() {
        EventListener[] lstrs =
            .getListeners(TextListener.class);
        if (lstrs != null && lstrs.length > 0) {
            TextEvent te =
                new TextEvent(.);
            for (int i = 0; i < lstrs.lengthi++) {
                ((TextListener)lstrs[i]).textValueChanged(te);
            }
        }
    }
    
    

Returns:
the last action
    
    public static String getLastAction() {
        return ;
    }
    
    

Returns:
the replacement count
    
    public static int getReplacementCount() {
        return ;
    }
    
    

Returns:
the search text
    
    public static String getSearchText() {
        return (String.getSelectedItem();
    }
    
    

Parameters:
textComponent the text component to listen to
    
    public static void registerTextComponent(JTextComponent textComponent) {
        textComponent.addFocusListener();
    }
    
    public static void removeTextListener(TextListener tl) {
        .remove(TextListener.classtl);
    }
    
    
Find and select the next searchable matching text.

Parameters:
reverse look forwards or backwards
pos the starting index to start finding from
Returns:
the location of the next selected, or -1 if not found
    private static int findNext(boolean reverseint pos) {
        boolean backwards = .isSelected();
        backwards = backwards ? !reverse : reverse;
        
        String pattern = (String.getSelectedItem();
        if (pattern != null && pattern.length() > 0) {
            try {
                Document doc = .getDocument();
                doc.getText(0, doc.getLength(), );
            }
            catch (Exception e) {
                // should NEVER reach here
                e.printStackTrace();
            }
            pos += .getSelectedText() == null ? 
                (backwards ? -1 : 1) : 0;
            char first = backwards ?
                pattern.charAt(pattern.length() - 1) : pattern.charAt(0);
            char oppFirst = Character.isUpperCase(first) ? 
                Character.toLowerCase(first) : Character.toUpperCase(first);
            int start = pos;
            boolean wrapped = .isSelected();
            int end = backwards ? 0 : .getEndIndex();
            pos += backwards ? -1 : 1;
            
        	int length = .getDocument().getLength();
        	if (pos > length) {
        		pos = wrapped ? 0 : length;
        	}
            
            boolean found = false;
            while (!found && (backwards ? pos > end : pos < end)) {
                found = !.isSelected() && .[pos] == oppFirst;
                found = found ? found : .[pos] == first;
                
                if (found) {
                    pos += backwards ? -(pattern.length() - 1) : 0;
                    for (int i = 0; found && i < pattern.length(); i++) {
                        char c = pattern.charAt(i);
                        found =  .[pos + i] == c;
                        if (!.isSelected() && !found) {
                            c = Character.isUpperCase(c) ? 
                                Character.toLowerCase(c) :
                                Character.toUpperCase(c);
                            found =  .[pos + i] == c;
                        }
                    }
                }
                
                if (!found) {
                    pos += backwards ? -1 : 1;
                    if (pos == end && wrapped) {
                        pos = backwards ? .getEndIndex() : 0;
                        end = start;
                        wrapped = false;
                    }
                }
            }
            pos = found ? pos : -1;
        }
        
        return pos;
    }
    
    private static void setListStrings() {
        Object findObject = .getSelectedItem();
        Object replaceObject = .isShowing() ?
            (String.getSelectedItem() : "";
            
        if (findObject != null && replaceObject != null) {
            boolean found = false;
            for (int i = 0; !found && i < .getItemCount(); i++) {
                found = .getItemAt(i).equals(findObject);
            }
            if (!found) {
                .insertItemAt(findObject, 0);
                if (.getItemCount() > 7) {
                    .removeItemAt(7);
                }
            }
            
            if (.isShowing()) {
                found = false;
                for (int i = 0; !found && i < .getItemCount(); i++) {
                    found = .getItemAt(i).equals(findObject);
                }
                if (!found) {
                    .insertItemAt(replaceObject, 0);
                    if (.getItemCount() > 7) {
                        .removeItemAt(7);
                    }
                }
            }
        }
    }
    
    public static void showDialog() {
        showDialog(false);
    }
    
    

Parameters:
isReplace show a replace dialog rather than a find dialog if true
    
    public static void showDialog(boolean isReplace) {
        String title = isReplace ?  : ;
        .setTitle(title);
        
        String text = .getSelectedText();
        if (text == null) {
        	text = "";
        }
        .getEditor().setItem(text);
        .getEditor().selectAll();
                
        .setVisible(isReplace);
        .setVisible(isReplace);
        .setVisible(isReplace);
        Action action = isReplace ?
                 : ;
        .setAction(action);
        .setPreferredSize(null);
        Dimension d = isReplace ? 
            .getPreferredSize() :
            .getPreferredSize();
        .setPreferredSize(d);
        .setPreferredSize(d);
        .repaint();
        .pack();
        
        java.awt.Frame[] frames = java.awt.Frame.getFrames();
        for (int i = 0; i < frames.lengthi++) {
            if (frames[i].isFocused()) {
                .setLocationRelativeTo(frames[i]);
            }
        }
        
        .setVisible(true);
    }
    
    

Parameters:
textComponent the text component to stop listening to
    public static void unregisterTextComponent(JTextComponent textComponent) {
        textComponent.removeFocusListener();
    }
    
    private static class FindAction extends AbstractAction {
        
        public FindAction() {
            putValue(.);
            putValue(., Integer.valueOf(.));
        }
        
        public void actionPerformed(ActionEvent ae) {
             = ;
             = 0;
            
            if (.isVisible() &&
                .getTitle().equals()) {
            }
            int pos = .getSelectedText() == null ? 
                .getCaretPosition() : 
                .getSelectionStart();
            
            boolean reverse = (ae.getModifiers() & .) != 0;
            pos = findNext(reversepos);
            
            if (pos > -1) {
                String pattern = (String.getSelectedItem();
                .select(pospos + pattern.length());
                 = 1;
            }
            
            setListStrings();
            
            fireTextEvent();
        }
    }
    
    private static class ReplaceAction extends AbstractAction {
        
        public ReplaceAction() {
            putValue(.);
            putValue(., Integer.valueOf(.));
        }
        public void actionPerformed(ActionEvent ae) {
             = ae.getActionCommand();
             = 0;
            
            int pos = .getSelectedText() == null ? 
                .getCaretPosition() : 
                .getSelectionStart();
            pos = findNext(falsepos - 1);
            if (pos > -1) {
                String find = (String.getSelectedItem();
                String replace = (String.getSelectedItem();
                replace = replace == null ? "" : replace;
                Document doc = .getDocument();
                try {
                    doc.remove(posfind.length());
                    doc.insertString(posreplace);
                    int last = pos;
                    pos = findNext(falsepos);
                    if (pos > -1) {
                        .select(pospos + find.length());
                    }
                    else {
                        .setCaretPosition(last + replace.length());
                    }
                }
                catch (BadLocationException ble) {
                    ble.printStackTrace();
                }
                 = 1;
            }
            setListStrings();
            
            fireTextEvent();
        }
    }
    
    private static class ReplaceAllAction extends AbstractAction {
        
        public ReplaceAllAction() {
            putValue(., Integer.valueOf(.));
        }
        public void actionPerformed(ActionEvent ae) {
             = ae.getActionCommand();
             = 0;
            
            int last = .getSelectedText() == null ? 
                .getCaretPosition() : 
                .getSelectionStart();
            int pos = findNext(falselast - 1);
            String find = (String.getSelectedItem();
            String replace = (String.getSelectedItem();
            replace = replace == null ? "" : replace;
            while (pos > -1) {
                Document doc = .getDocument();
                try {
                    doc.remove(posfind.length());
                    doc.insertString(posreplace);
                    last = pos;
                    pos = findNext(falsepos);
                }
                catch (BadLocationException ble) {
                    ble.printStackTrace();
                }
                ++;
            }
            
            if (pos > -1) {
                .select(pospos + find.length());
            }
            else {
                .setCaretPosition(last + replace.length());
            }
            setListStrings();
            
            fireTextEvent();
        }
    }
    
    private static class CloseAction extends AbstractAction {
        
        public CloseAction() {
            putValue(.);
            putValue(., Integer.valueOf(.));
            putValue(., KeyStroke.getKeyStroke("ESCAPE"));
        }
        public void actionPerformed(ActionEvent ae) {
            .dispose();
        }
    }
    public static void dispose() {
        .dispose();
    }
New to GrepCode? Check out our FAQ X