package dk.itu.oop.lecture11; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.*; class MVCExample extends JFrame { MVCExample(){ super(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(750, 100); setTitle("MVCExample"); JTextField tf1 = new JTextField(10); Document document = tf1.getDocument(); JTextField tf2 = new JTextField(document,null,10); DocumentSizeView dsv = new DocumentSizeView( document ); Container c = this.getContentPane(); c.setLayout(new FlowLayout()); c.add( tf1 ); c.add( tf2 ); c.add( dsv ); c.add( new DocumentSizeView( document ) ); new Thread( new InsertHaHa( document ) ).start(); tf1.setFont( new Font("Serif",Font.ITALIC,32) ); tf2.setFont( new Font("Serif",Font.BOLD,32) ); dsv.setFont( new Font("Serif",Font.PLAIN,32) ); setVisible(true); } public static void main(String[] a){ new MVCExample(); } } class DocumentSizeView extends JLabel implements DocumentListener { Document d; DocumentSizeView(Document d){ super(""); this.d = d; setText("Size: " + d.getLength() ); d.addDocumentListener(this); } public void changedUpdate(DocumentEvent e) {} public void insertUpdate(DocumentEvent e) { setText("Size: " + d.getLength()); } public void removeUpdate(DocumentEvent e){ setText("Size: " + d.getLength()); } } class InsertHaHa implements Runnable { Document d; InsertHaHa(Document d){ this.d = d; } public void run(){ int start = d.getStartPosition().getOffset(); while(true){ try{ Thread.sleep(3000); d.insertString(start, "HaHa", null); }catch(Exception ignore){}; } } }