简体   繁体   中英

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

        }
    });
}

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

the trouble here is that main method is static, a good workaround for this would be to create a class which implements Runnable and have its constructor accept the login information as arguments, in the run method, use the value obtained to set the text.

public class MyRunnable implements Runnable {

    private String user;

    public MyRunnable(final String user) {
        this.user = user;
    }

    @Override
    public void run() {
        // now use the user variable to set the text.
    }

}

in your main method say

 java.awt.EventQueue.invokeLater(new MyRunnable(user));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM