【发布时间】:2020-03-01 14:04:59
【问题描述】:
我试图使用 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 使用非等宽字体
标签: java swing formatting joptionpane