java-通过数字行从JTextArea获取文本 [英] java - get text from JTextArea by number line

查看:322
本文介绍了java-通过数字行从JTextArea获取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我来说,我想通过数字行在JTextArea中获取文本.

For my case, I want to get text inside JTextArea by number line.

例如

name : andy
birth : jakarta, 1 jan 1990
number id : 01011990 01
age : 26
study : Informatics engineering

所以,我想在第3行得到一个文本.

So, I want to get a text in line 3.

我想我可以使用jTextArea.getText(3,jTextArea.getText().length()), 但这不起作用.

I think I can use jTextArea.getText(3,jTextArea.getText().length()), but it doesn't work.

所以,我希望从第3行得到文本

so, from line 3, i wish get text

number id : 01011990 01

推荐答案

仅基于可运行的代码

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Element;

public class ElementEndOffsetTest {

    public JComponent makeUI() {
        String str = "name : andy\n"
                + "birth : jakarta, 1 jan 1990\n"
                + "number id : 01011990 01\n"
                + "age : 26\n"
                + "study : Informatics engineering\n";

        JTextArea textArea = new JTextArea(str);
        textArea.setEditable(false);
        JPanel p = new JPanel(new BorderLayout());
        p.add(new JScrollPane(textArea));
        p.add(new JButton(new AbstractAction("add") {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    Document doc = textArea.getDocument();
                    Element root = doc.getDefaultRootElement();
                    Element element = root.getElement(2);
                    int start = element.getStartOffset();
                    int end = element.getEndOffset();
                    System.out.println(doc.getText(start, end - start));
                } catch (BadLocationException ex) {
                    ex.printStackTrace();
                }
            }
        }), BorderLayout.SOUTH);
        return p;
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            f.getContentPane().add(new ElementEndOffsetTest().makeUI());
            f.setSize(320, 240);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        });
    }
}

但是,根据您的问题,我建议您考虑改用JTable,这样会更容易,请参见

Based on your questions, I would, however, recommend you consider using a JTable instead, it would be easier, see How to Use Tables for more details

这篇关于java-通过数字行从JTextArea获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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