user3437460
user3437460

Reputation: 17454

Sending text to another object with Swing Component

I have a class which creates a JButton, a JTextArea for displaying message, and another JTextArea for receiving input messages.

I used a class to create instances of 2 objects.

class TextingProgram
{
   public static void main(String[] args) 
   {
      TextSenderUI senderObj1 = new TextSenderUI("User1");
      TextSenderUI senderOjb2 = new TextSenderUI("User2");
   }
}


class TextSenderUI
{
   //Creates swing components - btnSend, txtDisplay, txtInput   
   //Action Listener for btnSend which sends text of txtInput to both windows' textDisplay
}

I've tried a few ways (for example adopting MVC) to let them share information. But ultimately I still need the text to be displayed in both windows the moment the send button is pressed from one of the sides.

Question: I have no problem if I were to use the action listener to display text on its own window. However, how do I let the action listener to perform action on textDisplay of both ojects (senderObj1 & senderObj2)?

Upvotes: 0

Views: 97

Answers (1)

mbw
mbw

Reputation: 366

A simple way would be to something similar to creating a custom listener.

In each TextSenderUI class, initialize a empty list of type TextSenderUI. ie,

LinkedList<TextSenderUI> textSenderUIList = new LinkedList<TextSenderUI>();

Add a public method to the class that will allow adding to this list. ie,

public void addTextSenderUIListener(TextSenderUI tSUI) {
    textSenderUIList.add(tSUI);
}

Add another public method to write text in this class, ie

public void showText(String text) {
    yourTextArea.setText(text);
}

You will need one more method to tell all the classes registered as a listener to perform an action, ie

protected void fireShowText() {
    String text = getTextFromWhateverYourTextArea();
    ListIterator<TextSenderUI> it = textSenderUIList.listIterator();
    while (it.hasNext()) {
        it.next().showText(text);
    }
 }

You will put an actionListener on your send button, and you will call fireShowText() each time it is pressed.

In your main code, you will change it to:

TextSenderUI senderObj1 = new TextSenderUI("User1");
TextSenderUI senderObj2 = new TextSenderUI("User2");
senderObj1.addTextSenderUIListener(senderObj2);
senderObj2.addTextSenderUIListener(senderObj1);

Upvotes: 2

Related Questions