2010-02-10 58 views
2

我有文本面板正在生成。我需要在文本被选中时对文本进行重写,并且在点击上标按钮期间,我需要上标文本。如果文本已经被上标,它需要对文本进行不记录。我的问题是我能够上标文字,但无法恢复。我正在检查isSuperscript条件,但每次它返回值为true并将文本设置为上标。下面是我使用的代码,谁能告诉我如何重置上标文本。SWING:无法重置字体上标

SimpleAttributeSet sasText = new SimpleAttributeSet(parentTextPane.getCharacterAttributes()); 
System.out.println("character set 1 " + sasText.toString()); 

if (StyleConstants.isSuperscript(sasText)){ 
    System.out.println("already super"); 
    StyleConstants.setSuperscript(sasText, false); 
} else { 
    System.out.println("needs super"); 
    StyleConstants.setSuperscript(sasText, true);  
} 

int caretOffset = parentTextPane.getSelectionStart(); 

parentTextPane.select(caretOffset, caretOffset + textLength); 
HTMLDoc.setCharacterAttributes(selStart,textLength,sasText, false); 

parentEkit.refreshOnUpdate(); 

回答

0

它适用于我。我做一个快速的测试与类似的代码:

SimpleAttributeSet green = new SimpleAttributeSet(); 
System.out.println(StyleConstants.isSuperscript(green)); 
StyleConstants.setForeground(green, Color.GREEN); 
StyleConstants.setSuperscript(green, true); 
System.out.println(StyleConstants.isSuperscript(green)); 
StyleConstants.setSuperscript(green, false); 
System.out.println(StyleConstants.isSuperscript(green)); 

,并得到输出:

false 
true 
false 

这证明属性是正确复位。文字也正确显示。

如果在测试上标属性时,您的“sasText”总是返回true,那么您必须在代码中的其他位置重置该属性。

如果您需要更多帮助,请发送您的SSCCE显示问题。

1

问题是parentTextPane.getCharacterAttributes()将返回当前插入符号位置后字符的字符属性。由于您的选择包含上标文字,因此以下字符是正常的。它是您正在测试的下列字符的属性,结果将是false。你必须做的选择是什么getCharacterAttributes()(从JTextPane):

public AttributeSet getCharacterAttributes() { 
    StyledDocument doc = getStyledDocument(); 
    Element run = doc.getCharacterElement(getCaretPosition()); 
    if (run != null) { 
     return run.getAttributes(); 
    } 
    return null; 
} 
除非你想回到你的选择开始

public AttributeSet getMyCharacterAttributes() { 
    StyledDocument doc = parentTextPane.getStyledDocument(); 
    Element run = doc.getCharacterElement(parentTextPane.getSelectionStart()); 
    if (run != null) { 
     return run.getAttributes(); 
    } 
    return null; 
} 

您的代码将然后改做类似下面的:

SimpleAttributeSet sasText = new SimpleAttributeSet(getMyCharacterAttributes()); 
//... the rest of your code 
+0

非常感谢AKF。我有一种感觉,这是关于这个getCharacterAttribute(),但没有适当的技能来改变它。 – user234852 2010-02-11 02:56:16