Wrap the String After a Number of Characters Word-Wise in Java

Wrap the string after a number of characters word-wise in Java

You can use Apache-common's WordUtils.wrap().

How to wrap a string

You can do something like this -

    String str = "The event for mobile is here";
String temp = "";
if(str !=null && str.length() > 10) {
temp = str.substring(0, 10) + "...."; // here 0 is start index and 10 is last index
} else {
temp = str;
}
System.out.println(temp);

output would be - The event ....

cut string in java without breaking the middle of word

In this method pass your string and last index till you want to trancate.

public String truncate(final String content, final int lastIndex) {
String result = content.substring(0, lastIndex);
if (content.charAt(lastIndex) != ' ') {
result = result.substring(0, result.lastIndexOf(" "));
}
return result;
}

Use line wrap in JTextArea that wraps the line to a specific position in JTextArea

i want it to start from where rahul is written just below that not from left edge of text area

This is not supported in a JTextArea. A JTextArea is used for displaying simple text.

You could use a JTextPane. It allows you to control attributes of the text and one of the attributes could be the left indent. So you can set the paragraph attributes for a single line to be indented by a specific number of pixels.

So instead of using tabs to indent the text you would just need to set the left indent when you add the line of text.

Note also that a JTextPane does not implement an append method so you would need to create your own by adding text directly to the Document using:

textPane.getDocument.insertString(...);

So the basic logic would be:

StyledDocument doc=(StyledDocument)textPane.getDocument();
doc.insertString(...);
SimpleAttributeSet attrs = new SimpleAttributeSet();
//StyleConstants.setFirstLineIndent(attrs, 50);
StyleConstants.setLeftIndent(attrs, 50);
doc.setParagraphAttributes(0,doc.getLength(),attrs, false);

This will change the indent of the line of text you just added to the text pane.

Java parsing long lines of text into multiple lines

as per your comments, you are using JLabel for displaying the data.

to show multi-line text in JLabel just wrap your text in <html> tag like:

JLabel label = new JLabel("<html>your long text here ....</html>");

example:

String theReadLineFromTextFile = ....;

theReadLineFromTextFile = "<html>"+theReadLineFromTextFile+"</html>";
JLabel label = new JLabel(theReadLineFromTextFile);
//or
JLabel label = new JLabel();
label.setText(theReadLineFromTextFile);


Related Topics



Leave a reply



Submit