0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Javaで「パスワードフィールドに入力されたテキストを取得する」の動作を確認してみた。

Posted at

概要

Javaで「パスワードフィールドに入力されたテキストを取得する」の動作を確認してみました。
以下のページを参考にしました。

実装

以下のファイルを作成しました。

JSample2_1.java
import javax.swing.JFrame;
import javax.swing.JPasswordField;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import java.awt.Container;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

class JSample2_1 extends JFrame implements ActionListener{
  JPasswordField pass;

  public static void main(String args[]){
    JSample2_1 frame = new JSample2_1("MyTitle");
    frame.setVisible(true);
  }

  JSample2_1(String title){
    setTitle(title);
    setBounds(100, 100, 600, 400);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JLabel label = new JLabel("Enter your password");

    pass = new JPasswordField(30);

    JButton button = new JButton("Check");
    button.addActionListener(this);

    JPanel p = new JPanel();
    p.add(label);
    p.add(pass);
    p.add(button);

    Container contentPane = getContentPane();
    contentPane.add(p, BorderLayout.CENTER);
  }

  public void actionPerformed(ActionEvent e){
    String password = new String(pass.getPassword());

    if (password.equals("abcd")){
      JLabel label = new JLabel("Success");
      JOptionPane.showMessageDialog(this, label, "Success",
        JOptionPane.INFORMATION_MESSAGE);
    }else{
      JLabel label = new JLabel("Failure");
      JOptionPane.showMessageDialog(this, label, "Failure",
        JOptionPane.ERROR_MESSAGE);
      pass.setText("");
    }
  }
}

以下のコマンドを実行しました。

$ javac JSample2_1.java 
$ java JSample2_1

実行結果は以下の通りでした。

Screenshot from 2025-01-31 07-41-23.png

まとめ

何かの役に立てばと。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?