私はSwingを使ってJavaでテキストエディタを書いています。私がテキストを入力するために使用する主なコンポーネントはJTextPaneです。私は選択されたテキストを太字にする方法を知っていますが、太字を押して新しいテキストをフォーマットしたいだけです。ここに私のコードは次のとおりです。Swingを使ってJavaで太字で書く
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 、それは私が何をしたいです:JTextPane
インクルードは、エディタによって使用される可能性のある他の一般的なアクションと一緒に大胆Action
をサポートしていますが使用し Entering bolded text
すぐに役立つようにするには、[MCVE]または[短く、自己完結型の正しい例](http://www.sscce.org/)を投稿してください。 –
あなたはあなたが "太字"の状態にあるかどうかをチェックし、それが入力された文字に適用されるアクションリスナーを探しているでしょう – Rogue