• 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: https://lh4.googleusercontent.com/-N1aQ1F9Zrn8/UReetdvfWQI/AAAAAAAABdc/9J_2lkAgW0Y/s800/TextFieldOnReadOnlyTextPane.png

概要

JTextFieldを空欄として編集不可にしたJTextPaneに追加します。

サンプルコード

#spandel
void insertQuestion(final JTextPane textPane, String str) {
#spanend
#spanadd
private static void insertQuestion(JTextPane textPane, String str) {
#spanend
  Document doc = textPane.getDocument();
  try {
    doc.insertString(doc.getLength(), str, null);
    final int pos = doc.getLength();
#spanadd

#spanend
    int pos = doc.getLength();
    System.out.println(pos);
    final JTextField field = new JTextField(4) {
    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) {
          ex.printStackTrace();
          // 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);

    SimpleAttributeSet a = new SimpleAttributeSet();
    // 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 e) {
    e.printStackTrace();
  } catch (BadLocationException ex) {
    // should never happen
    RuntimeException wrap = new StringIndexOutOfBoundsException(
        ex.offsetRequested());
    wrap.initCause(ex);
    throw wrap;
  }
}
View in GitHub: Java, Kotlin

解説

上記のサンプルでは、編集不可状態のJTextPane内の文字列中に編集可能なJTextFieldJTextPane#insertComponent(...)を使用メソッドを使用して追加しています。 上記のサンプルでは、編集不可状態のJTextPane内の文字列中に編集可能なJTextFieldJTextPane#insertComponent(...)メソッドを使用して追加しています。

参考リンク

コメント