Click here to Skip to main content
15,920,508 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to set a length to my String, as I want the different elements of my ArrayList, displayed by a JList, to be aligned correctly.

Here is an image of the problem: https://prnt.sc/k7vg91

What I have tried:

I tried using this while loop, but the element in the JList are not lining up properly.
nameBoisson is the String I'm using.

public String toString()
    {
        while (nameBoisson.length() <49)
        {
            nameBoisson = nameBoisson + " ";
        }
        return nameBoisson +prixDeVente +" € " +conditionnement +"L";
    }
Posted
Updated 17-Jul-18 23:12pm
v3

You have to use a fixed width font (Monospaced font - Wikipedia[^]) like Courier to show properly aligned text tables. How to select such depends on the used output method.

This uses a fixed width font:
Item     Price
AnItem   €    13.49
Another  €   127.80
The same using a proportional font:
Item     Price
AnItem   €    13.49
Another  €   127.80

[EDIT]
Overlooked the JList.
To set the font use something like
Java
myList.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
To format the line strings use String.format as suggested in solution 1:
Java
String strLine = String.format("%-49s% 10.2f € ", nameBoisson, prixDevente);
Here %-49s prints a string left aligned with trailing spaces up to a total length of 49 characters and % 10.2f prints a floating point value right aligned with a total length of 10 characters, 2 digits after the decimal point, and a leading space for positive values.
[/EDIT]
 
Share this answer
 
v3
You may use String.format for the purpose, see, for instance: Java String.format examples[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900