views:

460

answers:

1

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;
    }
}
+5  A: 

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.

Tom Hawtin - tackline
@Tom, can you elaborate on what is the alternative?
DJ