java主函数程序,Java使用MainWindow函数

So I have a MainWindow.java that creates the window with all the controls and things. I put a menubar object on the window, one of the options in the menubar is make the program a server. So here's the main window looks like this:

public class MainWindow extends javax.swing.JFrame {

//all code including menubar click action handler

//Server.start()

}

When you click the option, it goes into the Server.java class and starts the server. Here's the skeleton of that class:

public class Server {

public static void start(String port) {

try {

startServer(Integer.parseInt(port));

} catch (Exception e) {

e.printStackTrace();

}

}

public static void startServer(int PORT) 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() {

...

}

}

}

The problem now is that once it gets inside the Server class, it listens for connections and connects fine but I just can't go back to the MainWindow class. It stays within the Server class. I can't even call the MainWindow functions by doing MainWindow.function() because it says

Cannot make a static reference to the non-static method function() from the type MainWindow

I even tried putting all of the Server class code into the MainWindow class or just above it but Java didn't like that and said it wanted it in a separate file.

How exactly do I reference MainWindow functions from within the Server class? Or is there a better way of going about this?

解决方案

You need to either create an instance of the MainWindow class using for instance MainWindow m = new MainWindow() and then calling the function as m.function(), or declare your function as static.

Static means that you can call a function without creating an instance of the object. This is why you get the error, since your function is not static, so it requires an instance of the object to be called.

You'll also want to make sure that the MainWindow class is imported into the Server class.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值