Initializing new variable for entire class

Hello!

I have a variable like this:

Server srv = new Server(5154);

I want this srv variable to be accessible from all methods of my class...
Server is another class...

I'm on another class using Server class...

I want to use this srv variable for example in method JButton1 Click and on JButton2 Click.

Thanks
LVL 17
CSecurityAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
objectsConnect With a Mentor Commented:
the other way twould be to make it a member var or your class, and have both listeners as inner classes of that class

public class MyClass
{
   public Server srv;

   .....

   button1.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
         srv = new Server(5154);
         ...
      }});

   button2.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
         srv.doSomething();
         ...
      }});
0
 
CEHJCommented:
Just make it an instance variable of your class. It will be visible from every method
0
 
objectsCommented:
public class MyClass
{
   public static Server srv = new Server(5154);

   .....




You can then access it using:

Server srv = MyClass.srv;
0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
CSecurityAuthor Commented:
Look.

Assume I have 2 methods Button1 Clicked and Button2 Clicked.

When I press Button1 the variable gets initilized.

And I want to initilaize it in a way that I can call it from Button2.
0
 
CEHJCommented:
void buttonOneClicked() {
  if (srv == null) {
      srv = new Server(5154);
  }
}
0
 
CEHJConnect With a Mentor Commented:
public class MyClass
{
   private Server srv = new Server(5154);
0
 
CSecurityAuthor Commented:
I get error on this line:
srv = new Server(5154);
non-static variable srv cannot be referenced from a static context
0
 
objectsCommented:
If you're calling it from a static method then you'll need to make it static as i showed in my first post
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.