【问题标题】:JTextPane change the font of a certain starting pointJTextPane 改变某个起点的字体
【发布时间】:2014-01-06 04:27:00
【问题描述】:

如何改变某个起点的字体?

我有一个按钮,在某个点切换字体。

例子:

somtext |

按下按钮

sometext 粗体文本|

所以我释放了事件键,但我可以看到不断变化的字体释放键

这是关键释放事件

         private void textoKeyReleased(javax.swing.event.CaretEvent evt)                  {                                  
          int end = texto.getSelectionEnd();
            StyledDocument doc = texto.getStyledDocument();

            Style style = texto.getStyle("negra");

        if (car==1) 
            {

            StyleConstants.setBold(style, true);
            doc.setCharacterAttributes(end-1,end, style, false);
            texto.requestFocus();
            texto.moveCaretPosition(doc.getLength());
            }
        if(car==0)
        {
            StyleConstants.setBold(style, false);
            doc.setCharacterAttributes(end-1 ,end, style, false);
            texto.requestFocus();
            texto.moveCaretPosition(doc.getLength());
        }  
    }

但我明白了

第一个

结局一个

更新不是实时的还有另一种方法:

【问题讨论】:

  • 如果您没有很快得到合适的答案,请考虑创建并发布sscce

标签: java swing jtextpane caret


【解决方案1】:

KeyListener 接口中按键释放事件的问题在于,只有在用户松开按键时才会调用它。在您的代码中,如果用户按住一个键重复它,则只会根据设置的样式修改最后一个字符。此外,在打字过程中,如果用户在释放第一个键之前按下了第二个键,那么只会更新最后一个字符。

另一种方法是在 KeyListener 接口的 keyTyped 方法中调用您的代码。

还稍微简化了代码。

private void textoKeyReleased(javax.swing.event.CaretEvent evt) {
    int end = textPane.getSelectionEnd();
    StyledDocument doc = textPane.getStyledDocument();

    Style style = textPane.getStyle("negra");
    StyleConstants.setBold(style, car == 1);
    doc.setCharacterAttributes(end - 1, 1, style, false);
    textPane.requestFocus();
}

@Override
public void keyTyped(KeyEvent e) {
    SwingUtilities.invokeLater(new Runnable() {         
        @Override
        public void run() {
            textoKeyReleased(null);
        }
    });
}

【讨论】:

    【解决方案2】:

    阅读 Text Component Features 上的 Swing 教程中的部分,它向您展示了如何为粗体属性创建 JMenuItem。相同的方法可用于 JButton,因为粗体 Action 也可用于按钮。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-09
      • 1970-01-01
      • 2020-06-09
      • 2016-12-16
      • 2012-06-16
      • 2013-10-27
      • 2012-08-22
      相关资源
      最近更新 更多