gpt4 book ai didi

java - JTextField 将用户输入保存为字符串

转载 作者:行者123 更新时间:2023-11-29 07:45:26 24 4
gpt4 key购买 nike

所以我试图创建一个登录屏幕,用文本框和 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();
}
});
}
}

最佳答案

你先在构造函数外面声明这个字段,然后在构造函数里面再声明一次,这样构造函数返回,GUI销毁后,它就会被删除,构造函数之后你的类就不能用了已完成。你应该改变这一行:

JTextField playerNameTxt = new JTextField(20);

为此:

playerNameTxt = new JTextField(20);

关于java - JTextField 将用户输入保存为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26283199/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com