Swing/TextFieldOnReadOnlyTextPane のバックアップ(No.14)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/TextFieldOnReadOnlyTextPane へ行く。
- 1 (2013-02-11 (月) 00:11:13)
- 2 (2013-07-26 (金) 01:32:11)
- 3 (2013-08-20 (火) 14:27:07)
- 4 (2014-12-28 (日) 15:06:05)
- 5 (2016-03-04 (金) 13:38:36)
- 6 (2016-11-07 (月) 03:24:36)
- 7 (2017-08-09 (水) 12:59:27)
- 8 (2018-08-10 (金) 16:16:55)
- 9 (2020-08-09 (日) 04:32:15)
- 10 (2022-01-02 (日) 17:38:00)
- 11 (2025-01-03 (金) 08:57:02)
- 12 (2025-01-03 (金) 09:01:23)
- 13 (2025-01-03 (金) 09:02:38)
- 14 (2025-01-03 (金) 09:03:21)
- 15 (2025-01-03 (金) 09:04:02)
- category: swing
folder: TextFieldOnReadOnlyTextPane
title: JTextFieldを編集不可のJTextPaneに追加する
tags: [JTextPane, JTextField, JScrollPane, Focus]
author: aterai
pubdate: 2013-02-11T00:11:13+09:00
description: JTextFieldを空欄として編集不可にしたJTextPaneに追加します。
image:
Summary
JTextField
を空欄として編集不可にしたJTextPane
に追加します。
Screenshot

Advertisement
Source Code Examples
private static void insertQuestion(JTextPane textPane, String str) {
Document doc = textPane.getDocument();
try {
doc.insertString(doc.getLength(), str, null);
int pos = doc.getLength();
System.out.println(pos);
JTextField field = new JTextField(4) {
@Override public Dimension getMaximumSize() {
return getPreferredSize();
}
};
field.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));
field.addFocusListener(new FocusAdapter() {
@Override public void focusGained(FocusEvent e) {
try {
Rectangle rect = textPane.modelToView(pos);
rect.grow(0, 4);
rect.setSize(field.getSize());
// System.out.println(rect);
// System.out.println(field.getLocation());
textPane.scrollRectToVisible(rect);
} catch (BadLocationException ex) {
// should never happen
RuntimeException wrap = new StringIndexOutOfBoundsException(
ex.offsetRequested());
wrap.initCause(ex);
throw wrap;
}
}
});
Dimension d = field.getPreferredSize();
int baseline = field.getBaseline(d.width, d.height);
field.setAlignmentY(baseline / (float) d.height);
// MutableAttributeSet a = new SimpleAttributeSet();
MutableAttributeSet a = textPane.getStyle(StyleContext.DEFAULT_STYLE);
StyleConstants.setLineSpacing(a, 1.5f);
textPane.setParagraphAttributes(a, true);
textPane.insertComponent(field);
doc.insertString(doc.getLength(), "\n", null);
} catch (BadLocationException ex) {
// should never happen
RuntimeException wrap = new StringIndexOutOfBoundsException(
ex.offsetRequested());
wrap.initCause(ex);
throw wrap;
}
}
View in GitHub: Java, KotlinExplanation
上記のサンプルでは、編集不可状態のJTextPane
内の文字列中に編集可能なJTextField
をJTextPane#insertComponent(...)
メソッドを使用して追加しています。
JTextPane
- 編集不可に設定
- 行間を
1.5
倍に設定
JTextField
JTextField#getMaximumSize()
をオーバーライドして幅を制限JTextField
にMatteBorder
を設定して下線のみの空欄を表示JTextField#setAlignmentY(...)
でベースラインを揃えるJTextField
にFocusListener
を追加してTabキーなどでFocus
が移動したら、そのJTextField
までスクロールするように設定