在利用观察者模式相应awt时间时,没有出现结果!!
- Java code
package Test;public class Clinet { public static void main(String[] args) { IntervalWindow Iw= new IntervalWindow(); Interval i=new Interval(); i.addObserver(Iw); }}
- Java code
package Test;import java.util.Observable;public class Interval extends Observable { public String start = "0"; public String end = "0"; public String length = "0"; public void calculatestart(String start, String end) { this.start = start; this.end = end; this.length = String.valueOf(Integer.parseInt(start) - Integer.parseInt(end)); setChanged(); notifyObservers(); } public void calculateend(String start, String end) { this.start = start; this.end = end; this.length = String.valueOf(Integer.parseInt(start) - Integer.parseInt(end)); setChanged(); notifyObservers(); } public void calculatelength(String start, String length) { this.start = start; this.length = length; this.end = String.valueOf(Integer.parseInt(start) - Integer.parseInt(length)); setChanged(); notifyObservers(); } }
- Java code
package Test;import java.awt.Color;import java.awt.GridLayout;import java.awt.event.FocusAdapter;import java.awt.event.FocusEvent;import java.util.Observable;import java.util.Observer;import javax.swing.JFrame;import javax.swing.JTextField;@SuppressWarnings("serial")public class IntervalWindow extends JFrame implements Observer { JTextField start = new JTextField("0", 10); JTextField end = new JTextField("0", 10); JTextField length = new JTextField("0", 10); GridLayout fl = new GridLayout(3, 1); public IntervalWindow() { super("测试观察者模式在GUI中的使用"); this.setSize(400, 400); this.setLocation(500, 100); this.setBackground(Color.WHITE); this.setLayout(fl); this.add(start); this.add(end); this.add(length); start.addFocusListener(new SymFocus()); end.addFocusListener(new SymFocus()); length.addFocusListener(new SymFocus()); this.setVisible(true); } class SymFocus extends FocusAdapter { private String tf_start; private String tf_end; private String tf_length; private Interval interval = new Interval(); @Override public void focusLost(FocusEvent event) { Object obj = event.getSource(); if (obj == start) { tf_start = start.getText(); tf_end = end.getText(); interval.calculatestart(tf_start, tf_end); } else if (obj == end) { tf_start = start.getText(); tf_end = end.getText(); interval.calculateend(tf_start, tf_end); } else if (obj == length) { tf_start = start.getText(); tf_length = length.getText(); interval.calculatelength(tf_start, tf_length); } } } @Override public void update(Observable o, Object arg1) { System.out.println("her"); start.setText(((Interval) o).start); end.setText(((Interval) o).end); length.setText(((Interval) o).length); }}
------解决方案--------------------
根据你的逻辑,new 一个IntervalWindow然后添加到主题里面就行了,比如说: