Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Below program will create 2 simple windows where we can type some text, and it will be shown in both windows' display screen.

I created a Class to generate UI. However, when I use the same class to create 2 objects (typeWriterObj1 & typeWriterObj2) and click on btnSend.

The typed in message are always directed and displayed in the last created window (For example: I type text into Alice's txtMessage and click btnSend, text is shown in Bob's window instead of Alice's).

See below example:

public class TextProgram
{   
    public static void main(String[] args) 
    {       
        TypeWriterUI typeWriterObj1 = new TypeWriterUI();    
        TypeWriterUI typeWriterObj2 = new TypeWriterUI();                    
        TypeWriterObj1.showGUI("Alice");            
        TypeWriterObj2.showGUI("Bob");          
    }    
}

class TypeWriterUI extends JPanel
{
    static JButton btnSend;
    static JTextArea txtDisplay = new JTextArea();
    static JTextArea txtMessage = new JTextArea();

        //...Codes which add the swing components

        //ActionListerner for btnSend which transfer input text from txtMessage to txtDisplay
}

Que: How can this problem be resolved if I were not to use multi-threading?

share|improve this question

1 Answer 1

up vote 2 down vote accepted

Undo making the fields static (one instance per class). Both GUIs shared every button instance. That this worked is even a miracle; probably twice assigned a new JButton to the same variable and so on.

share|improve this answer
    
Thanks for that. But if I want the text typed in from one window to show in both windows, can I use static for that? I will remove static for the button anyway. :) –  user3437460 yesterday
    
No, any GUI component, like JTextField, holds a reference to its parent, and that can only be one. You can add a change listener, and pass the new value to a controller object holding both GUI classes, and passing that new value to the other class. This is the so-called MVC, Model-Vieew-Controller, pattern. Best hold the JFrames and provide them with public void updateText(String newValue);. –  Joop Eggen yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.