[Solved] Wrapping Text

I am trying to change the text that I have put as default in an xml file via code, but the new string is not wrapping.

Here’s what I’m doing…



screen.xml



text id=“CharText” text=“A long string that does wrap as required” width=“100%” height=“100%” wrap=“true”





code to change CharText



Element CharText = nifty.getCurrentScreen().findElementByName(“CharText”);



CharText.getRenderer(TextRenderer.class).setText(“A long string that does NOT wrap as required”);





The new text does display but overlaps its boundaries and does not wrap.



How can I make the new text wrap?



Thanks in advance.

This is a known bug in Nifty and hasn’t been fixed yet. The work around I’ve been using is to pre-wrap the string



[java]

// Hack to make line wrapping work until the nifty control is fixed!

String[] lines = ret.split(“n”);

ret = “”;



for (int line = 0;line<lines.length;line++) {

int offset = 0;



String l=lines[line];

while (l.length()-offset > 60) {

for (int i=60;i>=40;i–)

if (l.charAt(i+offset)==’ ’ || i==40) {

l = l.substring(0, i+offset)+“n”+l.substring(i+offset+1);

offset += i;

break;

}

}

lines[line]=l;

ret += l+“n”;

}

[/java]



Change 60 and 40 to be suitable threshold values for your text object. 60 is the character to wrap at, 40 is the minimum line length at which it wraps even if a space wasn’t found.

1 Like

(And I know it could be optimised/tidied up/etc but it’s a hack until a fix is available and is only called pretty infrequently so I spent the minimum time possible on it :p)

1 Like

ok thanks,

i will have a look at that.

It doesn’t work automatically?

I’m using the latest nifty from the git repository, so maybe that’s why it works for me, but all I do is this:

[java]element.getRenderer(TextRenderer.class).setText(text);

element.getParent().layoutElements();[/java]

and of course ‘wrap=“true”’ on the label element in the xml.

3 Likes

this





element.getParent().layoutElements();





does the job. thanks.



saved me a lot of hassle but increased my work load as I won’t scrap feature now :stuck_out_tongue:

Wow I searched the forums and nifty wiki some weeks ago for this problem without finding a solution and here -bang!- it is and it works, thank you!

@cmur2 said:
Wow I searched the forums and nifty wiki some weeks ago for this problem without finding a solution and here -bang!- it is and it works, thank you!


Yep, me too.

Nice one @Tumaini. A much better work around than my one :)