考虑以下代码:

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)


我究竟做错了什么?

最佳答案

不要尝试在单个语句中创建属性。

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

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

...

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

关于java - 使用StyleConstants.Bold时AttributeSet引发错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36268703/

10-12 05:51