繁体   English   中英

从另一个类访问对象方法

[英]access object method from another class

我是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实例sets为实例变量,并且然后只需调用addToHistoryArea方法

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

在Server的某个位置,您可以拥有History

public class Server{

    private History history;


    public void setHistory(History history){
      this.history= history;
    }

    public void someMethod(){
      history.addToHistoryArea();
    }

}

或者,如果您不想在服务器中拥有实例

public void someMethod(History history){
      history.addToHistoryArea();
}

或者,如果你想要更加分离,你可以采用观察者模式,或者如果他们是同事,也可以采取调解者。

您可能希望在Server类中创建History对象,然后在该history实例上调用addToHistoryArea()方法。

public class Server{

    private History history;

    public void setHistory(History history){
        this.history = history;
    }

    public void methodCall(){
        history.addToHistoryArea();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM