Cannot bind: field is static: form.MainForm.nameTextField

妖精的绣舞 提交于 2019-12-12 18:33:31

问题


I'm getting an error when I create static methods and call them in another class:

public static JTextField getNameTxtField(){
    return nameTxtField;
}
public static JTextField getNewUserNameTxtField(){
    return newUserNameTxtField;
}
public static JPasswordField getNewPasswordTextField(){
    return newPasswordTxtField;
}

All the above getters are located in the MainForm class and are called in the this class:

GameLogic:

public void addToDatabase() throws SQLException {
    controller.addUserToDatabase(MainForm.getNameTxtField().getText(),MainForm.getNewUserNameTxtField().getText(), String.valueOf(MainForm.getNewPasswordTextField()) , "insert into application_user values(?, ?, ?)");
}

Why am I getting the message? I don't really understand the message so can someone explain to me?

I can't create an object like this: MainForm form = new MainForm(); in the class GameLogic because I will get a StackOverflowError.

Does the problem occur because I call the static getters in a non-static method?


回答1:


Forget the statics. I assume what you're trying to do is reference an instance variable from one class into another. And your attempt is to use static variables. And you're getting stackoverflow because you're attempting something like this

public class MainForm ... {
    public MainForm() {
        GameForm game = new GameForm();
    }
}
public class GameForm ... {
    public GameForm() {
        MainForm main = new MainForm();
    }
}

This will definitely give you a stackoverflow because you create a GameForm which creates MainForm, which creates a GameForm, which creates a MainForm, which creates a GameForm, which creates a MainForm (get the point?), which creates a stackoverflow.

A solution is to pass MainForm to GameForm by reference and use getter and setters in MainForm where necessary. Something like

public class MainForm ... {
    private JTextField field;
    private GameForm game;

    public MainForm() {
        game = new GameForm(MainForm.this);
    }

    public JTextField getField (){
        return field;
    }
}

public class GameField ... {
    private MainForm main;
    private JTextField field;

    public GameForm(final MainForm main) {
        this.main = main;
        this.field = main.getField();
    }
}

Now, in GameForm you are referencing the same instance JTextField.


An even better, and probably more appropriate solution though, would be to use an interface and have MainForm implement it. You can see this answer for an example.




回答2:


getText() (called in addToUserDatabase()) is a non-static function. You can't reference something that's non-static from a static context.



来源:https://stackoverflow.com/questions/22584546/cannot-bind-field-is-static-form-mainform-nametextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!