I’m facing an annoying little bug with JTextPane and hanging indent.
Here’s a simple example:
public class Scrap {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setLayout(new BorderLayout());
JTextPane textPane = new JTextPane();
JScrollPane scroll = new JScrollPane(textPane);
frame.add(scroll);
StyledDocument doc = (StyledDocument) textPane.getDocument();
try {
String str = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum ";
doc.insertString(doc.getLength(), str, null);
// Hanging indent
MutableAttributeSet mas = new SimpleAttributeSet();
StyleConstants.setLeftIndent(mas, 20);
StyleConstants.setFirstLineIndent(mas, -20);
doc.setParagraphAttributes(0, str.length(), mas, false);
} catch (BadLocationException e) {
e.printStackTrace();
}
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}
On my computer, with Java 7, the first row is bolder than the other rows for some reason… Anyone have ideas how to fix this?
I got back to this, and I got it fixed! At least well enough for my needs. The problem was, as I suspected, that JTextPane drew the first line twice.
Oracle conveniently ignored my bug report, I guess they just don’t care about Swing anymore.
Here’s the fix (including the long word wrap fix for Java 7, which I found from somewhere):
}