如何通过“:”对齐多行 JOptionPane 输出对话框消息?

问题描述

我需要使用 JOptionPane.showdialogmessage() 将输出分成 3 行并通过“:”对齐: *注意“:”的对齐方式

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

我试过在每个“:”之前手动添加空格,但这 3 行仍然没有严格对齐:

        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);

输出截图如下:

enter image description here

实现这种对齐的最简单方法是什么? 谢谢

P.S.:这是我的第一篇文章。抱歉,我仍然在苦苦思索如何以一种向您显示正确输出格式的方式编辑帖子……我已经被格式化逼疯了……所以我只是发布了屏幕截图……哈哈>

解决方法

避免使用等宽字体或奇怪的技巧。
构造一个使用 JPanelGridBagLayout,并记住 showMessageDialog 接受其他 Component,而不仅仅是文本。

enter image description here

相关代码。我为 : 选择了一个单独的标签,以便您可以根据自己的喜好自定义它,同时仍然保持对齐。

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,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.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);
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);
,

如果您将标签文本设置为以 "<html>" 开头,那么该文本将被解释为非常基本的早期 HTML。因此,您可以插入表格或其他对齐方式。

,

如果可以接受等宽字体:

  1. 使用 "monospaced" Font(默认字体不是等宽的,因此几乎不可能对齐)
  2. 根据需要使用 String.format 格式化字符串

替代方法(我的首选,但不是最简单的方法):
使用 JPanel 作为 JOptionPanemessage,在那里您可以使用布局管理器,如 GridBagLayout(或 GridLayout,易于使用)。

Tom 的回答,使用 HTML,也很容易使用(可能是最简单的解决方案)