0

我一直在尝试在 java 中打印一个仅由小写字母组成的 char 矩阵。起初我从矩阵条目中定义一个字符串,然后使用 JOptionPane 打印它,但显然由于字母的间距不同,列没有对齐,所以看起来很糟糕。代码如下:

String wordSearch = ""; 
for(int i = 0; i < 20; i++){   
  for(int j = 0; j < 20; j++){
    wordSearch = wordSearch + matrix[i][j] +"\t";    
  } 
wordSearch = wordSearch + "\n"; 
} 
JOptionPane.showMessageDialog(null, wordSearch);

然后我尝试使用 System.out 打印矩阵,如下所示

  for(int i = 0; i < 20; i++){
    for(int j = 0; j < 20; j++){
      System.out.print(matrix[i][j] +"   ");
    }
  System.out.println();
  }

并且输出看起来很完美,列对齐良好。

所以我的问题是如何使用 JOptionPane 或类似的东西获得相同的结果?为什么当我在控制台中打印时输出看起来不同?

非常感谢您的帮助。

4

1 回答 1

1

这应该有效:

javax.swing.UIManager.put("OptionPane.font", new Font("Courier", Font.PLAIN, 16));
final StringBuilder wordSearch = new StringBuilder(); 
for (int i = 0; i < 20; i++){   
    for (int j = 0; j < 20; j++){
        wordSearch.append(matrix[i][j]).append('\t');    
    } 
    wordSearch.append('\n'); 
} 
JOptionPane.showMessageDialog(null, wordSearch.toString());

(未测试)

于 2013-06-24T05:47:45.813 回答