首页 > 解决方案 > 如何在没有类的情况下使用另一个类的方法

问题描述

我有一个方法 showMessage() 将字符串附加到 JTextArea 上,我想在我的“类中的类”(ServerThread)中调用它。如果没有 Main main,我怎么能做到这一点;或 Main main = new Main();

public class Main extends JFrame {
private static final long serialVersionUID = 1L;
private JTextArea chatWindow;
private List<Integer> ports = new ArrayList<Integer>();

public Main() throws IOException {
    super("ServerConsole");

    chatWindow = new JTextArea();
    chatWindow.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(chatWindow);
    scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    scrollPane.setBounds(0, 20, 596, 200);
    add(scrollPane);

    setLayout(null);
    setSize(600, 300);
    setResizable(false);
    setVisible(true);
    getContentPane().setBackground(Color.white);

    Socket s = null;
    ServerSocket ss2 = null;
    showMessage("Server Listening......\n");
    try {
        ss2 = new ServerSocket(3175);
    } catch (IOException e) {
        e.printStackTrace();
        showMessage("Server error");
    }
    while (true) {
        try {
            s = ss2.accept();
            showMessage("connection Established\n");
            ports.add(s.getPort());
            ServerThread st = new ServerThread(s);
            st.start();

        }

        catch (Exception e) {
            e.printStackTrace();
            showMessage("Connection Error");

        }
    }

}

public void showMessage(final String m) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            chatWindow.append(m);
        }
    });

}

}

class ServerThread extends Thread {

private ObjectOutputStream output;
private ObjectInputStream input;
Socket s = null;
private static LinkedHashMap<Integer, String> playerCoords = new LinkedHashMap<Integer, String>();

public ServerThread(Socket s) {
    this.s = s;
}

public void run() {
}
}

示例:在 run 方法中,我希望在没有声明 Main 对象的情况下拥有类似 main.showMessage(string) 的内容。

标签: javaclassmethods

解决方案


只需将您的方法声明为static

public static void showMessage(final String m)

这样,您可以这样称呼它-

Main.showMessage("Some String");


推荐阅读