简体   繁体   中英

How to access to the value inside a Swing JTextField/JPasswordField?

I am pretty new in Java Swing development and I have the following problem.

I have a custom LoginFrame that extends a classic JFrame Swing class to create a login windows in which the user insert its username and password.

Inside this class I have something like this:

externalPanel.setLayout(new net.miginfocom.swing.MigLayout("fill"));    
    externalPanel.add(new JLabel("Username"), "w 50%, wrap");
    JTextField userNameTextField = new JTextField(20);    
    externalPanel.add(userNameTextField, "w 90%, wrap");    
    externalPanel.add(new JLabel("Password"), "w 50%, wrap");
    // JTextField pswdTextField = new JTextField(20);
    JPasswordField pswdTextField = new JPasswordField(20);
    externalPanel.add(pswdTextField, "w 90%, wrap");    
    JButton loginButton = new JButton("Login");
    // loginButton.setActionCommand("loginAction");
    loginButton.addActionListener(this);

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        System.out.println("Button LogIn cliccked");    
        firePropertyChange("loginResult", false, loginResult);    
    }

As you can see I have the actionPerformed that is executed when the user click the JButton loginButton object.

Ok, my problem is: From inside the actionPerformed()^^ method how can I access to the values inserted in my **JTextField userNameTextField and JPasswordField pswdTextField ?

What have I to do?

Tnx

Andrea

Declare JTextField userNameTextField, JPasswordField pswdTextField, JButton loginButton as globel. Then you can get values like this..

@Override
public void actionPerformed(ActionEvent e) {
    if(e.getSource() == loginButton){
         String name = userNameTextField.getText();
         char[] pass = pswdTextField.getPassword();
         // your remaining operation...
    }

}

For JTextField: jTextField.getText() ---> returns String

For JPasswordField: jPasswordField.getPassword() ----> returns char[]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM