2012-11-18 12 views
10

私が書いている現在のプログラムの中に機能を実装しようとしています.JTextArea内の特定のテキストにスクロールする方法を学びたいと思います。たとえば、以下の私が持って言うことができます:Java - JTextArea内の特定のテキストにスクロール

JTextArea area = new JTextArea(someReallyLongString); 

someReallyLongStringは、段落、またはテキストの非常に大きな部分を(ここで、垂直スクロールバーが表示されます)を表します。そして、私がしようとしていることは、そのテキストエリア内の特定のテキストにスクロールすることです。たとえば、someReallyLongStringにスクロールバーの中央付近に「the」という単語が含まれているとします(この単語は表示されません)。どのようにその特定のテキストにスクロールしますか?

ありがとうございました。ご協力いただきありがとうございます。

答えて

23

これは非常に基本的な例です。これは、基本的にドキュメント内を移動してドキュメント内の単語の位置を見つけ、テキストが表示可能領域に移動することを保証します。また、試合

enter image description here

public class MoveToText { 

    public static void main(String[] args) { 
     new MoveToText(); 
    } 

    public MoveToText() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
       } 

       JFrame frame = new JFrame("Testing"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setLayout(new BorderLayout()); 
       frame.add(new FindTextPane()); 
       frame.setSize(400, 400); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public class FindTextPane extends JPanel { 

     private JTextField findField; 
     private JButton findButton; 
     private JTextArea textArea; 
     private int pos = 0; 

     public FindTextPane() { 
      setLayout(new BorderLayout()); 
      findButton = new JButton("Next"); 
      findField = new JTextField("Java", 10); 
      textArea = new JTextArea(); 
      textArea.setWrapStyleWord(true); 
      textArea.setLineWrap(true); 

      Reader reader = null; 
      try { 
       reader = new FileReader(new File("Java.txt")); 
       textArea.read(reader, null); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } finally { 
       try { 
        reader.close(); 
       } catch (Exception e) { 
       } 
      } 

      JPanel header = new JPanel(new GridBagLayout()); 

      GridBagConstraints gbc = new GridBagConstraints(); 
      gbc.gridx = 0; 
      gbc.gridy = 0; 
      gbc.anchor = GridBagConstraints.WEST; 
      header.add(findField, gbc); 
      gbc.gridx++; 
      header.add(findButton, gbc); 

      add(header, BorderLayout.NORTH); 
      add(new JScrollPane(textArea)); 

      findButton.addActionListener(new ActionListener() { 
       @Override 
       public void actionPerformed(ActionEvent e) { 
        // Get the text to find...convert it to lower case for eaiser comparision 
        String find = findField.getText().toLowerCase(); 
        // Focus the text area, otherwise the highlighting won't show up 
        textArea.requestFocusInWindow(); 
        // Make sure we have a valid search term 
        if (find != null && find.length() > 0) { 
         Document document = textArea.getDocument(); 
         int findLength = find.length(); 
         try { 
          boolean found = false; 
          // Rest the search position if we're at the end of the document 
          if (pos + findLength > document.getLength()) { 
           pos = 0; 
          } 
          // While we haven't reached the end... 
          // "<=" Correction 
          while (pos + findLength <= document.getLength()) { 
           // Extract the text from teh docuemnt 
           String match = document.getText(pos, findLength).toLowerCase(); 
           // Check to see if it matches or request 
           if (match.equals(find)) { 
            found = true; 
            break; 
           } 
           pos++; 
          } 

          // Did we find something... 
          if (found) { 
           // Get the rectangle of the where the text would be visible... 
           Rectangle viewRect = textArea.modelToView(pos); 
           // Scroll to make the rectangle visible 
           textArea.scrollRectToVisible(viewRect); 
           // Highlight the text 
           textArea.setCaretPosition(pos + findLength); 
           textArea.moveCaretPosition(pos); 
           // Move the search position beyond the current match 
           pos += findLength; 
          } 

         } catch (Exception exp) { 
          exp.printStackTrace(); 
         } 

        } 
       } 
      }); 

     } 
    } 
} 
+2

私はこの答えを "打ち負かすことはできません"と恐れています – Robin

+0

ロビンのように。ありがとうMadProgrammer、非常に役立ち、ちょうど私が探していた。 –

+0

関連[例](http://stackoverflow.com/a/13449000/230513)も参照してください。 – trashgod

3

これは動作するはずです:

textArea.setCaretPosition(posOfTextToScroll); 

あなたはDocumentモデルによってposOfTextToScrollを得ることができます。 Javadocでそれについて読んでください。

+3

はい、しかし、どのようにposOfTextToScrollを取得するを強調

;) – MadProgrammer

+0

@Willmore私は「私は」、私はMouseEventのを奨励してする方法を知っているかなり確信していますその情報を提供してくれるのは、それが親切であるからです。 – MadProgrammer

+0

希望の位置にスクロールする方法の例を参照してください。http://java-swing-tips.blogspot.lt/2014/07/highlight-all-search-pattern- matches-in.html :) – Willmore

1

最初にテキスト領域に設定したテキストを取得し、文字とその位置を保持するマップを使用してインデックスを作成します。

これを元に、マップから取得した値を使用してsetCaretPositionを使用することを提案しました。

関連する問題