java - 与 System.out.println(); 相比,为什么 JOptionPane 显示不同的输出?
问题描述
我试图使用 System.out.println(); 创建一个乘法表;并且格式完美;但是,当我尝试将其更改为 JOptionPane 函数时,结果并不令人满意。这是 System.out.println(); 代码:
public class Problem {
public static void main(String[]args){
String output = " Multiplication Table\n";
output+= " ------------------------------------\n";
output+=" | ";
for(int j = 1;j<=9;j++)
output+= j +" ";
output+= "\n";
for(int i = 1 ; i<=9;i++){
output+= i + "|";
for(int j = 1;j<=9;j++){
output+=String.format("%4d", i * j);
}
output+="\n";
}
System.out.println(output);
}
}
这是输出:
Multiplication Table
------------------------------------
| 1 2 3 4 5 6 7 8 9
1| 1 2 3 4 5 6 7 8 9
2| 2 4 6 8 10 12 14 16 18
3| 3 6 9 12 15 18 21 24 27
4| 4 8 12 16 20 24 28 32 36
5| 5 10 15 20 25 30 35 40 45
6| 6 12 18 24 30 36 42 48 54
7| 7 14 21 28 35 42 49 56 63
8| 8 16 24 32 40 48 56 64 72
9| 9 18 27 36 45 54 63 72 81
但是改变System.out.println(output); 到JOptionPane.showMessageDialog(null, output); 与 System.out.println() 相比,给出了混乱的格式,没有很好地对齐;我不知道如何从 JOptionPane 复制输出,但它看起来像这样:
1| 1 2 3 4 5 6 7 8 9
2| 2 4 6 8 10 12 14 16 18
3| 3 6 9 12 15 18 21 24 27
4| 4 8 12 16 20 24 28 32 36
5| 5 10 15 20 25 30 35 40 45
6| 6 12 18 24 30 36 42 48 54
7| 7 14 21 28 35 42 49 56 63
8| 8 16 24 32 40 48 56 64 72
9| 9 18 27 36 45 54 63 72 81
解决方案
问题都与使用的字体有关,默认情况下 JOptionPane 不会以等宽字体显示文本。您可以通过更改用于 JOptionPane 的字体来亲眼看到这一点:
import javax.swing.*;
import java.awt.*;
public class Problem {
public static void main(String[]args){
String output = " Multiplication Table\n";
output+= " ------------------------------------\n";
output+=" | ";
for(int j = 1;j<=9;j++)
output+= j +" ";
output+= "\n";
for(int i = 1 ; i<=9;i++){
output+= i + "|";
for(int j = 1;j<=9;j++){
output+=String.format("%4d", i * j);
}
output+="\n";
}
System.out.println(output);
JOptionPane.showMessageDialog(null, output); // non-monospaced font
JTextArea textArea = new JTextArea(output);
textArea.setFocusable(false);
textArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
textArea.setBorder(null);
textArea.setBackground(null);
JOptionPane.showMessageDialog(null, textArea); // displaying a monospaced font
}
}
这将第二个 JOptionPane 显示为:
请注意,JOptionPane 的字体将由您的程序使用的任何外观指定。您可以通过使用 UIManager 更改 JOptionPane 使用的默认消息字体来告诉 L&F 使用特定的字体。例如,如果您在下面进行调用,那么 JOptionPane 使用的 JLabel(这里 JOptionPane 使用 GridLayout 创建了几行 JLabel 显示在 JPanel 中)到所需的任何字体:
UIManager.put("OptionPane.messageFont", new Font(Font.MONOSPACED, Font.PLAIN, 12));
JOptionPane.showMessageDialog(null, output); // non-monospaced font
推荐阅读
- c++ - 如何使用 CMake 和 Qt Creator 自动将 Qt 依赖项复制到构建目录?
- flutter - 如何在 Flutter 中检查 ShareExtend.share() 的目的地
- azure - 如何获取 Azure 数据工厂数据集、触发器、管道和链接服务的数量?
- php - 将 WordPress 帖子添加到 Elementor Pro 表单选择字段
- subshell - 子shell中奇怪的ksh93行为
- c# - 有没有办法访问 Roslyn 中降低的 C# AST
- google-data-studio - Vega-Lite:堆叠分组条形图
- react-admin - 升级到 3.18 后 React-Admin 翻译中断
- mysql - MariaDB中日期范围和时间范围之间的SQL查询
- regex - Intellij Search Regex,选择特定的捕获组