Java菜单栏对类的操作 [英] Java Menubar Action to a Class
问题描述
我的程序中有一个Java菜单栏,其中只有1个选项和2个子选项,例如文件->保存,关闭。但是,我选择的是服务器和客户端,而不是保存和关闭。因此,对于第一个选项的动作事件,我有以下java动作侦听器:
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");
}
}
因此,当我点击File-> Server,它会弹出一个窗口,显示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() {
...
}
}
}
现在我需要当我单击主程序的服务器选项时,请调用此 SocketServer
类,以便它可以启动服务器代码并等待并监听任何声音t连接。我的问题是,如何从 serverAction
类中启动整个 SocketServer
类代码?
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?
推荐答案
您的嵌套类是私有
,这意味着它们仅在 ServerSocket
类中可见。因此,您可以提供具有更高可见性的帮助程序方法或具有更高可见性的更改类声明签名。
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();
}
}
在您的行动中
public class ServerAction extends AbstractAction{
@Override
public void actionPerformed(ActionEvent e){
SocketServer.startServer();
JOptionPane.showMessageDialog(null, "Test");
}
}
如果您可以通知客户何时会很棒已连接,依此类推,我建议您看看 SwingWorker
,它提供了有用的工具来处理后台线程和gui线程之间的通知。
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.
了解更多:工作线程和SwingWorker
注意:如果实现 Runnable
而不是扩展Thread,那将会很棒没有为线程添加任何特殊功能没有任何理由,这里有更多详细信息-> implements Runnable ;与扩展线程 。
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".
这篇关于Java菜单栏对类的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!