user3437460
user3437460

Reputation: 17454

Creating and running multiple Java windows using one class

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?

Upvotes: 0

Views: 213

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109547

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.

Upvotes: 2

Related Questions