tags:

views:

66

answers:

1

Hello, I have a little problem with my java-program. I wanna use Observer, to synchronize two GUIs. But I can't synchronize the JComponent / JButton elements. For example:

I have a GUI-Class which implements the Observer-Class:

public class GUI extends JFrame implements Observer

I have a second "GUI"-Class which extends the JButton-Class and makes changes on a specific Button-Element.

public class Karte extends JButton{
...
this.setEnabled(false);
...

How do I synchronize this Button via Observable? I have already tried to use "extends Observable" in this class, but the "setEnabled()" method is explicit for the JButton-Class, which is not Observable!

Can someone help?

Thanks.

+1  A: 

One way to do it is to let Karte have an Observable (rather than being one).

public class Karte extends JButton{

    final Observable obs = new Observable() {
        // override as needed here
    }

    // ...

    Observable asObservable() { return obs; }
}

myKarte.asObservable().addObserver(myGUI);

It's considered good practice to favor composition over inheritance, but sometimes it's simply necessary whether or not you want to!

Jonathan Feinberg