简体   繁体   English

Java观察者和可观察者

[英]Java observer and observable

Can anyone explain why the update method on printobserver is not being called when I click the button on this JFrame? 任何人都可以解释为什么我点击这个JFrame上的按钮时没有调用printobserver上的更新方法?

import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;


/**
 * 
 */

/**
 * @author james
 *
 */
public class Driver extends JFrame {


    /**
     * @param title
     */
    public Driver() {
        super("click me");

        setSize(400, 400);
        //set up observer

        final ButtonObservable gw = new ButtonObservable();
        Observer o1 = new PrintObserver();
        gw.addObserver(o1);

        setLayout(new BorderLayout());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setExtendedState(Frame.MAXIMIZED_BOTH);
        JPanel panel = new JPanel();
        add(panel, BorderLayout.CENTER);        

        JButton connectBtn = new JButton("print me"); //$NON-NLS-1$
        connectBtn.addActionListener(new ActionListener() {         
            public void actionPerformed(ActionEvent e) {
                gw.buttonPress();
            }
        });

        panel.add(connectBtn);


    }

    /**
     * @param args
     */
    public static void main(String[] args) {

        JFrame mypane = new Driver();
        mypane.setVisible(true);

    }

}

class PrintObserver implements Observer
{
    public void update(Observable o, Object arg)
    {
        int x = ButtonObservable.getX();
        File jf = new File("/home/foo/bar");
        try {
            jf.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Blah var -= " + x);
    }
}

class ButtonObservable extends Observable
{
    private static int x = 0 ;

    @Override
    public int countObservers()
    {
        return this.countObservers();
    }

    public void buttonPress()
    {
        x += 1;
        this.notifyObservers();

    }

    /**
     * @return the x
     */
    public static final int getX() {
        return x;
    }
}

You need to call Observable.setChanged . 你需要调用Observable.setChanged Notice that the API docs for notifyObservers starts with "If this object has changed, as indicated by the hasChanged method". 请注意, notifyObservers的API文档以“如果此对象已更改,如hasChanged方法所示”开头。

But really, I strongly suggest not using java.util.Observable and Observer . 但实际上,我强烈建议不要使用java.util.ObservableObserver

As Tom said you have to call to Observable.setChanged first. 正如汤姆所说,你必须先调用Observable.setChanged

The problem with the Observable implementation in Java is that it comes from JDK 1.0, that is not necessary bad, but it wasn't updated since them :(. Java中的Observable实现的问题在于它来自JDK 1.0,这不是必须的,但它没有更新,因为它们:(。

Apart from that I don't see any issues with it, but take account that Observable doesn't use weak references for the observers (WeakReference appeared in Java 1.2), so you have to take care to always call to deleteObserver to not generate leaks when the observer is no longer necessary. 除此之外,我没有看到它的任何问题,但考虑到Observable不使用弱引用观察者(WeakReference出现在Java 1.2中),所以你必须注意始终调用deleteObserver不产生泄漏当观察者不再需要时。

Another alternative, but with a more complex interface is the utility class PropertyChangeSupport . 另一个替代方案,但具有更复杂的接口是实用程序类PropertyChangeSupport Swing listeners are based on the PropertyChangeListener interface and that utility class, so if you are using it in UI code you'll find it more appropriate. Swing侦听器基于PropertyChangeListener接口和该实用程序类,因此如果您在UI代码中使用它,您会发现它更合适。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM