2つの異なるスタイルでjtextpaneを作成しました。1つは数字用(ピンクの前景)、残りはデフォルトのスタイル(黒の前景)です。新しい押された文字を処理するために、jtextpaneにkeylistener(KeyReleased関数を使用)を追加しましたが、書き込み中に問題が発生します。シナリオは次のとおりです。
- テキストは次のとおりです。こんにちは123
- また、「こんにちは」のテキストは黒で、数字の「123」はピンクです。
- これで、キャレットは「1」と「2」の間にあり、「a」を押して何か奇妙なことが発生します。
- 文字「a」はピンクになり、次に黒になります。
なぜ短時間黒くなるのですか?
KeyReleasedは次のように処理します。
- すべてのテキストをデフォルトのスタイルで設定しました(クリーンフェーズ)
- 前景を数字だけピンクに変更します
これは例です:
import java.awt.Color;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.StringTokenizer;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
public class Example extends JFrame {
JTextPane pn = new JTextPane();
public Example() {
addDefaultStyle(pn);
addNumberStyle(pn);
pn.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent arg0) {
String text = pn.getText();
pn.getStyledDocument().setCharacterAttributes(0, text.length(), pn.getStyle("default"), true);
StringTokenizer ts = new StringTokenizer(text, " ");
while(ts.hasMoreTokens()){
String token = ts.nextToken();
try{
Integer.parseInt(token);
pn.getStyledDocument().setCharacterAttributes(text.indexOf(token), token.length(), pn.getStyle("numbers"), true);
}catch(Exception e){
pn.getStyledDocument().setCharacterAttributes(text.indexOf(token), token.length(), pn.getStyle("default"), true);
}
}
}
});
getContentPane().add(pn);
setSize(400, 400);
setLocationRelativeTo(null);
setVisible(true);
}
private void addDefaultStyle(JTextPane pn){
Style style = pn.addStyle("default", null);
pn.setForeground(Color.blue);
pn.setBackground(Color.WHITE);
StyleConstants.setForeground(style, pn.getForeground());
StyleConstants.setBackground(style, pn.getBackground());
StyleConstants.setBold(style, false);
}
private void addNumberStyle(JTextPane pn){
Style style = pn.addStyle("numbers", null);
StyleConstants.setForeground(style, Color.PINK);
StyleConstants.setBackground(style, Color.WHITE);
StyleConstants.setBold(style, true);
}
public static void main(String args []){
new Example();
}
}