概要
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
実行結果は以下の通りでした。
まとめ
何かの役に立てばと。