Search code examples
javaswingjframeobserver-pattern

JFrame waiting for data reception to perform its task


I have two different and independent JFrame windows:

  1. DataFrame
  2. GraphFrame

The first one is for the user to manipulate, with the input of different values and patterns to display on a graph presented in 2). The 1) sends specific values to 2) (array with doubles) so that "GraphFrame" can create the graph.

I invoke the "main " method from GraphFrame in the "main" method of DataFrame so that they both run at the same time and are both visible during the whole process.

I want these frames to be completely independent, which means that the mission for 1) is to send values and the mission for 2) is to check when values are recieved and then create the graph.

I also prefer to keep most of the methods private, so that they can't be accessed from external sources.

My problem, is that I don't know which is the best way to implement this data exchange. What is the best way for Frame 2) keep "listening" for the values it needs to recieve?

Should I create getters/setters on 2) and with the help of an Observer https://sourcemaking.com/design_patterns/observer ?

Or should I use threads?

Or even the creation of a traditional loop that keeps waiting for values, like:

while(array.isEmpty()) {
     //stuck here
}
//create the graph from the values in array

At the moment I am receiving the values in 2) from setter methods, but I am uncapable, so far, of performing the code I desire only after I get the values.

What do you think is the best way to implement this?

P.S.: Should I consider not invoking GraphFrame main from DataFrame and run these 2 separately?


Solution

  • From what I understood, you're trying to run both JFrames in the same application. Conceptually this is rather one UI split into two windows than running two Frames as you put it.

    Swing requires all UI elements to be updated by one thread - the AWT-Thread. Also interaction with the UI will run in the AWT-Thread. You need to take this into account.

    Also it is best practice to separate data model and view. To solve your problem you could create a model for the GraphFrame that is manipulated by changes on the DataFrame. These changes could e.g. be picked up by a listener on the model that uses SwingUtils.invokeLater() to update the GraphFrame.

    Of course there is a number of Issues you might need to care for additionally and depending on your requirements you might need to further decouple the two parts.