Search code examples
javaswingoopauthenticationjtextfield

Setting a JTextField's content using text from another java file


I am supposed to set the JTextField UserDisp's text to the username retrieved from a login form, but an error shows up. The variable user's value is from the username inputted into the login form.

The error shows: 'Non-static Variable UserDisp cannot be referenced from a static context'

The code is as follows:

public static void main(final String user) {

    //look and feel codes are omitted

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            String name = "Welcome "+user+"!";
            UserDisp.setText(name);
            new MainMenu().setVisible(true);

        }
    });
}

Solution

  • static variable initialized when class is loaded into JVM on the other hand instance variable has different value for each instances and they get created when instance of an object is created either by using new() operator or using reflection like Class.newInstance().

    So if you try to access a non static variable without any instance compiler will complain because those variables are not yet created and they don't have any existence until an instance is created and they are associated with any instance. So in my opinion only reason which make sense to disallow non static or instance variable inside static context is non existence of instance.

    So in your case you need to create MainNenu Object, then set the user name text, then show the menu.

    For Example:

     MainMenu menu = new MainMenu();
     menu.setUserDispNameText(name);
     menu.setVisible(true);
    

    Read more here