package examples; import java.awt.GridLayout; import java.awt.event.ActionEvent; import javax.swing.*; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.PlainDocument; public class DocumentSharing { public static void main(String[] args) { JFrame f = new JFrame("Document Sharing"); f.setLayout(new GridLayout(0,1)); // Create two text areas and add them to the frame. final JTextArea top = new JTextArea(); final JTextArea bottom = new JTextArea(); f.add(top); f.add(bottom); final JToggleButton share = new JToggleButton(); share.setAction(new AbstractAction("share") { public void actionPerformed(ActionEvent arg0) { // When the button is pushed, have them share documents. if (share.isSelected()) bottom.setDocument(top.getDocument()); else { Document d = bottom.getDocument(); int length = d.getLength(); Document d2 = new PlainDocument(); try { d2.insertString(0, d.getText(0,length), null); } catch (BadLocationException e) { e.printStackTrace(); } bottom.setDocument(d2); } } }); f.add(share); f.pack(); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }