问题
For my case, I want to get text inside JTextArea by number line.
For e.g
name : andy
birth : jakarta, 1 jan 1990
number id : 01011990 01
age : 26
study : Informatics engineering
So, I want to get a text in line 3.
I think I can use jTextArea.getText(3,jTextArea.getText().length())
,
but it doesn't work.
so, from line 3, i wish get text
number id : 01011990 01
回答1:
Simply based on the example from your previous question...
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));
And the runnable code
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);
});
}
}
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
回答2:
try following
String[] lines = jTextArea.getText().split("\n"); String numberId = lines[3];
or
String numberId = jTextArea.getText().split("\n")[3];
来源:https://stackoverflow.com/questions/34758621/java-get-text-from-jtextarea-by-number-line