使用StyleConstants.Bold时,AttributeSet会引发错误

时间:2016-03-28 18:35:19

标签: java swing awt jtextpane

请考虑以下代码:

import java.awt.*;import javax.swing.*;import javax.swing.text.*;
public class Main extends JFrame {
    private final StyleContext cont = StyleContext.getDefaultStyleContext();
    private final AttributeSet normal = cont.addAttribute(cont.getEmptySet(),StyleConstants.Foreground,Color.BLACK);
    private final AttributeSet bold = cont.addAttribute(cont.getEmptySet(),StyleConstants.Bold,Color.BLACK);
    public Main() {
        setSize(800,600);
        JPanel pane = new JPanel();
        pane.setLayout(new BorderLayout()); // this is used to make the textpane take up the entire space
        getContentPane().add(pane); // adds pane to the frame
        JTextPane textPane = new JTextPane();
        StyledDocument doc = textPane.getStyledDocument();
        try {
            doc.insertString(0,"Lorem ipsum dolor sit amet, consectetur adipiscing elit.",normal/*change to bold for error*/);
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
        pane.add(textPane,BorderLayout.CENTER);
    }
    public static void main(String[] args) {
        Main main = new Main();
        main.setVisible(true);
    }
}

当我使用AttributeSet normal将文本插入JTextPane时,代码会正常运行并显示所需的结果。但是,当我尝试使用AttributeSet bold(请参阅第14行的评论)插入文字时,我得到以下ClassCastException

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.awt.Color cannot be cast to java.lang.Boolean
    at javax.swing.text.StyleConstants.isBold(StyleConstants.java:399)
    at javax.swing.text.StyleContext.getFont(StyleContext.java:188)
    at javax.swing.text.DefaultStyledDocument.getFont(DefaultStyledDocument.java:943)
    at javax.swing.text.LabelView.setPropertiesFromAttributes(LabelView.java:145)
    at javax.swing.text.LabelView.sync(LabelView.java:56)
    at javax.swing.text.LabelView.getFont(LabelView.java:208)
    at javax.swing.text.GlyphPainter1.sync(GlyphPainter1.java:222)
    at javax.swing.text.GlyphPainter1.getSpan(GlyphPainter1.java:59)
    at javax.swing.text.GlyphView.getPreferredSpan(GlyphView.java:592)
    at javax.swing.text.FlowView$LogicalView.getPreferredSpan(FlowView.java:732)
    at javax.swing.text.FlowView.calculateMinorAxisRequirements(FlowView.java:233)
    at javax.swing.text.ParagraphView.calculateMinorAxisRequirements(ParagraphView.java:717)
    at javax.swing.text.BoxView.checkRequests(BoxView.java:935)
.
.
. (The exception is very long, so tell me if you need the full trace)

我做错了什么?

1 个答案:

答案 0 :(得分:5)

请勿尝试在单个语句中创建属性。

通过执行以下操作使编码更易于理解和维护:

SimpleAttributeSet error = new SimpleAttributeSet();
StyleConstants.setForeground(error, Color.RED);
StyleConstants.setBackground(error, Color.YELLOW);
StyleConstants.setBold(error, true);

...

doc.insertString(0, "...", error);