问题
I have a java menubar in my program that just has 1 option with 2 sub-options, e.g. File -> Save, Close. But instead of Save and Close, my options are Server and Client. So for the action event for the 1st option I have this java action listener:
public class serverAction extends AbstractAction
{
public serverAction()
{
super();
}
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(null, "Test");
}
}
So this works when I click on File->Server, it pops up a window that says Test. Now I have a server class (That I have tested separately and know it works) that looks like this:
public class SocketServer {
public static void main(String[] args) throws Exception {
...
}
private static class ClientListenThread extends Thread {
public ClientListenThread(Socket socket, int ClientNumber){
...
}
public void run() {
...
}
}
private static class ServerSendThread extends Thread {
public ServerSendThread(Socket socket) {
...
}
public void run() {
...
}
}
}
Now I need to call this SocketServer
class when I click on the server option of my main program so that it can start the server code and wait and listen for any client connections. My question is, how do I start the entire SocketServer
class code from the serverAction
class?
回答1:
Your nested-classes are private
that means that are only visible in ServerSocket
class. So you can provide a helper method with more visibility or change class declaration signature with more visibility.
Example with helper method:
public class SocketServer {
.
.
//nested classes declaration
public static void startServer(){
//code to start threads new SomeThread().start();
}
}
And in your action
public class ServerAction extends AbstractAction{
@Override
public void actionPerformed(ActionEvent e){
SocketServer.startServer();
JOptionPane.showMessageDialog(null, "Test");
}
}
It would be great if you can notify when a client is connected and so on, I'd recommend you to take a look to SwingWorker
that provide helpful tool to handle notification between a background thread and the gui thread.
Read more: Worker threads and SwingWorker
Note : Would be great if you implements Runnable
rather to extend Thread, you are not adding any special functionality to thread there is no reason, more details here --> "implements Runnable" vs. "extends Thread".
来源:https://stackoverflow.com/questions/22619323/java-menubar-action-to-a-class