我是Java和面向对象的新手,我正在尝试创建一个聊天程序。这是我想做的事情:我的Main.java中的某个地方Window window = new Window;我的Window.java中的某个地方History history = new History()在我的History.java中的某个位置:public History(){ super(new GridBagLayout()); historyArea = new JTextArea(15, 40); historyArea.setEditable(false); JScrollPane scrollPane = new JScrollPane(historyArea); /* some other code... */}public void actionPerformed(ActionEvent event){ String text = entryArea.getText(); historyArea.append(text + newline); entryArea.selectAll(); historyArea.setCaretPosition(historyArea.getDocument().getLength());}public JTextArea getHistoryArea(){ return historyArea;}public void addToHistoryArea(String pStringToAdd){ historyArea.append(pStringToAdd + newline); historyArea.setCaretPosition(historyArea.getDocument().getLength());}现在,我在Server.java中,我想使用方法addToHistoryArea。在不使我的historyArea静态的情况下该怎么办?因为如果我很好地理解了静态的工作原理,即使创建新的历史记录,我也不会拥有不同的historyArea ...感谢您的帮助,并告诉我我是否理解错了! 最佳答案 在您的Server构造函数中,发送您的History对象的实例(例如new Server (history),然后您可以调用history.addToHistoryArea,另一个选项是使用setter方法,该方法sets一个实例的到一个实例变量,然后只需调用history方法public class Server{ private History history; public Server(History history){ this.history = history; } public void someMethod(){ this.history.addToHistoryArea(); }}另一种方式public class Server{ private History history; public void setHistory(History history){ this.history = history; } public void someMethod(){ this.history.addToHistoryArea(); }}
07-27 13:34