• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 199
  • Last Modified:

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
0
CSecurity
Asked:
CSecurity
  • 3
  • 3
  • 2
2 Solutions
 
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
 
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
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

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.

 
CEHJCommented:
void buttonOneClicked() {
  if (srv == null) {
      srv = new Server(5154);
  }
}
0
 
objectsCommented:
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:
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.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 3
  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now