如何在 JOptionpane 中格式化 table?

How to format a table in JOptionpane?

所以,我有一个程序可以搜索文件以找到用户想要的所需信息,我试图在 JOptionPane 中以漂亮的 table 输出它以使其更易于阅读,但是我不断收到这样的信息:

我希望这些行相应地排列并正确格式化,这是该特定消息的代码:

 String message=String.format("%-10s|%7s|%14s|%13s|%22s", element,symbol,atomicNumber,atomicMass,valence);
JOptionPane.showMessageDialog(null, "Name      |Symbol |Atomic Number |Atomic Mass  |# of Valence Electrons  \n _________________________________________________________________ \n " + message);

似乎无法弄清楚我在这里做错了什么,我在不同的任务中使用了完全相同的格式代码,它只使用了终端并且工作正常,但现在我正在尝试在 JOptionPane 中使用它的格式不正确。

关于如何解决这个问题或让它发挥作用有什么想法吗?

改用 JTable:

Object[][] rows = {
    {element,symbol,atomicNumber,atomicMass,valence}
};
Object[] cols = {
    "Name","Symbol","Atomic Number","Atomic Mass", "# of Valence Electrons"
};
JTable table = new JTable(rows, cols);
JOptionPane.showMessageDialog(null, new JScrollPane(table));

终端和Swing对话框的区别在于前者使用固定宽度的字体,而后者使用可变宽度的字体。例如:如果您查看您发布的图片,您会发现 'i' 的宽度远小于 'm'。这意味着一个 15 个字符长的字符串不一定占用与另一个相同长度的字符串相同的 space。

在 Swing 中格式化此类内容的正确解决方案是使用 JTable or a GridBagLayout. If you are happy to use a third party library I recommend looking at DesignGridLayout.

您也可以显式设置字体,但这仍然需要您更改代码,并且在 Swing 应用程序的上下文中看起来有点陈旧。

Any ideas on how to fix this or make it work?

在 JOptionPane 的强力解决方案的上下文中,您应该能够指定选项窗格要使用的对象数组。所以代码应该是这样的:

JLabel[] labels = new JLabel[3];
JLabel heading = new JLabel(...);
heading.setFont( ("monospaced", Font.PLAIN, 12) );
labels[0] = heading;
JLabel line = new JLabel(...);
...
JLabel data = new JLabel(...);
...
JOptionPane.showMessageDialog(null, labels);

这不是一个很好的解决方案,但我只是想展示 JOptionPane 显示垂直组织的多个组件的灵活性。

另一个选项可能是使用 UIManager 并更改选项窗格的默认字体。代码类似于:

Font original = UIManager.getFont("Label.font");
UIManager.put("Label.font", new Font(...)); // specify your monospaced font here
JOptionPane.showMessage(...);
UIManager.put("Label.font", original); // restore default font

我不确定这种字体是适用于选项面板上的所有组件还是仅适用于按钮或仅适用于显示组件。

JTable 对我来说是更好的方法。