2017-09-18 3 views
0

JTextPaneフォントの色に問題があり、解決策が見つからないようです。 ユーザーがテキストを入力するテキストボックス(JTextPane)があります。ある時点で、彼はいくつかの単語の色を変えるボタンを押す。JTextPaneのフォント色を変更して古いもので書き込む

SimpleAttributeSet attr = new SimpleAttributeSet(); 
StyleConstants.setBackground(attr, Color.RED); 
StyledDocument doc = inputArea.getStyledDocument(); 
//find the start of the word 
String wholeText = inputArea.getText(); 
int i = 0; 
while (i <= wholeText.length() - word.length()) { 
    if (wholeText.substring(i, i + word.length()).equals(word)) { 
     doc.setCharacterAttributes(i, word.length(), attr, false); 
    } 
    i ++; 
} 

問題は今、ユーザーが戻ってテキストを書くに返した場合、この単語は、テキストから最後のものであれば、新たに入力したテキストは、黒、赤ではないということです。私はそれを理解しようと2時間を費やしましたが、運はありません。

編集:私はまた、ハイライターを使ってみましたが、問題は同じです。

// Newly typed text at the end of the document will inherit the 
// "keyword" attributes unless we remove the attributes 

textPane.setCaretPosition(doc.getLength()); 
textPane.getInputAttributes().removeAttributes(keyWord); 

答えて

0

私が文書に属性を持つテキストを挿入した後にする前に、次のコードを使用してきました。 上記の解決策でも、ハイライトされた単語をクリックして文字を追加した場合、キャレットは赤くなり、何も修正されません。

inputArea.addKeyListener(new KeyListener() { 
     @Override 
     public void keyTyped(KeyEvent e) { 
      StyleConstants.setForeground(blackColor, Color.BLACK); 

      inputArea.setCharacterAttributes(blackColor, false); 

     } 

     @Override 
     public void keyPressed(KeyEvent e) { 

     } 

     @Override 
     public void keyReleased(KeyEvent e) { 

     } 
    }); 

黒い色は種類はSimpleAttributeSetである場合は:私は、テキスト・ペインに、私はこれをしなかった各キーストロークのキーリスナーを追加した理由である

。これはあまりエレガントではないかもしれませんが、それを解決します。

+0

keyWordとは何ですか? –

+0

さて、それを得ました。それは部分的に問題を解決しますが、私はここから管理できると思います。 –

0

[OK]をので、私はので、私は私の解決策を掲載する予定それを考え出し:

関連する問題