Java - 滚动到JTextArea中的特定文本 [英] Java - Scroll to specific text inside JTextArea

查看:97
本文介绍了Java - 滚动到JTextArea中的特定文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  JTextArea area = new JTextArea(someReallyLongString); 

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



<谢谢,任何帮助都会非常感激。

解决方案

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



它还突出显示匹配



  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框架= 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);
}
});
}

公共类FindTextPane扩展JPanel {

private JTextField findField;
私人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(例外e){
e.printStackTrace();
} finally {
try {
reader.close();
} catch(例外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){
//获取文本以查找...转换eaiser比较小写
String find = findField.getText()。toLowerCase();
//聚焦文本区域,否则突出显示不会显示
textArea.requestFocusInWindow ();
//确保我们有一个有效的搜索词
if(find!= null&& find.length()> 0){
Document document = textArea。 getDocument();
int findLength = find.length();
try {
boolean found = false;
//如果我们在结束时休息搜索位置文件
if(p os + findLength> document.getLength()){
pos = 0;
}
//虽然我们尚未到达终点...
//< =更正
而(pos + findLength< = document.getLength( )){
//从文档中提取文本
String match = document.getText(pos,findLength).toLowerCase();
//检查它是否匹配或请求
if(match.equals(find)){
found = true;
休息;
}
pos ++;
}

//我们找到了什么...
if(found){
//获取文本可见的矩形... 。
Rectangle viewRect = textArea.modelToView(pos);
//滚动以使矩形可见
textArea.scrollRectToVisible(viewRect);
//突出显示文本
textArea.setCaretPosition(pos + findLength);
textArea.moveCaretPosition(pos);
//将搜索位置移动到当前匹配之外
pos + = findLength;
}

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

}
}
});

}
}
}


I'm trying to implement a feature inside the current program that I'm writing and I wanna learn how to scroll down to specific text inside a JTextArea. For example, lets say I have the following:

JTextArea area = new JTextArea(someReallyLongString);

someReallyLongString would represent a paragraph, or a very large piece of text (in which the vertical scrollbar would be visible). And so what I am trying to do is scroll down to specific text within that text area. For example, lets say someReallyLongString contained the word "the" near the middle of the scrollbar (meaning this word is not visible), how would I scroll down to that specific text?

Thanks, any help would be greatly appreciating.

解决方案

This is a VERY basic example. This basically walks the document to find the position of the word within the document and ensures that the text is moved to the viewable area.

It also highlights the match

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

                    }
                }
            });

        }
    }
}

这篇关于Java - 滚动到JTextArea中的特定文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆