Making a JFrame and Observable Object

让人想犯罪 __ 提交于 2019-12-05 05:35:13

Extend Observable and declare setChanged() public.

Hovercraft Full Of Eels

I think many here, myself included use the Observer Design Pattern without using Java's formal Observer/Observable interface/class, and there are many ways to implement this, especially in Swing. Probably the most flexible is to use PropertyChangeSupport with PropertyChangeListeners which is how SwingWorkers implement this. Another is to use the very basic ChangeListener interface.

If you need more specific help, please provide more detail on your problem and likely we can offer suggestions.

Edit 1
This also alights on a separate but important issue that's suggested by the description of your program: your GUI class extending JFrame. Many here (again myself included) recommend that you should avoid doing this unless your code alters the intrinsic behavior of JFrame -- that is that your class overrides one or more of JFrame's methods. This is a small sub-discussion in the much greater discussion on which is better: enhancing classes through inheritance or through composition.

For example: Prefer composition over inheritance?

Edit 2
Next unrequested recommendation: I try to gear my GUI code toward creating JPanels rather than JFrames. This way if I want to display my GUI as a stand-alone GUI, I simply create a JFrame on the fly, place my gui's JPanel into the JFrame's contentPane, pack the JFrame and display it. I do the same procedure if I want to place the gui into a JDialog, a JApplet, a JOptionPane, or also in a CardLayout using container, another JPanel,... . This gives me tremendous flexibility in how I use my gui's.

This will do it.

public class MyJFrame extends JFrame implements Observer {
    private static class MyObservable extends Observable {
        @Override
        public void setChanged() {
            super.setChanged();
        }
    }
    private final MyObservable observable = new MyObservable();

    // rest of your code
} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!