0

I have this problem when i want to send data from a frame to another

I've manege to do it like this :

public class user_login extends javax.swing.JFrame {
public static String id;

and then in the next J frame I've done this

    String x = user_login.id);

I know its a bad practice

can anyone helps me ! Thanks <3

Ghassen Arfaoui
  • 59
  • 1
  • 12
  • It is quite confortable to use `Message Bus` in all sort of GUI appliocations. http://stackoverflow.com/questions/1953380/lightweight-message-bus-library – Antoniossss Apr 20 '17 at 21:46
  • First of all, `static` is not a cross communication mechanism, instead, you could use a modal dialog and return the result or some kind of model and/or observer pattern to generate notifications when some state has changed – MadProgrammer Apr 20 '17 at 21:56
  • Maybe, instead of posting a question, you should try a [quick google search](https://www.google.com.au/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#safe=off&q=java+swing+pass+data+between+frames) first, have a look at what you can find, try a few things, if they don't work, post what you've tried and what you want to accomplish and why the other solutions didn't work and maybe we can help your further – MadProgrammer Apr 20 '17 at 21:58
  • See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) – Andrew Thompson Apr 20 '17 at 22:38

1 Answers1

0

Indeed, you should not communicate in this way between 2 JFrame.
Providing the full api of the component could create mix of responsibilities between the two JFrame.
Besides, using a static field to share data is a very bad idea as global variable generates often a strong coupling between components and processing that should not be and also increases the side effect risk when code using this variable is modified.

Only the behavior in terms of API should be offered to the user class.

You can create an interface to define the API of the JFrame that you want to call from another JFrame. Make the used JFrame implement the interface and make the user JFrame having a reference object to this interface.
The, you have just to communicate with the API from the user JFrame.

API :

public interface UserLoginAPI{
   String getLogin();
}

User JFrame :

public class UserLoginFrame extends JFrame implements UserLoginAPI{

    private String id;
    ...
   public String getLogin(){
       return id;
   }

}

Used JFrame :

public class OtherFrame extends JFrame {

    private UserLoginAPI api;

    private OtherFrame(UserLoginAPI userLoginAPI){
        this.api = userLoginAPI;
    }

    public void doSomeProcessing(){
       String loginRetrievedByApi = api.getLogin();
    }

}
davidxxx
  • 125,838
  • 23
  • 214
  • 215