Reputation: 603
I'm still learning swing and sockets both, so bear with me. To learn I'm making a chat client/server system. Right now, I'm working on the client. My classes are
I set up a SocketManager
object in Main
when the program runs, but then when ActLis
needs to use that socket to send a message
I don't know of a good way to get it from Main
. Is what I'm doing completely ineffective and there is a better way to set it up, or is there a way to get my SocketManager
object from my Main
class that I don't know? (I realize there are other problems in my code, but I'm just trying to get sockets to work for a start, I'm having a hard time with them.)
Upvotes: 1
Views: 529
Reputation: 790
adding to Hunter McMillen's:
3) Make Main class, singleton. id est do not let more than one instance of it (If I've had understood your purpose, you don't need more than one instance of this class.) so just make a single instance of this class and keep its reference as a public static final field in it. (and of course don't let it be instantiated from outside this class:
public class Main
{
public static final Main instance = new Main(/*args*/);
private Main(/*args*/)
{
//blah blah
}
}
This way you can access your Socket
field in Main
form anywhere in your code with no problem.
Upvotes: 0
Reputation: 61512
You have a few options:
1) Have a ActLis object in the Main class and pass Main's reference to SocketManager to it
public class Main
{
public static void main(String[] args)
{
ActList a = new ActList(...);
SocketManager sm = new SocketManager(...);
a.sendMessageWithSocket(sm); //here you pass Main's reference to SocketManager
} //object to the ActLis class for use
}
2) Let the ActLis class have a reference to the SocketManager object, set in its constructor
public class ActLis
{
private SocketManager sm;
public ActLis(SocketManager sm)
{
this.sm = sm;
}
}
These are probably the most simple ways to do this.
Upvotes: 1