独自のコンポーネントを作成する必要はありません。
これは、私が行ったように、カスタムDocumentFilterを使用して行うことができます。
textPane.getDocument()
からドキュメントを入手し、document.setFilter()
でフィルタを設定することができます。フィルタ内でプロンプトの位置を確認し、その位置がプロンプトの後にある場合にのみ変更を許可することができます。例えば
:
private class Filter extends DocumentFilter {
public void insertString(final FilterBypass fb, final int offset, final String string, final AttributeSet attr)
throws BadLocationException {
if (offset >= promptPosition) {
super.insertString(fb, offset, string, attr);
}
}
public void remove(final FilterBypass fb, final int offset, final int length) throws BadLocationException {
if (offset >= promptPosition) {
super.remove(fb, offset, length);
}
}
public void replace(final FilterBypass fb, final int offset, final int length, final String text, final AttributeSet attrs)
throws BadLocationException {
if (offset >= promptPosition) {
super.replace(fb, offset, length, text, attrs);
}
}
}
しかし、これはプログラム端子の出力(編集不可)セクションにコンテンツを挿入できなくなります。代わりに、出力を追加しようとしているときに設定したフィルタのパススルーフラグか、出力を追加する前に文書フィルタをnullに設定してから、再実行されます。
textArea.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent event) {
int code = event.getKeyCode();
int caret = textArea.getCaretPosition();
int last = textArea.getText().lastIndexOf(">> ") + 3;
if(caret <= last) {
if(code == KeyEvent.VK_BACK_SPACE) {
textArea.append(" ");
textArea.setCaretPosition(last + 1);
}
textArea.setCaretPosition(textArea.getText().length());
}
}
});
(AbstractDocument)jta.getDocument())。setDocumentFilter(dfilter); –