概要

JTextFieldにフォーカスが無く文字列が空の場合、薄い色でその説明を表示します。

サンプルコード

class PlaceholderFocusListener implements FocusListener {
  private static final Color INACTIVE
    = UIManager.getColor("TextField.inactiveForeground");
  private final String hintMessage;

  public PlaceholderFocusListener(JTextComponent tf) {
    hintMessage = tf.getText();
    tf.setForeground(INACTIVE);
  }

  @Override public void focusGained(FocusEvent e) {
    JTextComponent tf = (JTextComponent) e.getComponent();
    if (hintMessage.equals(tf.getText())
        && INACTIVE.equals(tf.getForeground())) {
      tf.setForeground(UIManager.getColor("TextField.foreground"));
      tf.setText("");
    }
  }

  @Override public void focusLost(FocusEvent e) {
    JTextComponent tf = (JTextComponent) e.getComponent();
    if ("".equals(tf.getText().trim())) {
      tf.setForeground(INACTIVE);
      tf.setText(hintMessage);
    }
  }
}
View in GitHub: Java, Kotlin

解説

上記のサンプルでは、JTextFieldからフォーカスが失われた時にまだ何も入力されていない場合はそのJTextFieldの説明などを透かし文字として薄く表示しています。


  • Java 1.7.0以上の場合JLayerを使用して同様にヒント文字列を描画可能
class PlaceholderLayerUI extends LayerUI<JTextComponent> {
  private static final Color INACTIVE = UIManager.getColor("TextField.inactiveForeground");
  private final JLabel hint;

  public PlaceholderLayerUI(String hintMessage) {
    super();
    this.hint = new JLabel(hintMessage);
    hint.setForeground(INACTIVE);
  }

  @Override public void paint(Graphics g, JComponent c) {
    super.paint(g, c);
    if (c instanceof JLayer) {
      JLayer jlayer = (JLayer) c;
      JTextComponent tc = (JTextComponent) jlayer.getView();
      if (tc.getText().length() == 0 && !tc.hasFocus()) {
        Graphics2D g2 = (Graphics2D) g.create();
        g2.setPaint(INACTIVE);
        Insets i = tc.getInsets();
        Dimension d = hint.getPreferredSize();
        SwingUtilities.paintComponent(g2, hint, tc, i.left, i.top, d.width, d.height);
        g2.dispose();
      }
    }
  }

  @Override public void installUI(JComponent c) {
    super.installUI(c);
    if (c instanceof JLayer) {
      ((JLayer) c).setLayerEventMask(AWTEvent.FOCUS_EVENT_MASK);
    }
  }

  @Override public void uninstallUI(JComponent c) {
    super.uninstallUI(c);
    if (c instanceof JLayer) {
      ((JLayer) c).setLayerEventMask(0);
    }
  }

  @Override public void processFocusEvent(FocusEvent e, JLayer<? extends JTextComponent> l) {
    l.getView().repaint();
  }
}

参考リンク

コメント