Question

Let's say I have a gui, and the gui is composed of two parts where each part has its own class.
So one class contains a JLabel.
And second class contains a text field with a submit button.
How would I go about making those two components talk to each other?

This is of course a simple example, but if I have two classes where I use one for submitting data, and one for showing the submitted data, then how do I make the two components communicate?

Was it helpful?

Solution

Some thoughts:

  • Don't add such bindings to the GUI classes, look for a pattern like MVC
  • Unidirectional change propagation (input -> output as in your example) is usually never problematic, but in many cases, full synchronization of editable component groups is required. So one may keep that in mind during development of the simple case for good reusability of any custom class or interface.
  • Avoid infinite circular updates with a flag, rather than with a comparison of component values.
  • Whatever you do, keep things separated and whatever pattern you use, don't add bidirectional references (e.g. among GUI class <-> controller)

Regardless of MVC, there could be a controller class, getting all necessary references to the UI objects (i.E. JPanels with nested JTextFields and JLabels, etc.) via constructor. On construction, that controller can attach itself to those nested components. The controller should preferably contain nested, inner or perhaps anonymous classes for implementing the listener interfaces, rather than adding the listener interface to the controller itself. First, to encapsulate these listeners and second, to avoid the event source distinction, if the same interface needs to be implemented for multiple components (sources). These listener implementations (perhaps pretty generic PropertyChangeListener's) could then act as, or use mediator objects (as mentioned), for updating other components.

OTHER TIPS

If you have a submit button, you can add an action listener to it. When clicked you can call a method in your other class that will receive the string and then display it on your JLabel. However having multiple classes for different components isn't usually a good idea, and having a MVC like what Sam said is much better.

Class with JTextArea

//Have this object created
JLabelClass JLC = new JLabelClass();

//When submit button is clicked run this
JLC.displayText(JTextArea.getText());

Inside Class with JLabel

//add this method
public void displayText(String text){
    JLabel.setText(text);
    //Refresh Gui and display stuff....
}

Hope this helped... Sorry about the formatting I'm still new to StackOverflow

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top