public void search() {
    hilit.removeAllHighlights();

    String s = entry.getText();
    if (s.length() <= 0) {
      message("Nothing to search");
      return;
    }

    String content = textArea.getText();
    int index = content.indexOf(s, 0);
    if (index >= 0) {
      try {
        int end = index + s.length();
        hilit.addHighlight(index, end, painter);
        textArea.setCaretPosition(end);
        entry.setBackground(entryBg);
        message("'" + s + "' found. Press ESC to end search");
      } catch (BadLocationException e) {
        e.printStackTrace();
      }
    } else {
      entry.setBackground(ERROR_COLOR);
      message("'" + s + "' found. Press ESC to start a new search");
    }
  }
Exemplo n.º 2
0
 @Override
 public void actionPerformed(ActionEvent e) {
   if (td.getTabCount() > 0) {
     TextDocument ta = (TextDocument) td.getComponentAt(td.getSelectedIndex());
     Pattern pn = Pattern.compile(tf1.getText());
     Matcher mt = pn.matcher(ta.getText());
     if (e.getSource() == jb2) { // 取代
       ta.setText(mt.replaceAll(tf2.getText()));
     } else if (e.getSource() == jb1) { // 尋找
       Highlighter hl = ta.getHighlighter();
       hl.removeAllHighlights();
       while (mt.find()) {
         try {
           hl.addHighlight(
               mt.start(), mt.end(), new DefaultHighlighter.DefaultHighlightPainter(null));
         } catch (Exception ex) {
         }
       } // 開啟及關閉介面
     } else if (e.getSource() == replace_searchMenuItem) {
       System.out.println("Replace/Search is show:" + !show);
       if (show) {
         getContentPane().remove(jp);
         show = false;
       } else {
         getContentPane().add(jp, BorderLayout.SOUTH);
         show = true;
       }
       validate(); // 刷新容器
     }
   } else if (e.getSource() == replace_searchMenuItem) {
     JOptionPane.showMessageDialog(
         null, "尚無檔案,無法使用!", "Repace/Search error", JOptionPane.ERROR_MESSAGE);
   }
 }