JEdi​​torPane和系统字体中的自动换行

时间:2013-05-20 00:44:29

标签: java swing java-7 jeditorpane

我想为用户创建一个大文本字段来输入内容。我还希望它使用默认的系统字体来匹配预期的外观。所以我尝试使用JEditorPane和默认构造函数,它使用纯文本编码。

JEditorPane editorPane = new JEditorPane();
editorPane.setText(gettysburgAddress);

enter image description here

这样做的问题在于,纯文本编码不会在每个单词的末尾换行换行符,只有当它用完字符时才会换行。

我尝试使用HTML编码,这个词包装:

JEditorPane editorPane = new JEditorPane("text/html", "");
editorPane.setText(gettysburgAddress);

enter image description here

这有自动换行,但默认为不同于系统默认的字体(Mac OS X上的Helvetica,我不想要。)

我怎样才能充分利用这两个方面:自动换行和系统默认字体?我不需要任何特殊格式或任何其他内容,因此如果可能的话,纯文本编码将会发生。

1 个答案:

答案 0 :(得分:6)

如果只需要使用系统字体的单词包装的JEditorPane,并且您不需要任何特殊的东西,如程式化的文本或图像,那么最好只需切换到JTextArea,这是用于执行纯文本的文本组件。默认情况下它不会自动换行,但它很容易实现:

JTextArea textArea = new JTextArea();
textArea.setLineWrap(true); //Makes the text wrap to the next line
textArea.setWrapStyleWord(true); //Makes the text wrap full words, not just letters
textArea.setText(gettysburgAddress);

如果您出于某种原因绝对必须使用JEditorPane,则必须卷起袖子并对JEditorPane呈现文本的方式进行一些更改。从好的方面来说,您有几种不同的方法可供选择。你可以:

  • 将编码设置为HTML(包装哪个词)并使用CSS指定字体(描述为here
  • 将编码设置为RTF(哪个词包装)并修改底层RTFEditorKit的字体值(描述为here
  • 创建SimpleAttributeSet并在添加字符串时使用它以指定它们应以这种方式显示(描述为here