0

I created a JFrame with buttons, labels and texts and I want to show it two times when I execute the main program, so I did like that:

import java.net.SocketException;

public class Main {

    public static void main(String[] args) throws SocketException {
        new MyFrame("client1");
        new MyFrame("client2"); 
    }
}

The result: I get two frames: one with the component of the other one inside, and one empty.

How to resolve this issue?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Souad
  • 4,856
  • 15
  • 80
  • 140
  • I "guess" you are using static instance fields in your MyFrame class – MadProgrammer Nov 25 '14 at 19:50
  • Ah yeah that is true ! – Souad Nov 25 '14 at 19:51
  • 1) See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) 2) A single blank line of white space in source code is all that is *ever* needed. Blank lines after `{` or before `}` are also typically redundant. – Andrew Thompson Nov 26 '14 at 01:43

1 Answers1

2

You are using static instance fields with your MyFrame for your components

A component can only reside within a single container, the moment you create your second frame, the static components are removed from the first container before been added to the second.

The solution, don't do this, ever...

I assume you are using static because you want to access these fields from another class, in that case, you should appropriate getters in the MyFrame class and pass a reference of it to those classes that need it.

Alternatively, you could establish a series of observers who monitor for changes and take appropriate action, this helps to decouple the code.

Personally, if you need to modify the MyFrame instances in some way, I'd provide setter methods that update your components instead, as I don't like exposing UI elements without good reason, to much opportunity for others to mess with them in appropriately

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366