在 Java 6 之前的所有版本中,放置在 JScrollPane 中的 JTextPane 的默认行为是:如果可能,在单词边界换行。如果没有,则无论如何都要将它们包裹起来。
在 JDK 7 中,默认行为似乎是:如果可能,在单词边界换行。如果不是,只需扩大 JTextPane 的宽度(永远不要换行长单词)。
重现这个很容易,这是一个SSCCE:
public class WrappingTest extends JFrame
{
public static void main ( String[] args )
{
new WrappingTest();
}
public WrappingTest ()
{
setSize(200,200);
getContentPane().setLayout(new BorderLayout());
JTextPane jtp = new JTextPane();
JScrollPane jsp = new JScrollPane(jtp);
jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
getContentPane().add(jsp,BorderLayout.CENTER);
setVisible(true);
}
}
只需在 JDK 6 和 JDK 7 中运行它,写一些小词,写一个长词,你就会看到区别。
我的问题很简单...JDK 7 中的新默认行为完全扰乱了我的程序(他们在 Oracle 应该更加小心地更改这种默认...它们看起来不重要但是当您使用JTextPane 显示通常包含很长的字母字符串的数据,它们并不是那么不重要 - 事实上我要提交错误报告,但我想有一个解决方法,而/如果他们没有解决它).有什么办法可以回到以前的行为?
请注意,我已经检查了相关问题的答案 How is word-wrapping implemented in JTextPane, and how do I make it wrap a string without spaces?但它没有回答这个问题 - 它提供了一种使 JTextPane 换行而不考虑空格的方法,但对我来说,所需的行为是尽可能在空格处拆分行,如果不可能则在其他地方拆分行(如以前的 Java版本)。
最佳答案
对我来说修复有效(在 1.7.0_09 下测试)
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
public class WrapTestApp extends JFrame {
public static void main ( String[] args ) {
new WrapTestApp();
}
public WrapTestApp () {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(200,200);
getContentPane().setLayout(new BorderLayout());
JTextPane jtp = new JTextPane();
jtp.setEditorKit(new WrapEditorKit());
JScrollPane jsp = new JScrollPane(jtp);
jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
getContentPane().add(jsp, BorderLayout.CENTER);
jtp.setText("ExampleOfTheWrapLongWordWithoutSpaces");
setVisible(true);
}
class WrapEditorKit extends StyledEditorKit {
ViewFactory defaultFactory=new WrapColumnFactory();
public ViewFactory getViewFactory() {
return defaultFactory;
}
}
class WrapColumnFactory implements ViewFactory {
public View create(Element elem) {
String kind = elem.getName();
if (kind != null) {
if (kind.equals(AbstractDocument.ContentElementName)) {
return new WrapLabelView(elem);
} else if (kind.equals(AbstractDocument.ParagraphElementName)) {
return new ParagraphView(elem);
} else if (kind.equals(AbstractDocument.SectionElementName)) {
return new BoxView(elem, View.Y_AXIS);
} else if (kind.equals(StyleConstants.ComponentElementName)) {
return new ComponentView(elem);
} else if (kind.equals(StyleConstants.IconElementName)) {
return new IconView(elem);
}
}
// default to text display
return new LabelView(elem);
}
}
class WrapLabelView extends LabelView {
public WrapLabelView(Element elem) {
super(elem);
}
public float getMinimumSpan(int axis) {
switch (axis) {
case View.X_AXIS:
return 0;
case View.Y_AXIS:
return super.getMinimumSpan(axis);
default:
throw new IllegalArgumentException("Invalid axis: " + axis);
}
}
}
}
关于java - 在 JTextPane (Java 7) 中包装长词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8666727/