I am trying to render a java.text.AttributedString
which is both bold and superscript. While it works to make some range either bold or superscripted, the rendering can't seem to handle a range that is both bold and superscript.
The following SSCCE shows that rendering this using a JLabel with HTML text works fine. Is there a way to get this behaviour without a JLabel?
Btw, I had a look into the created AttributedString properties and they look okay by me, so it is definitively a rendering problem.
package funky.chart;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.font.TextAttribute;
import java.text.AttributedString;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class AttributedStringTest
{
public static void main(String[] args) {
// prevent using the default UI manager who renders in bold by default for the HTML label
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
System.err.println("Could not set look and feel: " + ex);
}
JFrame frame = new JFrame("AttributedString superscript with font");
frame.getContentPane().add(new JPanel() {
@Override
public void paint(Graphics gfx) {
super.paint(gfx);
Font bold = gfx.getFont().deriveFont(Font.BOLD);
// superscript and bold only works fine
AttributedString test1 = new AttributedString("test superscript and bold");
test1.addAttribute(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER, 5, 16);
test1.addAttribute(TextAttribute.FONT, bold, 21, 25);
// both superscript and bold is only rendered as bold
AttributedString test2 = new AttributedString("test superscript and bold");
test2.addAttribute(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER, 5, 25);
test2.addAttribute(TextAttribute.FONT, bold, 5, 25);
gfx.drawString(test1.getIterator(), 5, 20);
gfx.drawString(test2.getIterator(), 5, 40);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 70);
}
});
// HTML label works fine
frame.getContentPane().add(
new JLabel("<html>test <b>bold</b>, <sup>super</sup> and <b><sup>both</sup></b>"),
BorderLayout.SOUTH);
frame.pack();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…