有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从文本字段获取字符串

我正在使用java,我有一个视图类和另一个试图从视图类的文本字段中获取字符串的类。下面是我的观点课:

public class LoginView extends JFrame {

private static final long serialVersionUID = -7284396337557548747L;
private JTextField nameTxt = new JTextField(10);
private JTextField passwordTxt = new JTextField(10);
private JButton loginBtn = new JButton("Giriş");

public LoginView() {
    JPanel loginPanel = new JPanel();

    this.setSize(600,200);
    this.setLocation(600, 300);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    loginBtn.setBounds(200, 270, 100, 50);

    loginPanel.add(nameTxt);
    loginPanel.add(passwordTxt);
    loginPanel.add(loginBtn);

    this.add(loginPanel);
}
public void LoginBtnListener(ActionListener btnListener) {
    loginBtn.addActionListener(btnListener);
}

public String getName() {
    return nameTxt.getText();
}

我的actionlistener和其他类方法工作正常,但我的“getName()”方法返回null,即使我的nameTxt文本字段不是空的

我是java新手,所以如果这是一个简单的问题,我很抱歉,但这花了我很多时间。谢谢!


共 (1) 个答案

  1. # 1 楼答案

    public class LoginView extends JFrame implements ActionListener {
    
        private static final long serialVersionUID = -7284396337557548747L;
        private JTextField nameTxt = new JTextField(10);
        private JTextField passwordTxt = new JTextField(10);
        private JButton loginBtn = new JButton("Giriş");
    
        public LoginView() {
            JPanel loginPanel = new JPanel();
    
            this.setSize(600,200);
            this.setLocation(600, 300);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            loginBtn.setBounds(200, 270, 100, 50);
    
            loginPanel.add(nameTxt);
            loginPanel.add(passwordTxt);
            loginPanel.add(loginBtn);
    
            this.add(loginPanel);
            this.setVisible(true);
            loginBtn.addActionListener(this);
        }
    
        public String getName() {
            return nameTxt.getText();
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println(getName());
        }
    }
    

    我错过了你的听众电话,所以我加了一个。这会打印出预期的结果。我也错过了你的电话