在JTextArea中的列中对齐字符串

我想在JTextArea中打印字符串并正确对齐它们。 很难解释所以我将上传我想要实现的屏幕截图。

到目前为止我所获得的屏幕截图

因此,每行打印的字符串都是从Paper对象打印出来的,该对象具有参数(id,title,author,date,rank)。 数据从文本文件中读取,并使用loadPaper()函数存储在LinkedList中。

然后displayPapers()函数用于向JTextArea显示Paper对象的内容。 displayPapers()如下所示:

/** Print all Paper object present in the LinkedList paperList to textArea */ public void displayPapers(){ // clear textArea before displaying new content displayTxtArea.setText(""); Paper currentPaper; ListIterator iter = paperList.listIterator(); while(iter.hasNext()){ currentPaper = iter.next(); String line = currentPaper.toString(); if("".equals(line)){ continue; } // end if String[] words = line.split(","); displayTxtArea.append (" " + padString(words[0],30) + padString(words[1],30) + " " + padString(words[2],30) + " " + padString(words[3],30) + padString(words[4],30) + "\n"); System.out.println(words); //displayTxtArea.append(currentPaper.toString()); } // end while displayTxtArea.append(" Total " + noOfPapers + " entries!"); } // end showAllPaper 

padString()函数为String添加空格,以便它们都具有相同数量的单词。 PadString()如下所示:

 /** Add spaces to Strings so that all of the are of same number of characters * @param str String to be padded * @param n total number words String should be padded to * @return str Padded string */ private String padString(String str, int n){ if(str.length() < n){ for(int j = str.length(); j < n; j++){ str += " "; } // end for } // end if return str; } // end padString 

我已经研究了一段时间,但仍然无法得到解决方案。 正如您可以注意到上面的图片并非所有内容都按照预期完全对齐。

如何将它们完美对齐以使其看起来更好? 谢谢。

仅当您使用单倍间距字体时,输出才会在JTextArea中“正确”对齐。 例如,“Andale Mono 14”就可以解决这个问题。

此外,为了让您的生活更轻松并避免填充地狱,请使用String.format及其语法 。

 String format = "%1$5s %2$-40s %3$-20s"; String someLine; while (whatEver...) { ... someLine = String.format(format, aNum, aName, aDate); jTextArea1.append(someLine + "\n"); } 

使用JTable代替(显然是表格信息)。 有关更多详细信息和工作示例,请参见如何使用表 。

表格排序演示

您可以将HTML与swing组件一起使用或使用JEdi​​torPane 。

 JLabel jt=new JLabel(); jt.setText(" 
NoName
1Mr.A
");

如果问题允许,您还可以更改JTextArea的字体

 textArea.setFont(new Font("monospaced", Font.PLAIN, 12));