概要

JPasswordFieldに入力したパスワードの表示・非表示を切り替えるためのボタンを作成し、これを入力欄などに配置します。

サンプルコード

JPasswordField pf = new JPasswordField(24);
pf.setText("abcdefghijklmn");
pf.setAlignmentX(Component.RIGHT_ALIGNMENT);
AbstractDocument doc = (AbstractDocument) pf.getDocument();
doc.setDocumentFilter(new ASCIIOnlyDocumentFilter());

AbstractButton b = new JToggleButton(new AbstractAction() {
  @Override public void actionPerformed(ActionEvent e) {
    AbstractButton c = (AbstractButton) e.getSource();
    pf.setEchoChar(c.isSelected()
      ? '\u0000'
      : (Character) UIManager.get("PasswordField.echoChar"));
  }
});
b.setFocusable(false);
b.setOpaque(false);
b.setContentAreaFilled(false);
b.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 4));
b.setAlignmentX(Component.RIGHT_ALIGNMENT);
b.setAlignmentY(Component.CENTER_ALIGNMENT);
b.setIcon(new EyeIcon(Color.BLUE));
b.setRolloverIcon(new EyeIcon(Color.DARK_GRAY));
b.setSelectedIcon(new EyeIcon(Color.BLUE));
b.setRolloverSelectedIcon(new EyeIcon(Color.BLUE));
b.setToolTipText("show/hide passwords");

JPanel panel = new JPanel() {
  @Override public boolean isOptimizedDrawingEnabled() {
    return false;
  }
};
panel.setLayout(new OverlayLayout(panel));
panel.add(b);
panel.add(pf);
View in GitHub: Java, Kotlin

解説

上記のサンプルでは、JPasswordField#setEchoChar(...)メソッドの値に\u0000(0)を設定して入力したパスワードを可視状態に切り替えるためのボタンを追加しています。

  • BorderLayout + JCheckBox:
    • BorderLayoutJPasswordFieldの下にパスワード表示非表示切り替え用のJCheckBoxを配置
  • OverlayLayout + JToggleButton:
    • OverlayLayoutJPasswordField内の右端にパスワード表示非表示切り替え用のJToggleButtonを配置
    • JPasswordFieldJToggleButtonを配置するJPanelOverlayLayoutを設定し、マウスカーソルでこのレイアウトのz軸が入れ替わらないようにJPanel#isOptimizedDrawingEnabled()が常にfalseを返すようオーバーライド
  • CardLayout + JTextField(can copy) + ...:
    • 同じDocumentを使用するJPasswordFieldJTextFieldCardLayoutを設定したJPanelを作成
    • OverlayLayoutを設定したJPanelに上記のJPanelJToggleButtonを配置し、JPasswordFieldなどの内部右端にボタンが表示されるように設定
    • JTextFieldをそのまま使用しているので表示中の文字列を選択してコピー可能
      JPasswordField pf3 = new JPasswordField(24);
      pf3.setText("abcdefghijklmn");
      AbstractDocument doc = (AbstractDocument) pf3.getDocument();
      JTextField tf3 = new JTextField(24);
      tf3.setFont(FONT);
      tf3.enableInputMethods(false);
      tf3.setDocument(doc);
      
      final CardLayout cardLayout = new CardLayout();
      final JPanel p3 = new JPanel(cardLayout);
      p3.setAlignmentX(Component.RIGHT_ALIGNMENT);
      p3.add(pf3, PasswordField.HIDE.toString());
      p3.add(tf3, PasswordField.SHOW.toString());
      
      AbstractButton b3 = new JToggleButton(new AbstractAction() {
        @Override public void actionPerformed(ActionEvent e) {
          AbstractButton c = (AbstractButton) e.getSource();
          PasswordField s = c.isSelected() ? PasswordField.SHOW
                                           : PasswordField.HIDE;
          cardLayout.show(p3, s.toString());
        }
      });
      
  • press and hold down the mouse button:
    • OverlayLayoutJPasswordField内の右端にパスワード表示非表示切り替え用のJButtonを配置
    • このJButtonMouseListenerを追加してマウスでクリックしている間はパスワードを表示するように設定
      b4.addMouseListener(new MouseAdapter() {
        @Override public void mousePressed(MouseEvent e) {
          pf4.setEchoChar('\u0000');
        }
        @Override public void mouseReleased(MouseEvent e) {
          pf4.setEchoChar((Character) UIManager.get("PasswordField.echoChar"));
        }
      });
      

  • passwordField.setEchoChar((char) 0);を使用するサンプルを追加
    • JPasswordField#setEchoChar(...) (Java Platform SE 8)に「値0に設定すると標準のJTextFieldの動作と同様にテキストが入力したとおりに表示されます。」とあるようにpasswordField.setEchoChar((char) 0);とすればパスワード文字列の表示が可能
    • CardLayoutを使ってJTextFieldを表示する方法は一旦削除したが、表示中のパスワードをコピー可能なので残しておくことにした
  • ボタンをクリックしている間だけパスワードを表示するサンプルを追加

参考リンク

コメント