【问题标题】:getting string from a textfield从文本字段中获取字符串
【发布时间】:2014-09-16 09:30:13
【问题描述】:

我正在使用 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 textField 不为空。

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

【问题讨论】:

  • 如果某个答案解决了您的问题,请考虑接受该特定答案。

标签: java string view textfield


【解决方案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());
    }
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-04
    相关资源
    最近更新 更多