// 1. inits searchField with selected text // 2. adds focus listener so that textselection gets painted // even if the textcomponent has no focus protected void initSearch(ActionEvent ae) { super.initSearch(ae); JTextComponent textComp = (JTextComponent) ae.getSource(); String selectedText = textComp.getSelectedText(); if (selectedText != null) searchField.setText(selectedText); searchField.removeFocusListener(this); searchField.addFocusListener(this); }
public static void main(String[] args) throws Exception { JTextArea textArea = new JTextArea(10, 50); textArea.setEditable(false); try { new DefaultEditorKit() .read( new FileReader( "D:\\MyBlog\\IncrementalSearch\\src\\santhosh\\TextComponentFindAction.java"), textArea.getDocument(), 0); } catch (Exception e) { e.printStackTrace(); } FindAction findAction = new TextComponentFindAction(); findAction.install(textArea); JScrollPane scroll = new JScrollPane(textArea); scroll.setBorder( BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(50, 10, 10, 10), scroll.getBorder())); JOptionPane.showMessageDialog(null, scroll); }