J. Avelar
J. Avelar

Reputation: 15

Displaying loop horizontally in jlabel

while (minValue <= maxValue){
        valueOutput.setText(""+minValue);
        minValue++;

This is the while loop that I'm using to display the numbers from an entered minimum and maximum number, but I am having trouble displaying the numbers properly in the jLabel

The numbers are formatted vertically and only shows the last number in the jLabel

Upvotes: 0

Views: 54

Answers (2)

camickr
camickr

Reputation: 324118

The setText() replaces the existing text.

What you want to do is create a String in your loop and when the loop finishes you set the text in the label with the text in the String. You can use the StringJoiner class for this:

StringJoiner sj = new StringJoiner(",");

while (minValue <= maxValue)
{
    sj.add( "" + minValue);
    minValue++;
}

valueOutput.setText( sj.toString() );

Upvotes: 1

Antoniossss
Antoniossss

Reputation: 32517

Try this:

StringJoiner joiner=new StringJoiner();

while (minValue <= maxValue){
   joiner.add(String.valueOf(minValue++);
}
valueOutput.setText(joiner.toString());

This will create string of numbers separated by default separator (,) and then it will pe placed inside label (assuming thats what valueOutput is )

You can replace StringJoiner with StringBuilder if you are not using Java8

Upvotes: 0

Related Questions