[英]How to strikethrough selected text in JTextPane? (java)
标题说明了一切。 假设我有一个带有“Strikethrough selected text”选项的右键菜单。 当我在jtextpane中选择了一些文本时,右键单击 - >“删除所选文本”,所选文本将被删除。
有任何想法吗?
Swing文本组件使用Actions
来提供文本窗格的各种格式设置功能。
以下是StyledEditorKit
的UnderlineAction
的代码。
public static class UnderlineAction extends StyledTextAction {
/**
* Constructs a new UnderlineAction.
*/
public UnderlineAction() {
super("font-underline");
}
/**
* Toggles the Underline attribute.
*
* @param e the action event
*/
public void actionPerformed(ActionEvent e) {
JEditorPane editor = getEditor(e);
if (editor != null) {
StyledEditorKit kit = getStyledEditorKit(editor);
MutableAttributeSet attr = kit.getInputAttributes();
boolean underline = (StyleConstants.isUnderline(attr)) ? false : true;
SimpleAttributeSet sas = new SimpleAttributeSet();
StyleConstants.setUnderline(sas, underline);
setCharacterAttributes(editor, sas, false);
}
}
}
所以基本上你需要通过替换“下划线”StyleConstants方法来创建自己的“StrikeThroughAction”来使用“删除线”StyleConstants方法。
创建Action之后,您可以通过使用Action创建JMenuItem或JButton来使用Action。 单击该组件后,将通过属性添加到所选文本中。
在您的右键单击操作中
objJTextPane.setContentType( "text/html" );
String[] args = objJTextPane.getText().split(objJTextPane.getSelectedText());
objJTextPane.setText("<strike>" + objJTextPane.getSelectedText() + "</strike>"+ args[1].toString());
在分裂字符串中应用你的逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.