【问题标题】:Java - Scroll to specific text inside JTextAreaJava - 滚动到 JTextArea 内的特定文本
【发布时间】:2012-11-06 10:25:19
【问题描述】:

我正在尝试在我正在编写的当前程序中实现一项功能,我想学习如何向下滚动到 JTextArea 中的特定文本。例如,假设我有以下内容:

JTextArea area = new JTextArea(someReallyLongString);

someReallyLongString 将表示一个段落,或一段非常大的文本(其中垂直滚动条可见)。所以我想做的是向下滚动到该文本区域内的特定文本。例如,假设 someReallyLongString 在滚动条中间附近包含单词“the”(这意味着该单词不可见),我将如何向下滚动到该特定文本?

谢谢,任何帮助将不胜感激。

【问题讨论】:

    标签: java swing text jtextarea caret


    【解决方案1】:

    这是一个非常基本的例子。这基本上是遍历文档以找到单词在文档中的位置,并确保将文本移动到可视区域。

    它还突出了比赛

    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();
                            }
    
                        }
                    }
                });
    
            }
        }
    }
    

    【讨论】:

    • 恐怕我们无法“击败”这个答案
    • 好像是那个罗宾。非常感谢 MadProgrammer,非常有帮助,正是我想要的。
    【解决方案2】:

    这应该可行:

    textArea.setCaretPosition(posOfTextToScroll);
    

    您可以通过Document 模型获得posOfTextToScroll。在 Javadoc 中阅读它。

    【讨论】:

    • 是的,但是如何获取 posOfTextToScroll ;)
    • @Willmore 我很确定“我”知道怎么做,我鼓励 MouseEvent 提供这些信息,因为它是答案的重要部分
    • 查看示例如何滚动到所需位置java-swing-tips.blogspot.lt/2014/07/… :)
    【解决方案3】:

    首先获取您在文本区域中设置的文本,并使用映射构建索引来保存字符和您找到它的位置。

    基于此,先前的答案建议使用从地图中检索到的值使用 setCaretPosition。

    【讨论】:

      【解决方案4】:

      添加到 MadProgrammer 的评论中:

      scrollRectToVisible(viewRect) 自 Java SE9 起已弃用,已被 scrollRectToVisible2D(viewRect) 取代

      在不使用过时函数的情况下显示文本的正确方法是:

      java.awt.geom.Rectangle2D view = area.modelToView2D(pos); // View where pos is visible
      area.scrollRectToVisible(view.getBounds()); // Scroll to the rectangle provided by view
      area.setCaretPosition(pos); // Sets carat position to pos
      

      【讨论】:

        猜你喜欢
        • 2015-12-17
        • 2020-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多