Question

I'm new to Java and oriented-object and I'm trying to create a chat program. Here's what I'm trying to do:

Somewhere in my Main.java

Window window = new Window;

Somewhere in my Window.java

History history = new History()

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

Now that I'm in Server.java, I want to use the method addToHistoryArea. How can I do that without making my historyArea static? Because if I understand well how static works, I couldn't have different historyArea even if I create a new History...

Thanks for your help and tell me if I got it all wrong!

Was it helpful?

Solution

In your Server constructor, send the instance of your History object (e.g new Server (history), and then you can invoke, history.addToHistoryArea, other option would be have a setter method which sets an instance of history to an instance variable, and then just call the addToHistoryArea method

public class Server{

    private History history;

    public Server(History history){
        this.history = history;
    }

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

Another way

public class Server{

    private History history;

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

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

OTHER TIPS

In someplace in Server you can have History

public class Server{

    private History history;


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

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

}

Or if you don't want to have an instance in Server

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

Or if you want to be more decoupled you can take approach with the observer pattern or perhaps a mediator if they are colleagues.

You may want to create a History object in the Server class and then call the addToHistoryArea() method on that history instance.

public class Server{

    private History history;

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

    public void methodCall(){
        history.addToHistoryArea();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top