2012-11-18 15 views
10

Sto cercando di implementare una funzione all'interno del programma in corso che sto scrivendo e voglio imparare a scorrere verso il basso per un testo specifico all'interno di un JTextArea. Ad esempio, consente di dire che ho il seguente:Java - Scorrere fino a un testo specifico all'interno JTextArea

JTextArea area = new JTextArea(someReallyLongString); 

someReallyLongString rappresenterebbe un paragrafo o un grande pezzo di testo (in cui la barra di scorrimento verticale sarebbe visibile). E quindi quello che sto cercando di fare è scorrere verso il basso fino a un testo specifico all'interno dell'area di testo. Ad esempio, diciamo someReallyLongString conteneva la parola "the" vicino al centro della barra di scorrimento (nel senso che questa parola non è visibile), come potrei scorrere fino a quel particolare testo?

Grazie, qualsiasi aiuto sarebbe molto apprezzato.

risposta

23

Questo è un esempio MOLTO di base. In pratica, il documento viene spostato per trovare la posizione della parola all'interno del documento e assicura che il testo venga spostato nell'area visibile.

evidenzia anche la partita

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

Ho paura di non poter "battere" questa risposta – Robin

+0

Sembra come quel Robin. Grazie mille MadProgrammer, molto utile e proprio quello che stavo cercando. –

+0

Vedere anche questo relativo [esempio] (http://stackoverflow.com/a/13449000/230513). – trashgod

3

Questo dovrebbe funzionare:

textArea.setCaretPosition(posOfTextToScroll); 

è possibile ottenere il posOfTextToScroll dal modello Document. Leggi su, nel Javadoc.

+3

Sì, ma come ottenere il posOfTextToScroll;) – MadProgrammer

+0

@Willmore Sono abbastanza sicuro "I" so come, sono stato MouseEvent incoraggiante fornire tali informazioni, perché è gentile la parte importante della risposta – MadProgrammer

+0

vedere un esempio come scorrere fino alla posizione desiderata http://java-swing-tips.blogspot.lt/2014/07/highlight-all-search-pattern- matches-in.html :) – Willmore

1

prima ottenere il testo impostato nell'area di testo e costruire un indice utilizzando una mappa per contenere il carattere e la posizione a trovarlo su.

In base a ciò, la risposta precedente suggeriva di utilizzare setCaretPosition utilizzando il valore recuperato dalla mappa.

Problemi correlati