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 :$%.2f\n", manufactCost) +
String.format("Number of units manufactured : $%d\n", numManufacted) +
String.format("Cost per unit : $%.2f\n", unitCost);
JOptionPane.showMessageDialog(null, output);
Here is the output screenshot:
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
Avoid using monospaced fonts, or strange tricks.
Construct a JPanel
which uses a GridBagLayout
, and remember showMessageDialog
accepts other Component
s, not only text.
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);