如何在JTextPane中为文本设置StrikeThrough和Underline样式选项?

时间:2013-11-25 22:34:54

标签: java swing jeditorpane

我有一个JTextPane组件,我正在尝试将用户键入的文本设置为同时加下划线和删除线。

应将下一个类型字符的删除线属性设置为true的相关代码片段为:

JEditorPane editor = getEditor(e);
if (editor != null) {
     StyledEditorKit kit = getStyledEditorKit(editor);
     MutableAttributeSet attr = kit.getInputAttributes();            
     SimpleAttributeSet sas = new SimpleAttributeSet();
     StyleConstants.setStrikeThrough(sas, true);                
     setCharacterAttributes(editor, sas, false);
}

这样可以将文本设置为删除线,但如果它已经设置为下划线,则会丢失下划线样式信息。仔细看看StyleConstants.setStrikeThrough(...)背后的实际代码我注意到下划线和删除线属性的CSS样式标签将是相同的(即“文本装饰”)并且当值更新时保存属性的哈希表,它将被覆盖。

这意味着代码如下:

StyleConstants.setStrikeThrough(sas, true);
StyleConstants.setUnderlineThrough(sas, true);

将导致下一个键入的字符加下划线而没有删除线。我检查了属性值,对于“text-decoration”属性,值是“下划线”,而我期待“直通,下划线”。

有没有人知道如何以一种干净的Swing兼容方式实现这一目标?我的方法有问题吗?在JTextPane样式的核心是否存在一个潜在的假设,即文本不应该同时删除并强调下划线?

1 个答案:

答案 0 :(得分:6)

为什么不使用StyledDocument并使用两个Styleprimarysecondary,其中primarysecondary的父样式:< / p>

enter image description here

  StyledDocument styleDocument =  jTextPane1.getStyledDocument();
  Style primaryStyle = styleDocument.addStyle("Primary", null);
  Style secondaryStyle = styleDocument.addStyle("Secondary", primaryStyle);


  StyleConstants.setFontFamily(primaryStyle, "American Captain");
  StyleConstants.setFontSize(primaryStyle, 24);

//  StyleConstants.setFontFamily(secondaryStyle, "Bira PERSONAL USE ONLY");
  StyleConstants.setFontSize(secondaryStyle, 20);
  StyleConstants.setForeground(primaryStyle, new Color(0x552AFF));
  StyleConstants.setForeground(secondaryStyle, Color.black);
  StyleConstants.setStrikeThrough(secondaryStyle, true);
  StyleConstants.setUnderline(primaryStyle, true);

  try {
      styleDocument.insertString(0, "Title with American Captain font\n\n", primaryStyle);
      styleDocument.insertString(styleDocument.getLength(), "Font demonstration with JTextPane. "
              + "Seriously, it is powerful and has the power to do all kind of styling with text. "
              + "check it out, check its mighty power and be embrassed\n", secondaryStyle);
   } catch (BadLocationException ex) {
                Logger.getLogger(JTextPaneTest.class.getName()).log(Level.SEVERE, null, ex);
   }

修改:

  

想象你有4个切换按钮 - 斜体,粗体,下划线和   删除线。每当其中一个被按下或未按下时我需要   根据角色的需要调整样式   键入下一个。

是的,答案仍然在于使用DefaultStyleDocument并扩展它的偏好。上面的示例应该说明在使用Style方法插入字符串时,styleDocument.insertString(int offs, String str, AttributeSet a)的样式是如何工作的。当我们使用KeyBoardcopy-paste插入数据时,始终会调用关联StyleDocument的{​​{1}}函数。

因此,要像文本编辑器一样设置样式,您只需要扩展insertString并覆盖此DefaultStyleDocument函数并传递所需的特定样式属性。

满足您完整要求的演示示例应该明确这一点。

enter image description here

insertString