问题
I have a JTextArea
with the following properties:
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
In the GUI the text is wrapped normally but when I call textArea.getText();
a single line of text is returned with no line separators.
My question is how can I get the text from the text area component 'as it is in the GUI' into a String
or an array of strings?
Image Example:

回答1:
You can get width of JTextArea via textArea.size.width
, then get font metrics of JTextArea via textArea.getGraphics().getFontMetrics(textArea.getFont())
, using FontMetrics you can calculate width of a particular string - fontMetrics.stringWidth("Some string here")
.
Then you can, for example, add symbols of text one by one until you surpass width of JTextArea - and start a new line when you do.
I.e.
final String fullText = textArea.getText();
final int width = textArea.size.width;
final ArrayList lines = new ArrayList();
final FontMetrics fontMetrics = textArea.getGraphics().getFontMetrics(textArea.getFont());
StringBuilder sb = new StringBuilder();
for(final Character c : fullText) {
sb.append(c);
if(fontMetrics.stringWidth(sb.toString()) > width) {
sb.setLength(sb.length() - 1);
lines.add(sb.toString());
sb = new StringBuilder(c.toString());
}
}
lines.add(sb.toString());
回答2:
Read the javadoc - always informative.
int lineCount = textArea.getLineCount();
String[] lines = new String[lineCount];
String text = textArea.getText();
for (int i = 0; i < lineCount; ++i) {
int offset = textArea.getLineStartOffset(i);
int offset2 = textArea.getLineEndOffset(i);
lines[i] = text.substring(offset, offset2);
}
Not sure that this does line wraps.
来源:https://stackoverflow.com/questions/31519473/how-to-get-line-wrapped-text-from-jtextarea-into-multiple-line-seperated-strings