如何在没有该类的情况下使用另一个类的方法

时间:2018-09-02 18:48:24

标签: java class methods

我有一个方法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.showMessage(string)的东西而没有声明Main对象。

2 个答案:

答案 0 :(得分:0)

只需将您的方法声明为static

public static void showMessage(final String m)

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

Main.showMessage("Some String");

答案 1 :(得分:0)

同时声明showMessage方法和chatWindow字段static。然后,您可以在需要的地方以Main.showMessage("whatever")进行呼叫。

但是,更优雅的解决方案是在singleton上传达这两个listener

使用MessageListener方法声明接口onMessage(String message)

interface MessageListener {
    public void onMessage(String message);
}

ServerThread中保留MessageListener的列表,并在run方法中调用它们

class ServerThread extends Thread {

   // class content 

    static List<MessageListener> messageListeners = new ArrayList<>();

    public void run() {
        for (MessageListener messageListener : messageListeners) {
            messageListener.onMessage("the message");
        }
    }
}

然后让您的Main类实现MessageListener并在onMessage方法调用showMessage中,也不要忘记注册ServerThread的侦听器注册表

public class Main extends JFrame implements MessageListener {

    // class content

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

        ServerThread.messageListeners.add(this);

        // other content

    }

    // class content

    @Override
    public void onMessage(String message) {
        showMessage(message);
    }
}

仅此而已。那么整个代码如下:

import java.awt.Color;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;

public class Main extends JFrame implements MessageListener {

    private static final long serialVersionUID = 1L;
    private JTextArea chatWindow;
    private List<Integer> ports = new ArrayList<Integer>();

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

        ServerThread.messageListeners.add(this);

        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);
            }
        });

    }

    @Override
    public void onMessage(String message) {
        showMessage(message);
    }

}

interface MessageListener {
    public void onMessage(String message);
}

class ServerThread extends Thread {

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

    static List<MessageListener> messageListeners = new ArrayList<>();

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

    public void run() {
        for (MessageListener messageListener : messageListeners) {
            messageListener.onMessage("the message");
        }
    }
}