1

I'm a long-time Python developer, and relied on Enthought's Traits/TraitsUI libraries for quick GUI development. I'm trying to understand if Swing has a similar implementation of Traits that would allow for easy delegation.

Imagine I have a JFrame that references to another class, Foo, and has a textfield, fooText. When the user changes fooText, this triggers an event, and the change is propagated down to Foo

public class View extends javax.swing.JFrame {

    private Foo foo; 
    private javax.swing.JTextField fooText;

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt){
    foo.fooText = this.fooText.getText();                                        

    ...
}

Where the Fooclass also shares the fooText value:

public class Foo{
    public String fooText;
}

Is it possible to synchronize the value of fooText between the classes Foo and View? In the example above, I had to manually pass the new value in through an event listener. In the Python traits library, I can simply tell Foo to use delegation. Something like:

class Foo(HasTraits):
      view = Instance(View);
      String fooText = DelegatesTo(view)

In this way, rather than passing shared variables, I just pass a reference to the View object to other objects in my program, and then any changes to View.fooText are immediately propagated down to the delegating classes. This helps tremendously when UI fields need shared across many classes.

Is anything like this available in java/swing?

Thanks

Adam Hughes
  • 14,601
  • 12
  • 83
  • 122
  • In View, you declare fooText as a JTextField; in Foo, you declare fooText as a String. You can't set them equal. But in the actionListener you can set `foo.fooText = this.fooText.getText();` (It would be better to use different names for these fields, and also better to make the text variable private in nFoo and use a Setter to set its value. – FredK Dec 15 '15 at 15:41
  • Thanks for the tips, I completely overlooked the type differences. At the end of the day, I still don't understand if they can be synchronized in the way described in TraitsUI. I will update my question to reflect `getText()` – Adam Hughes Dec 15 '15 at 15:48
  • 1
    No, swing is not built like traits. You need to do a bit more work to expose the underlying variables. – aestrivex Feb 19 '16 at 21:33

0 Answers0