【问题标题】:Writing with bold in Java using Swing使用 Swing 在 Java 中用粗体书写
【发布时间】:2016-12-03 04:33:06
【问题描述】:

我正在用 Java 编写一个文本编辑器,使用 Swing。我用来输入文本的主要组件是 JTextPane。我知道如何加粗所选文本,但我也想按粗体并格式化新文本。这是我的代码:

static void boldSelection(JTextPane editor, JButton button){
    StyledDocument doc = (StyledDocument) editor.getDocument();
    int selectionEnd = editor.getSelectionEnd();
    int selectionStart = editor.getSelectionStart();
    if (selectionStart == selectionEnd) {
      return;
    }
    Element element = doc.getCharacterElement(selectionStart);
    AttributeSet as = element.getAttributes();

    MutableAttributeSet asNew = new SimpleAttributeSet(as.copyAttributes());
    StyleConstants.setBold(asNew, !StyleConstants.isBold(as));
    doc.setCharacterAttributes(selectionStart, editor.getSelectedText().length(), asNew, true);
}

它有效,但我不知道如何更改它,因为我必须将长度传递给 setCharacterAttributes。 要清楚: 这就是我所拥有的: Bolding selected text 这就是我想要做的: Entering bolded text

【问题讨论】:

标签: java swing jtextpane bold


【解决方案1】:

JTextPane 使用的EditorKit 支持粗体Action 以及编辑器可能使用的其他常见操作。所以不需要写什么特殊的代码,只需要创建一个Swing组件就可以使用Action

查看 Text Component Features 上的 Swing 教程中的部分以获取工作示例。

教程示例仅使用菜单项,但您也可以使用Action 创建JButton 以添加到JToolBar

【讨论】:

  • 这正是我一直在寻找的。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-23
  • 2017-04-03
  • 1970-01-01
  • 1970-01-01
  • 2014-03-06
  • 2019-12-10
  • 1970-01-01
相关资源
最近更新 更多