Koray Durudogan
Koray Durudogan

Reputation: 634

getting string from a textfield

i am using java and i have a view class and an other class that tries to get a string from view class's textfield.Here is my view class:

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();
}

my actionlistener and other class methods are working fine but my "getName()" method returns null even if my nameTxt textField is not empty.

I am new in java so i am sorry if it's an easy question but it took my time really much.Thank you

Upvotes: 0

Views: 83

Answers (1)

stealthjong
stealthjong

Reputation: 11093

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());
    }
}

I was missing your listener call, so I added it. This prints expected results. I was also missing your setVisible call.

Upvotes: 1

Related Questions