How to align multiple lines of JOptionPane output dialog messages by “:”?

Tags: , , ,



I need to make the output in 3 lines and also aligned by “:”, using JOptionPane.showdialogmessage(): *note the alignment of the “:”

Total  cost        : $11175.00
Number of units    : 500
Cost per unit      : $22.35

I have tried manually adding spaces before each “:” but still these 3 lines do not strictly align:

        String output = String.format("Total manufacturing cost                  :$%.2fn", manufactCost) + 
                String.format("Number of units manufactured       : $%dn", numManufacted) + 
                String.format("Cost per unit                                         : $%.2fn", unitCost);
                
        
        JOptionPane.showMessageDialog(null, output);

Here is the output screenshot:

enter image description here

What is the easiest way to realize this alignment? Thanks

P.S.: This is my first post. Sorry, I am still struggling with how to edit the post in a way that shows you the correct format of the output…I have been driven crazy by formatting… so I just post the screenshots instead… lol

Answer

Avoid using monospaced fonts, or strange tricks.
Construct a JPanel which uses a GridBagLayout, and remember showMessageDialog accepts other Components, not only text.

enter image description here

Relevant code. I opted for a separated label for : so that you can customize it as you prefer, while still keeping it aligned.

final JPanel panel = new JPanel(new GridBagLayout());

final GridBagConstraints gc = new GridBagConstraints();
final Insets descriptionInsets = new Insets(3, 5, 3, 15);
final Insets valuesInsets = new Insets(3, 2, 3, 2);

gc.fill = GridBagConstraints.HORIZONTAL;
gc.anchor = GridBagConstraints.NORTH;
gc.insets = descriptionInsets;
gc.weightx = 1.0;
panel.add(new JLabel("Total cost"), gc);

gc.insets = valuesInsets;
gc.weightx = 0;
gc.gridx = 1;
panel.add(new JLabel(":"), gc);

gc.gridx = 2;
panel.add(new JLabel("$11175.00"), gc);

gc.insets = descriptionInsets;
gc.weightx = 1.0;
gc.gridx = 0;
gc.gridy = 1;
panel.add(new JLabel("Number of units"), gc);

gc.insets = valuesInsets;
gc.weightx = 0;
gc.gridx = 1;
panel.add(new JLabel(":"), gc);

gc.gridx = 2;
panel.add(new JLabel("500"), gc);

gc.insets = descriptionInsets;
gc.weightx = 1.0;
gc.gridx = 0;
gc.gridy = 2;
panel.add(new JLabel("Cost per unit"), gc);

gc.insets = new Insets(3, 2, 3, 2);
gc.weightx = 0;
gc.gridx = 1;
panel.add(new JLabel(":"), gc);

gc.gridx = 2;
panel.add(new JLabel("$22.35"), gc);

JOptionPane.showMessageDialog(frame, panel);


Source: stackoverflow