-2

I'm creating a GUI with Swing. First of all I instance the class User and I initialize it. Then, depending on Action Listeners I call methods of this class. The problem is that I have different functions in my class GUI and when I call the methods of the class I have to use the instance created in the beggining. The problem is that I cannot set the User class instance as an attribute of my class GUI because is not static.

public class User{
    int id;
    public User(){
        id = 5;
    }
     public void setId(int a){
        id = a;
    }
}
public class Gui{
    User u;
    public static void main(String[] args){
         u = new User();
         ////////////////

         ////////////////
         doStuff();
    }
     public void doStuff() {
         u.setId(1);
    }
}     

How could I do something like this?

cruster946
  • 475
  • 2
  • 6
  • 16
  • 1
    Hint: you start doing ... less. Understanding the difference between static and non-static (and which one to use for what kind of purpose) is very basic stuff. Seriously: if you don't know such things ... then do not get into UI application programming. You should learn to walk; instead of trying to learn how to juggle with 3 balls whilst at the same time trying to learn to ride the unicycle. Meaning: focus on the base language stuff of java. And then, move forward. – GhostCat Jun 07 '16 at 09:12
  • Thanks, I'm trying to think in Java. – cruster946 Jun 07 '16 at 09:29
  • All I am saying is: thinking will be easier, if you focus on **one** aspect at a time. Not multiple. GUI programming by itself is an advanced topic. – GhostCat Jun 07 '16 at 09:32

1 Answers1

1

Within your main function, you should create a (public) instance of your Gui class.
Then do whatever you want, referring to that instance.

Robert Kock
  • 5,795
  • 1
  • 12
  • 20