java - 如何在没有类的情况下使用另一个类的方法
问题描述
我有一个方法 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) 的内容。
解决方案
只需将您的方法声明为static
public static void showMessage(final String m)
这样,您可以这样称呼它-
Main.showMessage("Some String");
推荐阅读
- mysql - 使用包含时间戳的特定名称在特定位置备份 MySQL 数据库
- java - 如何迭代Hashmap并与同一个Hashmap中的其他键进行组合以比较它们的对象
- javascript - 在 Material-UI 中从 textview 中选择项目后如何更改字体颜色
- javascript - 如何在 JavaScript 中将特殊符号转换为表情符号?
- java - Java JsonPath 函数“indexOf”给出异常:函数参数:“indexOf”未正确关闭
- python - Pandas replace() 所有掩码值
- r - 如何组合“geom_text”调用的斜体和非斜体组件。将 `geom_text` 标签添加到一系列 `facet_grid` 散点图
- java - 使用 PageRequest 上的模型参考排序不起作用
- android - 如何从 Jetpack compose 中的 drawable 加载图像?
- firebase - firebase admin sdk 身份验证在本地失败,getaddrinfo ENOTFOUND