JTextField将用户输入保存为String

Tho*_*olz 1 java swing jframe actionlistener jtextfield

所以我试图创建一个登录屏幕,提示用户输入一个文本框和2个按钮(登录和取消).当用户点击登录时,我希望将值JTextField存储在变量中或至少可用.当我尝试对该playerNameTxt.getText()方法做任何事情时,我得到一个错误,好像playerNameTxt不存在一样.

public class GUI extends JPanel implements ActionListener {

protected JTextField playerNameTxt;

public GUI() {
    JTextField playerNameTxt = new JTextField(20);

    JLabel playerNameLbl = new JLabel("Enter Player Name");

    JButton loginBtn = new JButton("Login");
    loginBtn.setVerticalTextPosition(AbstractButton.BOTTOM);
    loginBtn.setHorizontalTextPosition(AbstractButton.LEFT);
    loginBtn.setMnemonic(KeyEvent.VK_D);
    loginBtn.setActionCommand("login");
    loginBtn.addActionListener(this);
    loginBtn.setToolTipText("Click this to Login");

    JButton cancelBtn = new JButton("Cancel");
    cancelBtn.setVerticalTextPosition(AbstractButton.BOTTOM);
    cancelBtn.setHorizontalTextPosition(AbstractButton.RIGHT);
    cancelBtn.setMnemonic(KeyEvent.VK_M);
    cancelBtn.setActionCommand("cancel");
    cancelBtn.addActionListener(this);
    cancelBtn.setToolTipText("Click this to Cancel");

    add(playerNameLbl);
    add(playerNameTxt);
    add(loginBtn);
    add(cancelBtn);
}

public void actionPerformed(ActionEvent e) {
    if ("login".equals(e.getActionCommand())) {
        System.out.println(playerNameTxt);
    } else {
        System.exit(0);
    }
}

private static void createAndShowGUI() {
    JFrame frame = new JFrame("-- Munitions Login --");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocation(400, 200);

    GUI newContentPane = new GUI();
    newContentPane.setOpaque(true);
    frame.setContentPane(newContentPane);

    frame.pack();
    frame.setVisible(true);
}

public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}
}
Run Code Online (Sandbox Code Playgroud)

msr*_*rd0 5

首先在构造函数之外声明该字段,然后再次在构造函数中声明它,以便在构造函数返回并且GUI被销毁后将其删除,并且在构造函数完成后它将无法用于您的类.你应该改变这一行:

JTextField playerNameTxt = new JTextField(20);
Run Code Online (Sandbox Code Playgroud)

对此:

playerNameTxt = new JTextField(20);
Run Code Online (Sandbox Code Playgroud)