Java观察者和可观察者

发布于 2024-08-06 19:02:05 字数 2304 浏览 1 评论 0原文

谁能解释为什么当我单击此 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;
    }
}

Can anyone explain why the update method on printobserver is not being called when I click the button on this JFrame?

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;
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夕嗳→ 2024-08-13 19:02:06

您需要调用Observable.setChanged。请注意,notifyObservers 的 API 文档以“如果此对象已更改,如 hasChanged 方法所示”开头。

但实际上,我强烈建议不要使用 java.util.Observable 和 Observer。

You need to call Observable.setChanged. Notice that the API docs for notifyObservers starts with "If this object has changed, as indicated by the hasChanged method".

But really, I strongly suggest not using java.util.Observable and Observer.

一指流沙 2024-08-13 19:02:06

正如 Tom 所说,您必须首先调用 Observable.setChanged

Java 中的 Observable 实现的问题在于它来自 JDK 1.0,这并不一定是坏事,但自那时起它就没有更新:(。

除此之外,我没有看到任何问题使用它,但要考虑到 Observable 不使用观察者的弱引用(WeakReference 出现在 Java 1.2 中),因此您必须注意始终调用 deleteObserver当不再需要观察者时不产生泄漏

另一种替代方法是使用更复杂的接口,即实用程序类 PropertyChangeSupport 基于 PropertyChangeListener 接口。该实用程序类,因此如果您在 UI 代码中使用它,您会发现它更合适。

As Tom said you have to call to Observable.setChanged first.

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 :(.

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.

Another alternative, but with a more complex interface is the utility class 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文