public class View extends JFrame implements Observer {
private JLabel label;
private JTextField field;
public View() {
label = new JLabel();
field = new JTextField(10);
JButton change = new JButton("Change!");
change.addActionListener(new Controller(this));
JPanel panel = new JPanel();
panel.add(label);
panel.add(field);
panel.add(change);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
this.getContentPane().add(panel);
this.pack();
this.setVisible(true);
}
public static void main(
String[] args) {
View v = new View();
}
/**
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
public void update(Observable arg0, Object arg1) {
label.setText(((Model) arg0).getValue());
}
public String getValue() {
return field.getText();
}
}
public class Controller implements ActionListener {
private View view;
private Model model;
public Controller(View view) {
this.view = view;
model = new Model();
model.addObserver(view);
model.setValue("Fred");
}
public void actionPerformed(ActionEvent ae) {
model.setValue(view.getValue());
}
}