简体   繁体   中英

How to get the value of JTextField in Java Swing?

I have a JTextField and a JButton. I'm trying to get what user types in the textfield when they click the button.

public String insideTextField;

public void login() {

    loginFrame = new JFrame("Test");
    loginFrame.setIconImage(imageIcon.getImage());
    loginFrame.setSize(400,400);
    loginFrame.setLayout(new GridLayout(12, 3));

    loginFrame.add(usernameField);
    loginFrame.add(loginButton);

    loginButton.addActionListener(e -> {

        insideTextField = usernameField.getText();
        loginFrame.setVisible(false);
    });

    loginFrame.setVisible(true);
}

and I expect the insideTextField to be what user types in the text field after I called this method. but it is null. However, the loginFrame will be hidden because of loginFrame.setVisible(false); so the button is working !

what am I doing wrong?

Your expectations involve magical thinking. Understand that insideTextField holds a String object, an object which in fact is immutable (cannot be changed). Yes, when you create the insideTextField you assign to it the String that just so happens to be residing within the JTextField, likely an empty "" String, but understand that when the JTextField's text properties change, the insideTextField will not, and in fact cannot magically change on its own. The solution is to not have a insideTextField field, and instead give the class a getter method that extracts the current String within the JTextField when it is needed. For example:

public String getUserName() {
    return usernameField.getText();
}

Side note: I usually use a modal JDialog and not a JFrame to get log-in credentials. This way since the dialog is modal, I know when the user is done using it. And in fact a JOptionPane works as a quick and dirty modal dialog creator. For example if we had a login JPanel like so:

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

@SuppressWarnings("serial")
public class LoginPanel extends JPanel {
    private static final int GAP = 3;
    private JTextField usernameField = new JTextField(10);
    private JPasswordField passwordField = new JPasswordField(10);

    public LoginPanel() {
        setLayout(new GridBagLayout());
        GridBagConstraints gbc = getGbc(0, 0);
        add(new JLabel("User Name:"), gbc);
        gbc = getGbc(1, 0);
        add(usernameField, gbc);
        gbc = getGbc(0, 1);
        add(new JLabel("Password:"), gbc);
        gbc = getGbc(1, 1);
        add(passwordField, gbc);
        setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
    }

    private static GridBagConstraints getGbc(int x, int y) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.insets = new Insets(GAP, GAP, GAP, GAP);
        gbc.anchor = x == 0 ? GridBagConstraints.WEST : GridBagConstraints.EAST;        

        return gbc;
    }

    public String getUserName() {
        return usernameField.getText();
    }

    public char[] getPassword() {
        return passwordField.getPassword();
    }
}

again one that uses getter methods to extract the text in the JTextField, we could display it in a JOptionPane like so:

JFrame frame = new JFrame("LoginExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// fill the JFrame with the main GUI
// .... 

frame.pack();

// create the LoginPanel JPanel here
LoginPanel loginPanel = new LoginPanel();

// and display it in a JOptionPane here
int result = JOptionPane.showConfirmDialog(frame, loginPanel, 
        "User Log-In", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
    String userName = loginPanel.getUserName();
    char[] password = loginPanel.getPassword();

    // test to make sure code is working
    System.out.println("User Name: " + userName);

    // check for name/password validity here
    // ... if name/password OK, then show JFrame:
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

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