'Unable to call getText() on JTextField object

I am having trouble calling the getText() method on a JTextField object. First, I called panel.getComponent(2) because the second component that I added to panel was the username text field, which I confirmed by running my application and "username" was being printed in the console. This is where I sort of got lost because I knew that this returned the username text component, so I'm confused why when I get an error when I try to call getText(). Does anyone know why this is?

Here is my code:

// MODIFIES: this
// EFFECTS: creates username text field
private void makeUsernameTextField() {
    JTextComponent username = new JTextField();
    username.setName("username");
    username.setBounds(width / 2 - borderThickness - userFieldW / 2,
            height / 2 - borderThickness - textFieldH / 2, textFieldW, textFieldH);
    username.setOpaque(true);
    panel.add(username);
}

@Override
public void actionPerformed(ActionEvent e) {
    String username = panel.getComponent(2).getText();
    String action = e.getActionCommand();

    if (action == "login") {
        login.signIn(username);
        System.out.println(username);
        System.out.println("succesful!");
    } else if (action == "sign up") {
        System.out.println("sign up pressed");
    }
}


Solution 1:[1]

I get an error when I try to call getText()

String username = panel.getComponent(2).getText();

The getComponent() method returns a Component which does not have a getText() method.

You need to cast the object to a JTextField:

Component component= panel.getComponent(2); // or 1 if it really is the second component
JTextField textField = (JTextField)component;
String username = textField.getText();

Also:

if (action == "login") 

Don't use "==" for string comparison.

Insetead use the equals(...) method:

if (action.equals("login")) 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 camickr