Java/Swing JFC/TextArea

Материал из Java эксперт
Перейти к: навигация, поиск

Append some text to JTextArea

   <source lang="java">
 

import javax.swing.JTextArea; public class Main {

 public static void main(String[] argv) {
   JTextArea ta = new JTextArea("Initial Text");
   ta.append("some text");
 }

}


 </source>
   
  
 
  



A TransferHandler and JTextArea that will accept any drop at all

   <source lang="java">

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

// UTest.java //A test frame work for the UberHandler drop handler. This version has //no fancy Unicode characters for ease of use. (Note that "ease of use" //only applys to humans...the Java tools are quite happy with Unicode //characters. Not all text editors are, though...) // import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.io.BufferedReader; import java.io.Reader; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.TransferHandler; public class UTest {

 public static void main(String args[]) {
   JFrame frame = new JFrame("Debugging Drop Zone");
   frame.setSize(500, 300);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JTextArea jta = new JTextArea();
   frame.getContentPane().add(new JScrollPane(jta));
   UberHandler uh = new UberHandler();
   uh.setOutput(jta);
   jta.setTransferHandler(uh);
   frame.setVisible(true);
 }

} //UberHandler.java //A TransferHandler that will accept any drop at all. If a text area is //registered, debugging information will be sent there. Otherwise, all //debug information will be sent to stdout. // class UberHandler extends TransferHandler {

 JTextArea output;
 public void TransferHandler() {
 }
 public boolean canImport(JComponent dest, DataFlavor[] flavors) {
   // you bet we can!
   return true;
 }
 public boolean importData(JComponent src, Transferable transferable) {
   // Ok, here"s the tricky part...
   println("Receiving data from " + src);
   println("Transferable object is: " + transferable);
   println("Valid data flavors: ");
   DataFlavor[] flavors = transferable.getTransferDataFlavors();
   DataFlavor listFlavor = null;
   DataFlavor objectFlavor = null;
   DataFlavor readerFlavor = null;
   int lastFlavor = flavors.length - 1;
   // Check the flavors and see if we find one we like.
   // If we do, save it.
   for (int f = 0; f <= lastFlavor; f++) {
     println("  " + flavors[f]);
     if (flavors[f].isFlavorJavaFileListType()) {
       listFlavor = flavors[f];
     }
     if (flavors[f].isFlavorSerializedObjectType()) {
       objectFlavor = flavors[f];
     }
     if (flavors[f].isRepresentationClassReader()) {
       readerFlavor = flavors[f];
     }
   }
   // Ok, now try to display the content of the drop.
   try {
     DataFlavor bestTextFlavor = DataFlavor
         .selectBestTextFlavor(flavors);
     BufferedReader br = null;
     String line = null;
     if (bestTextFlavor != null) {
       println("Best text flavor: " + bestTextFlavor.getMimeType());
       println("Content:");
       Reader r = bestTextFlavor.getReaderForText(transferable);
       br = new BufferedReader(r);
       line = br.readLine();
       while (line != null) {
         println(line);
         line = br.readLine();
       }
       br.close();
     } else if (listFlavor != null) {
       java.util.List list = (java.util.List) transferable
           .getTransferData(listFlavor);
       println(list);
     } else if (objectFlavor != null) {
       println("Data is a java object:\n"
           + transferable.getTransferData(objectFlavor));
     } else if (readerFlavor != null) {
       println("Data is an InputStream:");
       br = new BufferedReader((Reader) transferable
           .getTransferData(readerFlavor));
       line = br.readLine();
       while (line != null) {
         println(line);
       }
       br.close();
     } else {
       // Don"t know this flavor type yet...
       println("No text representation to show.");
     }
     println("\n\n");
   } catch (Exception e) {
     println("Caught exception decoding transfer:");
     println(e);
     return false;
   }
   return true;
 }
 public void exportDone(JComponent source, Transferable data, int action) {
   // Just let us know when it occurs...
   System.err.println("Export Done.");
 }
 public void setOutput(JTextArea jta) {
   output = jta;
 }
 protected void print(Object o) {
   print(o.toString());
 }
 protected void print(String s) {
   if (output != null) {
     output.append(s);
   } else {
     System.out.println(s);
   }
 }
 protected void println(Object o) {
   println(o.toString());
 }
 protected void println(String s) {
   if (output != null) {
     output.append(s);
     output.append("\n");
   } else {
     System.out.println(s);
   }
 }
 protected void println() {
   println("");
 }
 public static void main(String args[]) {
   JFrame frame = new JFrame("Debugging Drop Zone");
   frame.setSize(500, 300);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JTextArea jta = new JTextArea();
   frame.getContentPane().add(new JScrollPane(jta));
   UberHandler uh = new UberHandler();
   uh.setOutput(jta);
   jta.setTransferHandler(uh);
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



Caret Sample

   <source lang="java">

import java.awt.BorderLayout; import java.awt.Container; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; public class CaretSample {

 public static void main(String args[]) {
   JFrame frame = new JFrame("Caret Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   Container content = frame.getContentPane();
   JTextArea textArea = new JTextArea();
   JScrollPane scrollPane = new JScrollPane(textArea);
   content.add(scrollPane, BorderLayout.CENTER);
   final JTextField dot = new JTextField();
   dot.setEditable(false);
   JPanel dotPanel = new JPanel(new BorderLayout());
   dotPanel.add(new JLabel("Dot: "), BorderLayout.WEST);
   dotPanel.add(dot, BorderLayout.CENTER);
   content.add(dotPanel, BorderLayout.NORTH);
   final JTextField mark = new JTextField();
   mark.setEditable(false);
   JPanel markPanel = new JPanel(new BorderLayout());
   markPanel.add(new JLabel("Mark: "), BorderLayout.WEST);
   markPanel.add(mark, BorderLayout.CENTER);
   content.add(markPanel, BorderLayout.SOUTH);
   CaretListener listener = new CaretListener() {
     public void caretUpdate(CaretEvent caretEvent) {
       dot.setText("" + caretEvent.getDot());
       mark.setText("" + caretEvent.getMark());
     }
   };
   textArea.addCaretListener(listener);
   frame.setSize(250, 150);
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



Copy selected text from one text area to another

   <source lang="java">
 

import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class Main extends JFrame {

 private JTextArea t1 = new JTextArea("this is a test", 10, 15), t2;
 private JButton copy = new JButton("Copy");
 public Main() {
   Box b = Box.createHorizontalBox();    
   b.add(new JScrollPane(t1));    
   copy.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       t2.setText(t1.getSelectedText());
     }
   });
   b.add(copy);
   t2 = new JTextArea(10, 15);
   t2.setEditable(false);
   b.add(new JScrollPane(t2));
   add(b); 
   setSize(425, 200);
   setVisible(true);
   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
 public static void main(String args[]) {
   new Main();
 }

}


 </source>
   
  
 
  



Creating a JTextArea Component

   <source lang="java">
 

import javax.swing.JTextArea; public class Main {

 public static void main(String[] argv) {
   // Create a text area with some initial text
   JTextArea textarea = new JTextArea("Initial Text");
   int rows = 20;
   int cols = 30;
   textarea = new JTextArea("Initial Text", rows, cols);
 }

}


 </source>
   
  
 
  



Cut Paste Sample

   <source lang="java">

import java.awt.BorderLayout; import java.awt.Container; import java.util.Hashtable; import javax.swing.Action; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.text.DefaultEditorKit; public class CutPasteSample {

 public static void main(String args[]) {
   JFrame frame = new JFrame("Cut/Paste Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   Container content = frame.getContentPane();
   JTextField textField = new JTextField();
   JTextArea textArea = new JTextArea();
   JScrollPane scrollPane = new JScrollPane(textArea);
   content.add(textField, BorderLayout.NORTH);
   content.add(scrollPane, BorderLayout.CENTER);
   Action actions[] = textField.getActions();
   Action cutAction = TextUtilities.findAction(actions,
       DefaultEditorKit.cutAction);
   Action copyAction = TextUtilities.findAction(actions,
       DefaultEditorKit.copyAction);
   Action pasteAction = TextUtilities.findAction(actions,
       DefaultEditorKit.pasteAction);
   JPanel panel = new JPanel();
   content.add(panel, BorderLayout.SOUTH);
   JButton cutButton = new JButton(cutAction);
   cutButton.setText("Cut");
   panel.add(cutButton);
   JButton copyButton = new JButton(copyAction);
   copyButton.setText("Copy");
   panel.add(copyButton);
   JButton pasteButton = new JButton(pasteAction);
   pasteButton.setText("Paste");
   panel.add(pasteButton);
   frame.setSize(250, 250);
   frame.setVisible(true);
 }

} class TextUtilities {

 private TextUtilities() {
 }
 public static Action findAction(Action actions[], String key) {
   Hashtable commands = new Hashtable();
   for (int i = 0; i < actions.length; i++) {
     Action action = actions[i];
     commands.put(action.getValue(Action.NAME), action);
   }
   return (Action) commands.get(key);
 }

}


 </source>
   
  
 
  



Delete the first 5 characters

   <source lang="java">
 

import javax.swing.JTextArea; public class Main {

 public static void main(String[] argv) {
   JTextArea ta = new JTextArea("Initial Text");
   int start = 0;
   int end = 5;
   ta.replaceRange(null, start, end);
 }

}


 </source>
   
  
 
  



Drag and drop: TextArea 2

   <source lang="java">

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

// DropTest.java //A simple drag & drop tester application. // import java.awt.BorderLayout; import java.awt.Color; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextArea; public class DropTest extends JFrame implements DropTargetListener {

 DropTarget dt;
 JTextArea ta;
 public DropTest() {
   super("Drop Test");
   setSize(300, 300);
   getContentPane().add(
       new JLabel("Drop a list from your file chooser here:"),
       BorderLayout.NORTH);
   ta = new JTextArea();
   ta.setBackground(Color.white);
   getContentPane().add(ta, BorderLayout.CENTER);
   // Set up our text area to recieve drops...
   // This class will handle drop events
   dt = new DropTarget(ta, this);
   setVisible(true);
 }
 public void dragEnter(DropTargetDragEvent dtde) {
   System.out.println("Drag Enter");
 }
 public void dragExit(DropTargetEvent dte) {
   System.out.println("Source: " + dte.getSource());
   System.out.println("Drag Exit");
 }
 public void dragOver(DropTargetDragEvent dtde) {
   System.out.println("Drag Over");
 }
 public void dropActionChanged(DropTargetDragEvent dtde) {
   System.out.println("Drop Action Changed");
 }
 public void drop(DropTargetDropEvent dtde) {
   try {
     // Ok, get the dropped object and try to figure out what it is
     Transferable tr = dtde.getTransferable();
     DataFlavor[] flavors = tr.getTransferDataFlavors();
     for (int i = 0; i < flavors.length; i++) {
       System.out.println("Possible flavor: "
           + flavors[i].getMimeType());
       // Check for file lists specifically
       if (flavors[i].isFlavorJavaFileListType()) {
         // Great! Accept copy drops...
         dtde.acceptDrop(DnDConstants.ACTION_COPY);
         ta.setText("Successful file list drop.\n\n");
         // And add the list of file names to our text area
         java.util.List list = (java.util.List) tr
             .getTransferData(flavors[i]);
         for (int j = 0; j < list.size(); j++) {
           ta.append(list.get(j) + "\n");
         }
         // If we made it this far, everything worked.
         dtde.dropComplete(true);
         return;
       }
     }
     // Hmm, the user must not have dropped a file list
     System.out.println("Drop failed: " + dtde);
     dtde.rejectDrop();
   } catch (Exception e) {
     e.printStackTrace();
     dtde.rejectDrop();
   }
 }
 public static void main(String args[]) {
   new DropTest();
 }

}


 </source>
   
  
 
  



Drop: TextArea

   <source lang="java">

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

/*

* NewDropTest.java A simple drag & drop tester application.
*/

import java.awt.BorderLayout; import java.awt.Color; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextArea; public class NewDropTest extends JFrame implements DropTargetListener {

 DropTarget dt;
 JTextArea ta;
 public NewDropTest() {
   super("Drop Test");
   setSize(300, 300);
   getContentPane().add(
       new JLabel("Drop a list from your file chooser here:"),
       BorderLayout.NORTH);
   ta = new JTextArea();
   ta.setBackground(Color.white);
   getContentPane().add(ta, BorderLayout.CENTER);
   // Set up our text area to recieve drops...
   // This class will handle drop events
   // dt = new DropTarget(ta, this);
   setVisible(true);
 }
 public void dragEnter(DropTargetDragEvent dtde) {
   System.out.println("Drag Enter");
 }
 public void dragExit(DropTargetEvent dte) {
   System.out.println("Source: " + dte.getSource());
   System.out.println("Drag Exit");
 }
 public void dragOver(DropTargetDragEvent dtde) {
   System.out.println("Drag Over");
 }
 public void dropActionChanged(DropTargetDragEvent dtde) {
   System.out.println("Drop Action Changed");
 }
 public void drop(DropTargetDropEvent dtde) {
   try {
     // Ok, get the dropped object and try to figure out what it is
     Transferable tr = dtde.getTransferable();
     DataFlavor[] flavors = tr.getTransferDataFlavors();
     for (int i = 0; i < flavors.length; i++) {
       System.out.println("Possible flavor: "
           + flavors[i].getMimeType());
       // Check for file lists specifically
       if (flavors[i].isFlavorJavaFileListType()) {
         // Great! Accept copy drops...
         dtde.acceptDrop(DnDConstants.ACTION_COPY);
         ta.setText("Successful file list drop.\n\n");
         // And add the list of file names to our text area
         java.util.List list = (java.util.List) tr
             .getTransferData(flavors[i]);
         for (int j = 0; j < list.size(); j++) {
           ta.append(list.get(j) + "\n");
         }
         // If we made it this far, everything worked.
         dtde.dropComplete(true);
         return;
       }
     }
     // Hmm, the user must not have dropped a file list
     System.out.println("Drop failed: " + dtde);
     dtde.rejectDrop();
   } catch (Exception e) {
     e.printStackTrace();
     dtde.rejectDrop();
   }
 }
 public static void main(String args[]) {
   new NewDropTest();
 }

}


 </source>
   
  
 
  



Enable word-wrapping

   <source lang="java">
 

import javax.swing.JTextArea; public class Main {

 public static void main(String[] argv) {
   JTextArea c = new JTextArea();
   c.setLineWrap(true);
   c.setWrapStyleWord(true);
 }

}


 </source>
   
  
 
  



Enabling Word-Wrapping and Line-Wrapping in a JTextArea Component

   <source lang="java">
 

import javax.swing.JTextArea; public class Main {

 public static void main(String[] argv) {
   JTextArea c = new JTextArea();
   // Enable line-wrapping
   c.setLineWrap(true);
   c.setWrapStyleWord(false);
 }

}


 </source>
   
  
 
  



Enumerate the content elements with a ElementIterator

   <source lang="java">
 

import javax.swing.JTextArea; import javax.swing.text.Document; import javax.swing.text.Element; import javax.swing.text.ElementIterator; public class Main {

 public static void main(String[] argv) throws Exception {
   JTextArea textArea = new JTextArea("word1 word2\nword3\nword4");
   Document doc = textArea.getDocument();
   ElementIterator it = new ElementIterator(doc.getDefaultRootElement());
   Element e;
   while ((e = it.next()) != null) {
     if (e.isLeaf()) {
       int rangeStart = e.getStartOffset();
       int rangeEnd = e.getEndOffset();
       String line = textArea.getText(rangeStart, rangeEnd - rangeStart);
       System.out.println(line);
     }
   }
 }

}


 </source>
   
  
 
  



Enumerating the Lines in a JTextArea Component

   <source lang="java">
 

import javax.swing.JTextArea; import javax.swing.text.Element; public class Main {

 public static void main(String[] argv) throws Exception {
   JTextArea textArea = new JTextArea("word1 word2\nword3\nword4");
   Element paragraph = textArea.getDocument().getDefaultRootElement();
   int contentCount = paragraph.getElementCount();
   for (int i = 0; i < contentCount; i++) {
     Element e = paragraph.getElement(i);
     int rangeStart = e.getStartOffset();
     int rangeEnd = e.getEndOffset();
     String line = textArea.getText(rangeStart, rangeEnd - rangeStart);
     System.out.println(line);
   }
 }

}


 </source>
   
  
 
  



Fancier custom caret class

   <source lang="java">

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

// FancyCaret.java //Another (fancier) custom caret class. // import java.awt.BorderLayout; import java.awt.Graphics; import java.awt.Rectangle; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultCaret; import javax.swing.text.JTextComponent; public class FancyCaret extends DefaultCaret {

 protected synchronized void damage(Rectangle r) {
   if (r == null)
     return;
   // give values to x,y,width,height (inherited from java.awt.Rectangle)
   x = r.x;
   y = r.y;
   height = r.height;
   // A value for width was probably set by paint(), which we leave alone.
   // But the first call to damage() precedes the first call to paint(), so
   // in this case we must be prepared to set a valid width, or else
   // paint()
   // will receive a bogus clip area and caret will not get drawn properly.
   if (width <= 0)
     width = getComponent().getWidth();
   repaint(); // calls getComponent().repaint(x, y, width, height)
 }
 public void paint(Graphics g) {
   JTextComponent comp = getComponent();
   if (comp == null)
     return;
   int dot = getDot();
   Rectangle r = null;
   char dotChar;
   try {
     r = comp.modelToView(dot);
     if (r == null)
       return;
     dotChar = comp.getText(dot, 1).charAt(0);
   } catch (BadLocationException e) {
     return;
   }
   if ((x != r.x) || (y != r.y)) {
     // paint() has been called directly, without a previous call to
     // damage(), so do some cleanup. (This happens, for example, when
     // the
     // text component is resized.)
     repaint(); // erase previous location of caret
     x = r.x; // Update dimensions (width gets set later in this method)
     y = r.y;
     height = r.height;
   }
   g.setColor(comp.getCaretColor());
   g.setXORMode(comp.getBackground()); // do this to draw in XOR mode
   if (dotChar == "\n") {
     int diam = r.height;
     if (isVisible())
       g.fillArc(r.x - diam / 2, r.y, diam, diam, 270, 180); // half
                                   // circle
     width = diam / 2 + 2;
     return;
   }
   if (dotChar == "\t")
     try {
       Rectangle nextr = comp.modelToView(dot + 1);
       if ((r.y == nextr.y) && (r.x < nextr.x)) {
         width = nextr.x - r.x;
         if (isVisible())
           g.fillRoundRect(r.x, r.y, width, r.height, 12, 12);
         return;
       } else
         dotChar = " ";
     } catch (BadLocationException e) {
       dotChar = " ";
     }
   width = g.getFontMetrics().charWidth(dotChar);
   if (isVisible())
     g.fillRect(r.x, r.y, width, r.height);
 }
 public static void main(String args[]) {
   JFrame frame = new JFrame("FancyCaret demo");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JTextArea area = new JTextArea(8, 32);
   area.setCaret(new FancyCaret());
   area.setText("VI\tVirgin Islands \nVA      Virginia\nVT\tVermont");
   frame.getContentPane().add(new JScrollPane(area), BorderLayout.CENTER);
   frame.pack();
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



Highlight of discontinous string

   <source lang="java">
 

import javax.swing.JTextArea; import javax.swing.text.DefaultHighlighter; import javax.swing.text.Highlighter; public class Main {

 public static void main(String args[]) {
   JTextArea area = new JTextArea(5, 20);
   area.setText("this is a test.");
   String charsToHighlight = "aeiouAEIOU";
   Highlighter h = area.getHighlighter();
   h.removeAllHighlights();
   String text = area.getText().toUpperCase();
   for (int i = 0; i < text.length(); i += 1) {
     char ch = text.charAt(i);
     if (charsToHighlight.indexOf(ch) >= 0)
       try {
         h.addHighlight(i, i + 1, DefaultHighlighter.DefaultPainter);
       } catch (Exception ble) {
       }
   }
 }

}


 </source>
   
  
 
  



Insert some text after the 5th character

   <source lang="java">
 

import javax.swing.JTextArea; public class Main {

 public static void main(String[] argv) {
   JTextArea ta = new JTextArea("Initial Text");
   int pos = 5;
   ta.insert("some text", pos);
 }

}


 </source>
   
  
 
  



Internationalized Graphical User Interfaces: unicode cut and paste

   <source lang="java">

/* Java Internationalization By Andy Deitsch, David Czarnecki ISBN: 0-596-00019-7 O"Reilly

  • /

/*import java.io.*; import java.awt.*; import java.awt.datatransfer.*; import java.awt.event.*; import javax.swing.*; public class CutAndPasteDemo extends JFrame implements ClipboardOwner {

 private static String TEMPFILE = "CUTPASTE.TMP";
 String davidMessage = "David says, \"\u05E9\u05DC\u05D5\u05DD \u05E2\u05D5\u05DC\u05DD\" \n";
 String andyMessage = "Andy also says, \"\u05E9\u05DC\u05D5\u05DD \u05E2\u05D5\u05DC\u05DD\"";
 private Clipboard clipboard;
 public void lostOwnership(Clipboard clipboard, Transferable contents) {
   System.out.println("Lost clipboard ownership");
 }
 JTextArea textArea1;
 JTextArea textArea2;
 public CutAndPasteDemo() {
   super("Cut And Paste Demonstration");
   clipboard = getToolkit().getSystemClipboard();
   GraphicsEnvironment.getLocalGraphicsEnvironment();
   Font font = new Font("LucidaSans", Font.PLAIN, 15);
   textArea1 = new JTextArea(davidMessage + andyMessage, 5, 25);
   textArea2 = new JTextArea("<Paste text here>", 5, 25);
   textArea1.setFont(font);
   textArea2.setFont(font);
   JPanel jPanel = new JPanel();
   JMenuBar jMenuBar = new JMenuBar();
   JMenuItem cutItem = new JMenuItem("Cut");
   JMenuItem pasteItem = new JMenuItem("Paste");
   JMenu jMenu = new JMenu("Edit");
   jMenu.add(cutItem);
   jMenu.add(pasteItem);
   cutItem.addActionListener(new CutActionListener());
   pasteItem.addActionListener(new PasteActionListener());
   jMenuBar.add(jMenu);
   jPanel.add(jMenuBar);
   jPanel.setLayout(new BoxLayout(jPanel,BoxLayout.Y_AXIS));
   jPanel.add(textArea1);
   jPanel.add(Box.createRigidArea(new Dimension(0,10)));
   jPanel.add(textArea2);
   getContentPane().add(jPanel, BorderLayout.CENTER);
 }
 class CutActionListener implements ActionListener {
   public void actionPerformed (ActionEvent event) {
     try {
       if (textArea1.getSelectedText() != null) {
         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(TEMPFILE), "UTF8"));
         bw.write(textArea1.getSelectedText());
         bw.close();
         textArea1.replaceSelection("");
       }
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
 class PasteActionListener implements ActionListener {
   public void actionPerformed (ActionEvent event) {
     try {
       BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(TEMPFILE), "UTF8"));
       StringBuffer text = new StringBuffer();
       String tempString;
       while ((tempString = br.readLine()) != null) {
         text.append(tempString);
       }
       br.close();
       textArea2.replaceSelection(text.toString());
     } catch (Exception e) {
     }
   }
 }
 public static void main(String[] args) {
   JFrame frame = new CutAndPasteDemo();
   frame.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {System.exit(0);}
   });
   frame.pack();
   frame.setVisible(true);
 }

}

  • /

import java.io.*; import java.awt.*; import java.awt.datatransfer.*; import java.awt.event.*; import javax.swing.*; public class CutAndPasteDemo extends JFrame implements ClipboardOwner {

 private static String TEMPFILE = "CUTPASTE.TMP";
 String davidMessage = "David says, \"\u05E9\u05DC\u05D5\u05DD" +
     "\u05E2\u05D5\u05DC\u05DD\" \n";
 String andyMessage = "Andy also says, \"\u05E9\u05DC\u05D5\u05DD" +
     "\u05E2\u05D5\u05DC\u05DD\"";
 private Clipboard clipboard;
 public void lostOwnership(Clipboard clipboard, Transferable contents) {
   System.out.println("Lost clipboard ownership");
 }
 JTextArea textArea1;
 JTextArea textArea2;
 public CutAndPasteDemo() {
   super("Cut And Paste Demonstration");
   clipboard = getToolkit().getSystemClipboard();
   GraphicsEnvironment.getLocalGraphicsEnvironment();
   Font font = new Font("LucidaSans", Font.PLAIN, 15);
   textArea1 = new JTextArea(davidMessage + andyMessage, 5, 25);
   textArea2 = new JTextArea("<Paste text here>", 5, 25);
   textArea1.setFont(font);
   textArea2.setFont(font);
   JPanel jPanel = new JPanel();
   JMenuBar jMenuBar = new JMenuBar();
   JMenuItem cutItem = new JMenuItem("Cut");
   JMenuItem pasteItem = new JMenuItem("Paste");
   JMenu jMenu = new JMenu("Edit");
   jMenu.add(cutItem);
   jMenu.add(pasteItem);
   cutItem.addActionListener(new CutActionListener());
   pasteItem.addActionListener(new PasteActionListener());
   jMenuBar.add(jMenu);
   jPanel.add(jMenuBar);
   jPanel.setLayout(new BoxLayout(jPanel,BoxLayout.Y_AXIS));
   jPanel.add(textArea1);
   jPanel.add(Box.createRigidArea(new Dimension(0,10)));
   jPanel.add(textArea2);
   getContentPane().add(jPanel, BorderLayout.CENTER);
 }
 class CutActionListener implements ActionListener {
   public void actionPerformed (ActionEvent event) {
     try {
       if (textArea1.getSelectedText() != null) {
         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new
             FileOutputStream(TEMPFILE), "UTF8"));
         bw.write(textArea1.getSelectedText());
         bw.close();
         textArea1.replaceSelection("");
       }
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
 class PasteActionListener implements ActionListener {
   public void actionPerformed (ActionEvent event) {
     try {
       BufferedReader br = new BufferedReader(new InputStreamReader(new
           FileInputStream(TEMPFILE), "UTF8"));
       StringBuffer text = new StringBuffer();
       String tempString;
       while ((tempString = br.readLine()) != null) {
         text.append(tempString);
       }
       br.close();
       textArea2.replaceSelection(text.toString());
     } catch (Exception e) {
     }
   }
 }
 public static void main(String[] args) {
   JFrame frame = new CutAndPasteDemo();
   frame.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {System.exit(0);}
   });
   frame.pack();
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



Modifying Text in a JTextArea Component

   <source lang="java">
 

import javax.swing.JTextArea; public class Main {

 public static void main(String[] argv) {
   // Create the text area
   JTextArea ta = new JTextArea("Initial Text");
   // Insert some text at the beginning
   int pos = 0;
   ta.insert("some text", pos);
 }

}


 </source>
   
  
 
  



Moving the Focus with the TAB Key in a JTextArea Component

   <source lang="java">
 

import java.awt.ruponent; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JTextArea; public class Main {

 public static void main(String[] argv) throws Exception {
   JTextArea component = new JTextArea();
   NextFocusAction nextFocusAction = new NextFocusAction();
   PrevFocusAction prevFocusAction = new PrevFocusAction();
   
   component.getActionMap().put(nextFocusAction.getValue(Action.NAME), nextFocusAction);
   component.getActionMap().put(prevFocusAction.getValue(Action.NAME), prevFocusAction);
 }

} class NextFocusAction extends AbstractAction{

 public NextFocusAction(){
   super("Move Focus Forwards");
 }
 public void actionPerformed(ActionEvent evt) {
   ((Component) evt.getSource()).transferFocus();
 }

} class PrevFocusAction extends AbstractAction {

 public PrevFocusAction(){
   super("Move Focus Backwards");
 }
 public void actionPerformed(ActionEvent evt) {
   ((Component) evt.getSource()).transferFocusBackward();
 }

}


 </source>
   
  
 
  



Replace text in text area

   <source lang="java">

import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; public class TextEditFrame extends JFrame {

 private JTextArea textArea = new JTextArea(8, 40);
 private JScrollPane scrollPane = new JScrollPane(textArea);
 private JTextField fromField = new JTextField(8);
 private JTextField toField = new JTextField(8);
 public TextEditFrame() {
   setTitle("TextEditTest");
   setSize(500, 300);
   addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   });
   Container contentPane = getContentPane();
   JPanel panel = new JPanel();
   JButton replaceButton = new JButton("Replace");
   panel.add(replaceButton);
   replaceButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent evt) {
       String from = fromField.getText();
       int start = textArea.getText().indexOf(from);
       if (start >= 0 && from.length() > 0)
         textArea.replaceRange(toField.getText(), start, start
             + from.length());
     }
   });
   panel.add(fromField);
   panel.add(new JLabel("with"));
   panel.add(toField);
   contentPane.add(panel, "South");
   contentPane.add(scrollPane, "Center");
 }
 public static void main(String[] args) {
   JFrame f = new TextEditFrame();
   f.show();
 }

}


 </source>
   
  
 
  



Replace the first 3 characters with some text

   <source lang="java">
 

import javax.swing.JTextArea; public class Main {

 public static void main(String[] argv) {
   JTextArea ta = new JTextArea("Initial Text");
   int start = 0;
   int end = 3;
   ta.replaceRange("new text", start, end);
 }

}


 </source>
   
  
 
  



Set the caret color

   <source lang="java">
 

import java.awt.Color; import javax.swing.JTextArea; import javax.swing.text.JTextComponent; public class Main {

 public static void main(String[] argv) throws Exception {
   JTextComponent c = new JTextArea();
   c.getCaretPosition();
   if (c.getCaretPosition() < c.getDocument().getLength()) {
     char ch = c.getText(c.getCaretPosition(), 1).charAt(0);
   }
   // Set the caret color
   c.setCaretColor(Color.red);
 }

}


 </source>
   
  
 
  



Set the end of the selection; ignored if new end is > start

   <source lang="java">
 

import javax.swing.JTextArea; import javax.swing.text.JTextComponent; public class Main {

 public static void main(String[] argv) {
   JTextComponent c = new JTextArea();
   c.setSelectionEnd(20);
 }

}


 </source>
   
  
 
  



Set the start of the selection; ignored if new start is < end

   <source lang="java">
 

import javax.swing.JTextArea; import javax.swing.text.JTextComponent; public class Main {

 public static void main(String[] argv) {
   JTextComponent c = new JTextArea();
   c.setSelectionStart(10);
 }

}


 </source>
   
  
 
  



Setting the Tab Size of a JTextArea Component

   <source lang="java">
 

import java.awt.Font; import javax.swing.JTextArea; public class Main {

 public static void main(String[] argv) {
   JTextArea textarea = new JTextArea();
   // Get the default tab size
   int tabSize = textarea.getTabSize(); // 8
   // Change the tab size
   tabSize = 4;
   textarea.setTabSize(tabSize);
   Font font = textarea.getFont();
   System.out.println(font);
 }

}


 </source>
   
  
 
  



Show line start end offsets in a JTextArea

   <source lang="java">

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

// OffsetTest.java //Show line start/end offsets in a JTextArea. // import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.text.BadLocationException; public class OffsetTest {

 public static void main(String[] args) {
   JTextArea ta = new JTextArea();
   ta.setLineWrap(true);
   ta.setWrapStyleWord(true);
   JScrollPane scroll = new JScrollPane(ta);
   // Add three lines of text to the JTextArea.
   ta.append("The first line.\n");
   ta.append("Line Two!\n");
   ta.append("This is the 3rd line of this document.");
   // Print some results . . .
   try {
     for (int n = 0; n < ta.getLineCount(); n += 1)
       System.out.println("line " + n + " starts at "
           + ta.getLineStartOffset(n) + ", ends at "
           + ta.getLineEndOffset(n));
     System.out.println();
     int n = 0;
     while (true) {
       System.out.print("offset " + n + " is on ");
       System.out.println("line " + ta.getLineOfOffset(n));
       n += 13;
     }
   } catch (BadLocationException ex) {
     System.out.println(ex);
   }
   // Layout . . .
   JFrame f = new JFrame();
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   f.getContentPane().add(scroll, java.awt.BorderLayout.CENTER);
   f.setSize(150, 150);
   f.setVisible(true);
 }

}


 </source>
   
  
 
  



Simple Editor Demo

   <source lang="java">

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

// SimpleEditor.java //An example showing several DefaultEditorKit features. This class is designed //to be easily extended for additional functionality. // import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Hashtable; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ImageIcon; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JOptionPane; import javax.swing.JTextArea; import javax.swing.JToolBar; import javax.swing.text.DefaultEditorKit; import javax.swing.text.JTextComponent; public class SimpleEditor extends JFrame {

 private Action openAction = new OpenAction();
 private Action saveAction = new SaveAction();
 private JTextComponent textComp;
 private Hashtable actionHash = new Hashtable();
 public static void main(String[] args) {
   SimpleEditor editor = new SimpleEditor();
   editor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   editor.setVisible(true);
 }
 // Create an editor.
 public SimpleEditor() {
   super("Swing Editor");
   textComp = createTextComponent();
   makeActionsPretty();
   Container content = getContentPane();
   content.add(textComp, BorderLayout.CENTER);
   content.add(createToolBar(), BorderLayout.NORTH);
   setJMenuBar(createMenuBar());
   setSize(320, 240);
 }
 // Create the JTextComponent subclass.
 protected JTextComponent createTextComponent() {
   JTextArea ta = new JTextArea();
   ta.setLineWrap(true);
   return ta;
 }
 // Add icons and friendly names to actions we care about.
 protected void makeActionsPretty() {
   Action a;
   a = textComp.getActionMap().get(DefaultEditorKit.cutAction);
   a.putValue(Action.SMALL_ICON, new ImageIcon("cut.gif"));
   a.putValue(Action.NAME, "Cut");
   a = textComp.getActionMap().get(DefaultEditorKit.copyAction);
   a.putValue(Action.SMALL_ICON, new ImageIcon("copy.gif"));
   a.putValue(Action.NAME, "Copy");
   a = textComp.getActionMap().get(DefaultEditorKit.pasteAction);
   a.putValue(Action.SMALL_ICON, new ImageIcon("paste.gif"));
   a.putValue(Action.NAME, "Paste");
   a = textComp.getActionMap().get(DefaultEditorKit.selectAllAction);
   a.putValue(Action.NAME, "Select All");
 }
 // Create a simple JToolBar with some buttons.
 protected JToolBar createToolBar() {
   JToolBar bar = new JToolBar();
   // Add simple actions for opening & saving.
   bar.add(getOpenAction()).setText("");
   bar.add(getSaveAction()).setText("");
   bar.addSeparator();
   // Add cut/copy/paste buttons.
   bar.add(textComp.getActionMap().get(DefaultEditorKit.cutAction))
       .setText("");
   bar.add(textComp.getActionMap().get(DefaultEditorKit.copyAction))
       .setText("");
   bar.add(textComp.getActionMap().get(DefaultEditorKit.pasteAction))
       .setText("");
   return bar;
 }
 // Create a JMenuBar with file & edit menus.
 protected JMenuBar createMenuBar() {
   JMenuBar menubar = new JMenuBar();
   JMenu file = new JMenu("File");
   JMenu edit = new JMenu("Edit");
   menubar.add(file);
   menubar.add(edit);
   file.add(getOpenAction());
   file.add(getSaveAction());
   file.add(new ExitAction());
   edit.add(textComp.getActionMap().get(DefaultEditorKit.cutAction));
   edit.add(textComp.getActionMap().get(DefaultEditorKit.copyAction));
   edit.add(textComp.getActionMap().get(DefaultEditorKit.pasteAction));
   edit.add(textComp.getActionMap().get(DefaultEditorKit.selectAllAction));
   return menubar;
 }
 // Subclass can override to use a different open action.
 protected Action getOpenAction() {
   return openAction;
 }
 // Subclass can override to use a different save action.
 protected Action getSaveAction() {
   return saveAction;
 }
 protected JTextComponent getTextComponent() {
   return textComp;
 }
 // ********** ACTION INNER CLASSES ********** //
 // A very simple exit action
 public class ExitAction extends AbstractAction {
   public ExitAction() {
     super("Exit");
   }
   public void actionPerformed(ActionEvent ev) {
     System.exit(0);
   }
 }
 // An action that opens an existing file
 class OpenAction extends AbstractAction {
   public OpenAction() {
     super("Open", new ImageIcon("icons/open.gif"));
   }
   // Query user for a filename and attempt to open and read the file into
   // the
   // text component.
   public void actionPerformed(ActionEvent ev) {
     JFileChooser chooser = new JFileChooser();
     if (chooser.showOpenDialog(SimpleEditor.this) != JFileChooser.APPROVE_OPTION)
       return;
     File file = chooser.getSelectedFile();
     if (file == null)
       return;
     FileReader reader = null;
     try {
       reader = new FileReader(file);
       textComp.read(reader, null);
     } catch (IOException ex) {
       JOptionPane.showMessageDialog(SimpleEditor.this,
           "File Not Found", "ERROR", JOptionPane.ERROR_MESSAGE);
     } finally {
       if (reader != null) {
         try {
           reader.close();
         } catch (IOException x) {
         }
       }
     }
   }
 }
 // An action that saves the document to a file
 class SaveAction extends AbstractAction {
   public SaveAction() {
     super("Save", new ImageIcon("icons/save.gif"));
   }
   // Query user for a filename and attempt to open and write the text
   // component"s content to the file.
   public void actionPerformed(ActionEvent ev) {
     JFileChooser chooser = new JFileChooser();
     if (chooser.showSaveDialog(SimpleEditor.this) != JFileChooser.APPROVE_OPTION)
       return;
     File file = chooser.getSelectedFile();
     if (file == null)
       return;
     FileWriter writer = null;
     try {
       writer = new FileWriter(file);
       textComp.write(writer);
     } catch (IOException ex) {
       JOptionPane.showMessageDialog(SimpleEditor.this,
           "File Not Saved", "ERROR", JOptionPane.ERROR_MESSAGE);
     } finally {
       if (writer != null) {
         try {
           writer.close();
         } catch (IOException x) {
         }
       }
     }
   }
 }

}


 </source>
   
  
 
  



TextArea Background Image

   <source lang="java">

import java.awt.BorderLayout; import java.awt.Container; import java.awt.Graphics; import java.awt.Image; import javax.swing.GrayFilter; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class BackgroundSample {

 public static void main(String args[]) {
   JFrame frame = new JFrame("Background Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   final ImageIcon imageIcon = new ImageIcon("draft.gif");
   JTextArea textArea = new JTextArea() {
     Image image = imageIcon.getImage();
     Image grayImage = GrayFilter.createDisabledImage(image);
     {
       setOpaque(false);
     }
     public void paint(Graphics g) {
       g.drawImage(grayImage, 0, 0, this);
       super.paint(g);
     }
   };
   JScrollPane scrollPane = new JScrollPane(textArea);
   Container content = frame.getContentPane();
   content.add(scrollPane, BorderLayout.CENTER);
   frame.setSize(250, 250);
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



TextArea Elements

   <source lang="java">

/* Core SWING Advanced Programming By Kim Topley ISBN: 0 13 083292 8 Publisher: Prentice Hall

  • /

import javax.swing.*; import javax.swing.text.*; public class TextAreaElements {

 public static void main(String[] args) {
   try {
       UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
   } catch (Exception evt) {}
 
   JFrame f = new JFrame("Text Area Elements");
   JTextArea ta = new JTextArea(5, 32);
   ta.setText("That"s one small step for man...\nOne giant leap for mankind.");
   f.getContentPane().add(ta);
   f.pack();
   f.setVisible(true);
   ((AbstractDocument)ta.getDocument()).dump(System.out);
 }

}


 </source>
   
  
 
  



TextArea Elements 2

   <source lang="java">

/* Core SWING Advanced Programming By Kim Topley ISBN: 0 13 083292 8 Publisher: Prentice Hall

  • /

import javax.swing.JFrame; import javax.swing.JTextArea; import javax.swing.UIManager; import javax.swing.text.AbstractDocument; public class TextAreaElements2 {

 public static void main(String[] args) {
   try {
       UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
   } catch (Exception evt) {}
 
   JFrame f = new JFrame("Text Area Elements 2");
   JTextArea ta = new JTextArea(5, 32);
   ta
       .setText("That"s one small step for man...\nOne giant leap for mankind.");
   ta.setLineWrap(true);
   ta.setWrapStyleWord(true);
   f.getContentPane().add(ta);
   f.setSize(100, 100);
   f.setVisible(true);
   ((AbstractDocument) ta.getDocument()).dump(System.out);
 }

}


 </source>
   
  
 
  



TextArea Example

   <source lang="java">

import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.UIManager; public class TextAreaExample {

 public static void main(String[] args) {
   JFrame f = new JFrame("Text Area Examples");
   JPanel upperPanel = new JPanel();
   JPanel lowerPanel = new JPanel();
   f.getContentPane().add(upperPanel, "North");
   f.getContentPane().add(lowerPanel, "South");
   upperPanel.add(new JTextArea(content));
   upperPanel.add(new JTextArea(content, 6, 10));
   upperPanel.add(new JTextArea(content, 3, 8));
   lowerPanel.add(new JScrollPane(new JTextArea(content, 6, 8)));
   JTextArea ta = new JTextArea(content, 6, 8);
   ta.setLineWrap(true);
   lowerPanel.add(new JScrollPane(ta));
   ta = new JTextArea(content, 6, 8);
   ta.setLineWrap(true);
   ta.setWrapStyleWord(true);
   lowerPanel.add(new JScrollPane(ta));
   f.pack();
   f.setVisible(true);
 }
 static String content = "Here men from the planet Earth\n"
     + "first set foot upon the Moon,\n" + "July 1969, AD.\n"
     + "We came in peace for all mankind.";

}


 </source>
   
  
 
  



TextArea Sample

   <source lang="java">

import java.awt.Container; import java.awt.GridLayout; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class TextAreaSample {

 public static void main(String args[]) {
   String title = (args.length == 0 ? "TextArea Example" : args[0]);
   JFrame frame = new JFrame(title);
   Container content = frame.getContentPane();
   content.setLayout(new GridLayout(0, 2));
   JTextArea leftTextArea = new JTextArea();
   content.add(leftTextArea);
   leftTextArea.paste();
   JTextArea rightTextArea = new JTextArea() {
     public boolean isManagingFocus() {
       return false;
     }
   };
   rightTextArea.paste();
   JScrollPane rightPane = new JScrollPane(rightTextArea);
   content.add(rightPane);
   frame.setSize(250, 150);
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



TextArea Share Model

   <source lang="java">

import java.awt.Container; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.text.Document; public class ShareModel {

 public static void main(String args[]) {
   JFrame f = new JFrame("Sharing Sample");
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   Container content = f.getContentPane();
   JTextArea textarea1 = new JTextArea();
   Document document = textarea1.getDocument();
   JTextArea textarea2 = new JTextArea(document);
   JTextArea textarea3 = new JTextArea(document);
   content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
   content.add(new JScrollPane(textarea1));
   content.add(new JScrollPane(textarea2));
   content.add(new JScrollPane(textarea3));
   f.setSize(300, 400);
   f.setVisible(true);
 }

}


 </source>
   
  
 
  



TextArea Views 2

   <source lang="java">

/* Core SWING Advanced Programming By Kim Topley ISBN: 0 13 083292 8 Publisher: Prentice Hall

  • /

import java.io.PrintStream; import javax.swing.JFrame; import javax.swing.JTextArea; import javax.swing.UIManager; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.JTextComponent; import javax.swing.text.View; public class TextAreaViews2 {

 public static void main(String[] args) {
   try {
       UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
   } catch (Exception evt) {}
 
   JFrame f = new JFrame("Text Area Views #2");
   JTextArea ta = new JTextArea(5, 32);
   ta
       .setText("That"s one small step for man...\nOne giant leap for mankind.");
   ta.setLineWrap(true);
   ta.setWrapStyleWord(true);
   f.getContentPane().add(ta);
   f.setSize(200, 100);
   f.setVisible(true);
   ViewDisplayer.displayViews(ta, System.out);
   try {
     Thread.sleep(30000);
     ViewDisplayer.displayViews(ta, System.out);
   } catch (InterruptedException e) {
   }
 }

} class ViewDisplayer {

 public static void displayViews(JTextComponent comp, PrintStream out) {
   View rootView = comp.getUI().getRootView(comp);
   displayView(rootView, 0, comp.getDocument(), out);
 }
 public static void displayView(View view, int indent, Document doc,
     PrintStream out) {
   String name = view.getClass().getName();
   for (int i = 0; i < indent; i++) {
     out.print("\t");
   }
   int start = view.getStartOffset();
   int end = view.getEndOffset();
   out.println(name + "; offsets [" + start + ", " + end + "]");
   int viewCount = view.getViewCount();
   if (viewCount == 0) {
     int length = Math.min(32, end - start);
     try {
       String txt = doc.getText(start, length);
       for (int i = 0; i < indent + 1; i++) {
         out.print("\t");
       }
       out.println("[" + txt + "]");
     } catch (BadLocationException e) {
     }
   } else {
     for (int i = 0; i < viewCount; i++) {
       displayView(view.getView(i), indent + 1, doc, out);
     }
   }
 }

}


 </source>
   
  
 
  



TextArea Views 3

   <source lang="java">

/* Core SWING Advanced Programming By Kim Topley ISBN: 0 13 083292 8 Publisher: Prentice Hall

  • /

import java.io.PrintStream; import javax.swing.JFrame; import javax.swing.JTextArea; import javax.swing.UIManager; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.JTextComponent; import javax.swing.text.View; public class TextAreaViews {

 public static void main(String[] args) {
   try {
       UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
   } catch (Exception evt) {}
 
   JFrame f = new JFrame("Text Area Views");
   JTextArea ta = new JTextArea(5, 32);
   ta
       .setText("That"s one small step for man...\nOne giant leap for mankind.");
   f.getContentPane().add(ta);
   f.setSize(200, 100);
   f.setVisible(true);
   ViewDisplayer.displayViews(ta, System.out);
   try {
     Thread.sleep(30000);
     ViewDisplayer.displayViews(ta, System.out);
   } catch (InterruptedException e) {
   }
 }

} class ViewDisplayer {

 public static void displayViews(JTextComponent comp, PrintStream out) {
   View rootView = comp.getUI().getRootView(comp);
   displayView(rootView, 0, comp.getDocument(), out);
 }
 public static void displayView(View view, int indent, Document doc,
     PrintStream out) {
   String name = view.getClass().getName();
   for (int i = 0; i < indent; i++) {
     out.print("\t");
   }
   int start = view.getStartOffset();
   int end = view.getEndOffset();
   out.println(name + "; offsets [" + start + ", " + end + "]");
   int viewCount = view.getViewCount();
   if (viewCount == 0) {
     int length = Math.min(32, end - start);
     try {
       String txt = doc.getText(start, length);
       for (int i = 0; i < indent + 1; i++) {
         out.print("\t");
       }
       out.println("[" + txt + "]");
     } catch (BadLocationException e) {
     }
   } else {
     for (int i = 0; i < viewCount; i++) {
       displayView(view.getView(i), indent + 1, doc, out);
     }
   }
 }

}


 </source>
   
  
 
  



TextArea with Unicode

   <source lang="java">

/* Java Internationalization By Andy Deitsch, David Czarnecki ISBN: 0-596-00019-7 O"Reilly

  • /

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JTextAreaDemo extends JFrame {

 String davidMessage = "David says, \"\u05E9\u05DC\u05D5\u05DD \u05E2\u05D5\u05DC\u05DD\" \n";
 String andyMessage = "Andy also says, \"\u05E9\u05DC\u05D5\u05DD \u05E2\u05D5\u05DC\u05DD\"";
 public JTextAreaDemo() {
   super("JTextAreaDemo");
   GraphicsEnvironment.getLocalGraphicsEnvironment();
   Font font = new Font("LucidaSans", Font.PLAIN, 40);
   JTextArea textArea = new JTextArea(davidMessage + andyMessage);
   textArea.setFont(font);
   this.getContentPane().add(textArea);
   textArea.show();
 }
 public static void main(String[] args) {
   JFrame frame = new JTextAreaDemo();
   frame.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {System.exit(0);}
   });
   frame.pack();
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



Text Component Demo

   <source lang="java">

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

/* TextDemo.java is a 1.4 application that requires no other files. */ import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; public class TextDemo extends JPanel implements ActionListener {

 protected JTextField textField;
 protected JTextArea textArea;
 private final static String newline = "\n";
 public TextDemo() {
   super(new GridBagLayout());
   textField = new JTextField(20);
   textField.addActionListener(this);
   textArea = new JTextArea(5, 20);
   textArea.setEditable(false);
   JScrollPane scrollPane = new JScrollPane(textArea,
       JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
       JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
   //Add Components to this panel.
   GridBagConstraints c = new GridBagConstraints();
   c.gridwidth = GridBagConstraints.REMAINDER;
   c.fill = GridBagConstraints.HORIZONTAL;
   add(textField, c);
   c.fill = GridBagConstraints.BOTH;
   c.weightx = 1.0;
   c.weighty = 1.0;
   add(scrollPane, c);
 }
 public void actionPerformed(ActionEvent evt) {
   String text = textField.getText();
   textArea.append(text + newline);
   textField.selectAll();
   //Make sure the new text is visible, even if there
   //was a selection in the text area.
   textArea.setCaretPosition(textArea.getDocument().getLength());
 }
 /**
  * Create the GUI and show it. For thread safety, this method should be
  * invoked from the event-dispatching thread.
  */
 private static void createAndShowGUI() {
   //Make sure we have nice window decorations.
   JFrame.setDefaultLookAndFeelDecorated(true);
   //Create and set up the window.
   JFrame frame = new JFrame("TextDemo");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   //Create and set up the content pane.
   JComponent newContentPane = new TextDemo();
   newContentPane.setOpaque(true); //content panes must be opaque
   frame.setContentPane(newContentPane);
   //Display the window.
   frame.pack();
   frame.setVisible(true);
 }
 public static void main(String[] args) {
   //Schedule a job for the event-dispatching thread:
   //creating and showing this application"s GUI.
   javax.swing.SwingUtilities.invokeLater(new Runnable() {
     public void run() {
       createAndShowGUI();
     }
   });
 }

}


 </source>
   
  
 
  



Text Component Demo 2

   <source lang="java">

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

/*

* TextComponentDemo.java is a 1.4 application that requires one additional
* file: DocumentSizeFilter
*/

import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Event; import java.awt.GridLayout; import java.awt.Insets; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.HashMap; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.InputMap; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextArea; import javax.swing.JTextPane; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.UndoableEditEvent; import javax.swing.event.UndoableEditListener; import javax.swing.text.AbstractDocument; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultEditorKit; import javax.swing.text.Document; import javax.swing.text.DocumentFilter; import javax.swing.text.JTextComponent; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; import javax.swing.text.StyledEditorKit; import javax.swing.undo.CannotRedoException; import javax.swing.undo.CannotUndoException; import javax.swing.undo.UndoManager; public class TextComponentDemo extends JFrame {

 JTextPane textPane;
 AbstractDocument doc;
 static final int MAX_CHARACTERS = 300;
 JTextArea changeLog;
 String newline = "\n";
 HashMap actions;
 //undo helpers
 protected UndoAction undoAction;
 protected RedoAction redoAction;
 protected UndoManager undo = new UndoManager();
 public TextComponentDemo() {
   super("TextComponentDemo");
   //Create the text pane and configure it.
   textPane = new JTextPane();
   textPane.setCaretPosition(0);
   textPane.setMargin(new Insets(5, 5, 5, 5));
   StyledDocument styledDoc = textPane.getStyledDocument();
   if (styledDoc instanceof AbstractDocument) {
     doc = (AbstractDocument) styledDoc;
     doc.setDocumentFilter(new DocumentSizeFilter(MAX_CHARACTERS));
   } else {
     System.err
         .println("Text pane"s document isn"t an AbstractDocument!");
     System.exit(-1);
   }
   JScrollPane scrollPane = new JScrollPane(textPane);
   scrollPane.setPreferredSize(new Dimension(200, 200));
   //Create the text area for the status log and configure it.
   changeLog = new JTextArea(5, 30);
   changeLog.setEditable(false);
   JScrollPane scrollPaneForLog = new JScrollPane(changeLog);
   //Create a split pane for the change log and the text area.
   JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
       scrollPane, scrollPaneForLog);
   splitPane.setOneTouchExpandable(true);
   //Create the status area.
   JPanel statusPane = new JPanel(new GridLayout(1, 1));
   CaretListenerLabel caretListenerLabel = new CaretListenerLabel(
       "Caret Status");
   statusPane.add(caretListenerLabel);
   //Add the components.
   getContentPane().add(splitPane, BorderLayout.CENTER);
   getContentPane().add(statusPane, BorderLayout.PAGE_END);
   //Set up the menu bar.
   createActionTable(textPane);
   JMenu editMenu = createEditMenu();
   JMenu styleMenu = createStyleMenu();
   JMenuBar mb = new JMenuBar();
   mb.add(editMenu);
   mb.add(styleMenu);
   setJMenuBar(mb);
   //Add some key bindings.
   addBindings();
   //Put the initial text into the text pane.
   initDocument();
   //Start watching for undoable edits and caret changes.
   doc.addUndoableEditListener(new MyUndoableEditListener());
   textPane.addCaretListener(caretListenerLabel);
   doc.addDocumentListener(new MyDocumentListener());
 }
 //This listens for and reports caret movements.
 protected class CaretListenerLabel extends JLabel implements CaretListener {
   public CaretListenerLabel(String label) {
     super(label);
   }
   //Might not be invoked from the event dispatching thread.
   public void caretUpdate(CaretEvent e) {
     displaySelectionInfo(e.getDot(), e.getMark());
   }
   //This method can be invoked from any thread. It
   //invokes the setText and modelToView methods, which
   //must run in the event dispatching thread. We use
   //invokeLater to schedule the code for execution
   //in the event dispatching thread.
   protected void displaySelectionInfo(final int dot, final int mark) {
     SwingUtilities.invokeLater(new Runnable() {
       public void run() {
         if (dot == mark) { // no selection
           try {
             Rectangle caretCoords = textPane.modelToView(dot);
             //Convert it to view coordinates.
             setText("caret: text position: " + dot
                 + ", view location = [" + caretCoords.x
                 + ", " + caretCoords.y + "]" + newline);
           } catch (BadLocationException ble) {
             setText("caret: text position: " + dot + newline);
           }
         } else if (dot < mark) {
           setText("selection from: " + dot + " to " + mark
               + newline);
         } else {
           setText("selection from: " + mark + " to " + dot
               + newline);
         }
       }
     });
   }
 }
 //This one listens for edits that can be undone.
 protected class MyUndoableEditListener implements UndoableEditListener {
   public void undoableEditHappened(UndoableEditEvent e) {
     //Remember the edit and update the menus.
     undo.addEdit(e.getEdit());
     undoAction.updateUndoState();
     redoAction.updateRedoState();
   }
 }
 //And this one listens for any changes to the document.
 protected class MyDocumentListener implements DocumentListener {
   public void insertUpdate(DocumentEvent e) {
     displayEditInfo(e);
   }
   public void removeUpdate(DocumentEvent e) {
     displayEditInfo(e);
   }
   public void changedUpdate(DocumentEvent e) {
     displayEditInfo(e);
   }
   private void displayEditInfo(DocumentEvent e) {
     Document document = (Document) e.getDocument();
     int changeLength = e.getLength();
     changeLog.append(e.getType().toString() + ": " + changeLength
         + " character" + ((changeLength == 1) ? ". " : "s. ")
         + " Text length = " + document.getLength() + "." + newline);
   }
 }
 //Add a couple of emacs key bindings for navigation.
 protected void addBindings() {
   InputMap inputMap = textPane.getInputMap();
   //Ctrl-b to go backward one character
   KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_B, Event.CTRL_MASK);
   inputMap.put(key, DefaultEditorKit.backwardAction);
   //Ctrl-f to go forward one character
   key = KeyStroke.getKeyStroke(KeyEvent.VK_F, Event.CTRL_MASK);
   inputMap.put(key, DefaultEditorKit.forwardAction);
   //Ctrl-p to go up one line
   key = KeyStroke.getKeyStroke(KeyEvent.VK_P, Event.CTRL_MASK);
   inputMap.put(key, DefaultEditorKit.upAction);
   //Ctrl-n to go down one line
   key = KeyStroke.getKeyStroke(KeyEvent.VK_N, Event.CTRL_MASK);
   inputMap.put(key, DefaultEditorKit.downAction);
 }
 //Create the edit menu.
 protected JMenu createEditMenu() {
   JMenu menu = new JMenu("Edit");
   //Undo and redo are actions of our own creation.
   undoAction = new UndoAction();
   menu.add(undoAction);
   redoAction = new RedoAction();
   menu.add(redoAction);
   menu.addSeparator();
   //These actions come from the default editor kit.
   //Get the ones we want and stick them in the menu.
   menu.add(getActionByName(DefaultEditorKit.cutAction));
   menu.add(getActionByName(DefaultEditorKit.copyAction));
   menu.add(getActionByName(DefaultEditorKit.pasteAction));
   menu.addSeparator();
   menu.add(getActionByName(DefaultEditorKit.selectAllAction));
   return menu;
 }
 //Create the style menu.
 protected JMenu createStyleMenu() {
   JMenu menu = new JMenu("Style");
   Action action = new StyledEditorKit.BoldAction();
   action.putValue(Action.NAME, "Bold");
   menu.add(action);
   action = new StyledEditorKit.ItalicAction();
   action.putValue(Action.NAME, "Italic");
   menu.add(action);
   action = new StyledEditorKit.UnderlineAction();
   action.putValue(Action.NAME, "Underline");
   menu.add(action);
   menu.addSeparator();
   menu.add(new StyledEditorKit.FontSizeAction("12", 12));
   menu.add(new StyledEditorKit.FontSizeAction("14", 14));
   menu.add(new StyledEditorKit.FontSizeAction("18", 18));
   menu.addSeparator();
   menu.add(new StyledEditorKit.FontFamilyAction("Serif", "Serif"));
   menu
       .add(new StyledEditorKit.FontFamilyAction("SansSerif",
           "SansSerif"));
   menu.addSeparator();
   menu.add(new StyledEditorKit.ForegroundAction("Red", Color.red));
   menu.add(new StyledEditorKit.ForegroundAction("Green", Color.green));
   menu.add(new StyledEditorKit.ForegroundAction("Blue", Color.blue));
   menu.add(new StyledEditorKit.ForegroundAction("Black", Color.black));
   return menu;
 }
 protected void initDocument() {
   String initString[] = { "Use the mouse to place the caret.",
       "Use the edit menu to cut, copy, paste, and select text.",
       "Also to undo and redo changes.",
       "Use the style menu to change the style of the text.",
       "Use these emacs key bindings to move the caret:",
       "ctrl-f, ctrl-b, ctrl-n, ctrl-p." };
   SimpleAttributeSet[] attrs = initAttributes(initString.length);
   try {
     for (int i = 0; i < initString.length; i++) {
       doc.insertString(doc.getLength(), initString[i] + newline,
           attrs[i]);
     }
   } catch (BadLocationException ble) {
     System.err.println("Couldn"t insert initial text.");
   }
 }
 protected SimpleAttributeSet[] initAttributes(int length) {
   //Hard-code some attributes.
   SimpleAttributeSet[] attrs = new SimpleAttributeSet[length];
   attrs[0] = new SimpleAttributeSet();
   StyleConstants.setFontFamily(attrs[0], "SansSerif");
   StyleConstants.setFontSize(attrs[0], 16);
   attrs[1] = new SimpleAttributeSet(attrs[0]);
   StyleConstants.setBold(attrs[1], true);
   attrs[2] = new SimpleAttributeSet(attrs[0]);
   StyleConstants.setItalic(attrs[2], true);
   attrs[3] = new SimpleAttributeSet(attrs[0]);
   StyleConstants.setFontSize(attrs[3], 20);
   attrs[4] = new SimpleAttributeSet(attrs[0]);
   StyleConstants.setFontSize(attrs[4], 12);
   attrs[5] = new SimpleAttributeSet(attrs[0]);
   StyleConstants.setForeground(attrs[5], Color.red);
   return attrs;
 }
 //The following two methods allow us to find an
 //action provided by the editor kit by its name.
 private void createActionTable(JTextComponent textComponent) {
   actions = new HashMap();
   Action[] actionsArray = textComponent.getActions();
   for (int i = 0; i < actionsArray.length; i++) {
     Action a = actionsArray[i];
     actions.put(a.getValue(Action.NAME), a);
   }
 }
 private Action getActionByName(String name) {
   return (Action) (actions.get(name));
 }
 class UndoAction extends AbstractAction {
   public UndoAction() {
     super("Undo");
     setEnabled(false);
   }
   public void actionPerformed(ActionEvent e) {
     try {
       undo.undo();
     } catch (CannotUndoException ex) {
       System.out.println("Unable to undo: " + ex);
       ex.printStackTrace();
     }
     updateUndoState();
     redoAction.updateRedoState();
   }
   protected void updateUndoState() {
     if (undo.canUndo()) {
       setEnabled(true);
       putValue(Action.NAME, undo.getUndoPresentationName());
     } else {
       setEnabled(false);
       putValue(Action.NAME, "Undo");
     }
   }
 }
 class RedoAction extends AbstractAction {
   public RedoAction() {
     super("Redo");
     setEnabled(false);
   }
   public void actionPerformed(ActionEvent e) {
     try {
       undo.redo();
     } catch (CannotRedoException ex) {
       System.out.println("Unable to redo: " + ex);
       ex.printStackTrace();
     }
     updateRedoState();
     undoAction.updateUndoState();
   }
   protected void updateRedoState() {
     if (undo.canRedo()) {
       setEnabled(true);
       putValue(Action.NAME, undo.getRedoPresentationName());
     } else {
       setEnabled(false);
       putValue(Action.NAME, "Redo");
     }
   }
 }
 /**
  * Create the GUI and show it. For thread safety, this method should be
  * invoked from the event-dispatching thread.
  */
 private static void createAndShowGUI() {
   //Make sure we have nice window decorations.
   JFrame.setDefaultLookAndFeelDecorated(true);
   //Create and set up the window.
   final TextComponentDemo frame = new TextComponentDemo();
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   //Display the window.
   frame.pack();
   frame.setVisible(true);
 }
 //The standard main method.
 public static void main(String[] args) {
   //Schedule a job for the event-dispatching thread:
   //creating and showing this application"s GUI.
   javax.swing.SwingUtilities.invokeLater(new Runnable() {
     public void run() {
       createAndShowGUI();
     }
   });
 }

} /* A 1.4 class used by TextComponentDemo.java. */ class DocumentSizeFilter extends DocumentFilter {

 int maxCharacters;
 boolean DEBUG = false;
 public DocumentSizeFilter(int maxChars) {
   maxCharacters = maxChars;
 }
 public void insertString(FilterBypass fb, int offs, String str,
     AttributeSet a) throws BadLocationException {
   if (DEBUG) {
     System.out.println("in DocumentSizeFilter"s insertString method");
   }
   //This rejects the entire insertion if it would make
   //the contents too long. Another option would be
   //to truncate the inserted string so the contents
   //would be exactly maxCharacters in length.
   if ((fb.getDocument().getLength() + str.length()) <= maxCharacters)
     super.insertString(fb, offs, str, a);
   else
     Toolkit.getDefaultToolkit().beep();
 }
 public void replace(FilterBypass fb, int offs, int length, String str,
     AttributeSet a) throws BadLocationException {
   if (DEBUG) {
     System.out.println("in DocumentSizeFilter"s replace method");
   }
   //This rejects the entire replacement if it would make
   //the contents too long. Another option would be
   //to truncate the replacement string so the contents
   //would be exactly maxCharacters in length.
   if ((fb.getDocument().getLength() + str.length() - length) <= maxCharacters)
     super.replace(fb, offs, length, str, a);
   else
     Toolkit.getDefaultToolkit().beep();
 }

}


 </source>
   
  
 
  



Text Components Sampler Demo

   <source lang="java">

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

/*

* TextSamplerDemo.java is a 1.4 application that requires the following files:
* TextSamplerDemoHelp.html (which references images/dukeWaveRed.gif)
* images/Pig.gif images/sound.gif
*/

import java.awt.BorderLayout; import java.awt.Container; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Insets; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JEditorPane; import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.text.BadLocationException; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyleContext; import javax.swing.text.StyledDocument; public class TextSamplerDemo extends JPanel implements ActionListener {

 private String newline = "\n";
 protected static final String textFieldString = "JTextField";
 protected static final String passwordFieldString = "JPasswordField";
 protected static final String ftfString = "JFormattedTextField";
 protected static final String buttonString = "JButton";
 protected JLabel actionLabel;
 public TextSamplerDemo() {
   setLayout(new BorderLayout());
   //Create a regular text field.
   JTextField textField = new JTextField(10);
   textField.setActionCommand(textFieldString);
   textField.addActionListener(this);
   //Create a password field.
   JPasswordField passwordField = new JPasswordField(10);
   passwordField.setActionCommand(passwordFieldString);
   passwordField.addActionListener(this);
   //Create a formatted text field.
   JFormattedTextField ftf = new JFormattedTextField(java.util.Calendar
       .getInstance().getTime());
   ftf.setActionCommand(textFieldString);
   ftf.addActionListener(this);
   //Create some labels for the fields.
   JLabel textFieldLabel = new JLabel(textFieldString + ": ");
   textFieldLabel.setLabelFor(textField);
   JLabel passwordFieldLabel = new JLabel(passwordFieldString + ": ");
   passwordFieldLabel.setLabelFor(passwordField);
   JLabel ftfLabel = new JLabel(ftfString + ": ");
   ftfLabel.setLabelFor(ftf);
   //Create a label to put messages during an action event.
   actionLabel = new JLabel("Type text and then Enter in a field.");
   actionLabel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
   //Lay out the text controls and the labels.
   JPanel textControlsPane = new JPanel();
   GridBagLayout gridbag = new GridBagLayout();
   GridBagConstraints c = new GridBagConstraints();
   textControlsPane.setLayout(gridbag);
   JLabel[] labels = { textFieldLabel, passwordFieldLabel, ftfLabel };
   JTextField[] textFields = { textField, passwordField, ftf };
   addLabelTextRows(labels, textFields, gridbag, textControlsPane);
   c.gridwidth = GridBagConstraints.REMAINDER; //last
   c.anchor = GridBagConstraints.WEST;
   c.weightx = 1.0;
   textControlsPane.add(actionLabel, c);
   textControlsPane.setBorder(BorderFactory.createCompoundBorder(
       BorderFactory.createTitledBorder("Text Fields"), BorderFactory
           .createEmptyBorder(5, 5, 5, 5)));
   //Create a text area.
   JTextArea textArea = new JTextArea("This is an editable JTextArea. "
       + "A text area is a \"plain\" text component, "
       + "which means that although it can display text "
       + "in any font, all of the text is in the same font.");
   textArea.setFont(new Font("Serif", Font.ITALIC, 16));
   textArea.setLineWrap(true);
   textArea.setWrapStyleWord(true);
   JScrollPane areaScrollPane = new JScrollPane(textArea);
   areaScrollPane
       .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
   areaScrollPane.setPreferredSize(new Dimension(250, 250));
   areaScrollPane.setBorder(BorderFactory.createCompoundBorder(
       BorderFactory.createCompoundBorder(BorderFactory
           .createTitledBorder("Plain Text"), BorderFactory
           .createEmptyBorder(5, 5, 5, 5)), areaScrollPane
           .getBorder()));
   //Create an editor pane.
   JEditorPane editorPane = createEditorPane();
   JScrollPane editorScrollPane = new JScrollPane(editorPane);
   editorScrollPane
       .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
   editorScrollPane.setPreferredSize(new Dimension(250, 145));
   editorScrollPane.setMinimumSize(new Dimension(10, 10));
   //Create a text pane.
   JTextPane textPane = createTextPane();
   JScrollPane paneScrollPane = new JScrollPane(textPane);
   paneScrollPane
       .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
   paneScrollPane.setPreferredSize(new Dimension(250, 155));
   paneScrollPane.setMinimumSize(new Dimension(10, 10));
   //Put the editor pane and the text pane in a split pane.
   JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
       editorScrollPane, paneScrollPane);
   splitPane.setOneTouchExpandable(true);
   splitPane.setResizeWeight(0.5);
   JPanel rightPane = new JPanel(new GridLayout(1, 0));
   rightPane.add(splitPane);
   rightPane.setBorder(BorderFactory.createCompoundBorder(BorderFactory
       .createTitledBorder("Styled Text"), BorderFactory
       .createEmptyBorder(5, 5, 5, 5)));
   //Put everything together.
   JPanel leftPane = new JPanel(new BorderLayout());
   leftPane.add(textControlsPane, BorderLayout.PAGE_START);
   leftPane.add(areaScrollPane, BorderLayout.CENTER);
   add(leftPane, BorderLayout.LINE_START);
   add(rightPane, BorderLayout.LINE_END);
 }
 private void addLabelTextRows(JLabel[] labels, JTextField[] textFields,
     GridBagLayout gridbag, Container container) {
   GridBagConstraints c = new GridBagConstraints();
   c.anchor = GridBagConstraints.EAST;
   int numLabels = labels.length;
   for (int i = 0; i < numLabels; i++) {
     c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last
     c.fill = GridBagConstraints.NONE; //reset to default
     c.weightx = 0.0; //reset to default
     container.add(labels[i], c);
     c.gridwidth = GridBagConstraints.REMAINDER; //end row
     c.fill = GridBagConstraints.HORIZONTAL;
     c.weightx = 1.0;
     container.add(textFields[i], c);
   }
 }
 public void actionPerformed(ActionEvent e) {
   String prefix = "You typed \"";
   if (textFieldString.equals(e.getActionCommand())) {
     JTextField source = (JTextField) e.getSource();
     actionLabel.setText(prefix + source.getText() + "\"");
   } else if (passwordFieldString.equals(e.getActionCommand())) {
     JPasswordField source = (JPasswordField) e.getSource();
     actionLabel.setText(prefix + new String(source.getPassword())
         + "\"");
   } else if (buttonString.equals(e.getActionCommand())) {
     Toolkit.getDefaultToolkit().beep();
   }
 }
 private JEditorPane createEditorPane() {
   JEditorPane editorPane = new JEditorPane();
   editorPane.setEditable(false);
   java.net.URL helpURL = TextSamplerDemo.class
       .getResource("TextSamplerDemoHelp.html");
   if (helpURL != null) {
     try {
       editorPane.setPage(helpURL);
     } catch (IOException e) {
       System.err.println("Attempted to read a bad URL: " + helpURL);
     }
   } else {
     System.err.println("Couldn"t find file: TextSampleDemoHelp.html");
   }
   return editorPane;
 }
 private JTextPane createTextPane() {
   String[] initString = {
       "This is an editable JTextPane, ", //regular
       "another ", //italic
       "styled ", //bold
       "text ", //small
       "component, ", //large
       "which supports embedded components..." + newline,//regular
       " " + newline, //button
       "...and embedded icons..." + newline, //regular
       " ", //icon
       newline
           + "JTextPane is a subclass of JEditorPane that "
           + "uses a StyledEditorKit and StyledDocument, and provides "
           + "cover methods for interacting with those objects." };
   String[] initStyles = { "regular", "italic", "bold", "small", "large",
       "regular", "button", "regular", "icon", "regular" };
   JTextPane textPane = new JTextPane();
   StyledDocument doc = textPane.getStyledDocument();
   addStylesToDocument(doc);
   try {
     for (int i = 0; i < initString.length; i++) {
       doc.insertString(doc.getLength(), initString[i], doc
           .getStyle(initStyles[i]));
     }
   } catch (BadLocationException ble) {
     System.err.println("Couldn"t insert initial text into text pane.");
   }
   return textPane;
 }
 protected void addStylesToDocument(StyledDocument doc) {
   //Initialize some styles.
   Style def = StyleContext.getDefaultStyleContext().getStyle(
       StyleContext.DEFAULT_STYLE);
   Style regular = doc.addStyle("regular", def);
   StyleConstants.setFontFamily(def, "SansSerif");
   Style s = doc.addStyle("italic", regular);
   StyleConstants.setItalic(s, true);
   s = doc.addStyle("bold", regular);
   StyleConstants.setBold(s, true);
   s = doc.addStyle("small", regular);
   StyleConstants.setFontSize(s, 10);
   s = doc.addStyle("large", regular);
   StyleConstants.setFontSize(s, 16);
   s = doc.addStyle("icon", regular);
   StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
   ImageIcon pigIcon = createImageIcon("images/Pig.gif", "a cute pig");
   if (pigIcon != null) {
     StyleConstants.setIcon(s, pigIcon);
   }
   s = doc.addStyle("button", regular);
   StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
   ImageIcon soundIcon = createImageIcon("images/sound.gif", "sound icon");
   JButton button = new JButton();
   if (soundIcon != null) {
     button.setIcon(soundIcon);
   } else {
     button.setText("BEEP");
   }
   button.setCursor(Cursor.getDefaultCursor());
   button.setMargin(new Insets(0, 0, 0, 0));
   button.setActionCommand(buttonString);
   button.addActionListener(this);
   StyleConstants.setComponent(s, button);
 }
 /** Returns an ImageIcon, or null if the path was invalid. */
 protected static ImageIcon createImageIcon(String path, String description) {
   java.net.URL imgURL = TextSamplerDemo.class.getResource(path);
   if (imgURL != null) {
     return new ImageIcon(imgURL, description);
   } else {
     System.err.println("Couldn"t find file: " + path);
     return null;
   }
 }
 /**
  * Create the GUI and show it. For thread safety, this method should be
  * invoked from the event-dispatching thread.
  */
 private static void createAndShowGUI() {
   //Make sure we have nice window decorations.
   JFrame.setDefaultLookAndFeelDecorated(true);
   //Create and set up the window.
   JFrame frame = new JFrame("TextSamplerDemo");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   //Create and set up the content pane.
   JComponent newContentPane = new TextSamplerDemo();
   newContentPane.setOpaque(true); //content panes must be opaque
   frame.setContentPane(newContentPane);
   //Display the window.
   frame.pack();
   frame.setVisible(true);
 }
 public static void main(String[] args) {
   //Schedule a job for the event-dispatching thread:
   //creating and showing this application"s GUI.
   javax.swing.SwingUtilities.invokeLater(new Runnable() {
     public void run() {
       createAndShowGUI();
     }
   });
 }

}


 </source>
   
  
 
  



TextField Example

   <source lang="java">

/* Core SWING Advanced Programming By Kim Topley ISBN: 0 13 083292 8 Publisher: Prentice Hall

  • /

import java.awt.FlowLayout; import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.UIManager; public class TextFieldExample {

 public static void main(String[] args) {
   try {
       UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
   } catch (Exception evt) {}
 
   JFrame f = new JFrame("Text Field Examples");
   f.getContentPane().setLayout(new FlowLayout());
   f.getContentPane().add(new JTextField("Text field 1"));
   f.getContentPane().add(new JTextField("Text field 2", 8));
   JTextField t = new JTextField("Text field 3", 8);
   t.setHorizontalAlignment(JTextField.RIGHT);
   f.getContentPane().add(t);
   t = new JTextField("Text field 4", 8);
   t.setHorizontalAlignment(JTextField.CENTER);
   f.getContentPane().add(t);
   f.getContentPane().add(new JTextField("Text field 5", 3));
   f.pack();
   f.setVisible(true);
 }

}


 </source>
   
  
 
  



Text Input Demo

   <source lang="java">

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.text.*; /**

* TextInputDemo.java is a 1.4 application that uses
* these additional files:
*   SpringUtilities.java
*   ...
*/

public class TextInputDemo extends JPanel

                                         implements ActionListener,
                                                    FocusListener {
   JTextField streetField, cityField;
   JFormattedTextField zipField;
   JSpinner stateSpinner;
   boolean addressSet = false;
   Font regularFont, italicFont;
   JLabel addressDisplay;
   final static int GAP = 10;
   public TextInputDemo() {
       setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
       JPanel leftHalf = new JPanel() {
           //Don"t allow us to stretch vertically.
           public Dimension getMaximumSize() {
               Dimension pref = getPreferredSize();
               return new Dimension(Integer.MAX_VALUE,
                                    pref.height);
           }
       };
       leftHalf.setLayout(new BoxLayout(leftHalf,
                                        BoxLayout.PAGE_AXIS));
       leftHalf.add(createEntryFields());
       leftHalf.add(createButtons());
       add(leftHalf);
       add(createAddressDisplay());
   }
   protected JComponent createButtons() {
       JPanel panel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
       JButton button = new JButton("Set address");
       button.addActionListener(this);
       panel.add(button);
       button = new JButton("Clear address");
       button.addActionListener(this);
       button.setActionCommand("clear");
       panel.add(button);
       //Match the SpringLayout"s gap, subtracting 5 to make
       //up for the default gap FlowLayout provides.
       panel.setBorder(BorderFactory.createEmptyBorder(0, 0,
                                               GAP-5, GAP-5));
       return panel;
   }
   /**
    * Called when the user clicks the button or presses
    * Enter in a text field.
    */
   public void actionPerformed(ActionEvent e) {
       if ("clear".equals(e.getActionCommand())) {
           addressSet = false;
           streetField.setText("");
           cityField.setText("");
           //We can"t just setText on the formatted text
           //field, since its value will remain set.
           zipField.setValue(null);
       } else {
           addressSet = true;
       }
       updateDisplays();
   }
   protected void updateDisplays() {
       addressDisplay.setText(formatAddress());
       if (addressSet) {
           addressDisplay.setFont(regularFont);
       } else {
           addressDisplay.setFont(italicFont);
       }
   }
   protected JComponent createAddressDisplay() {
       JPanel panel = new JPanel(new BorderLayout());
       addressDisplay = new JLabel();
       addressDisplay.setHorizontalAlignment(JLabel.CENTER);
       regularFont = addressDisplay.getFont().deriveFont(Font.PLAIN,
                                                           16.0f);
       italicFont = regularFont.deriveFont(Font.ITALIC);
       updateDisplays();
       //Lay out the panel.
       panel.setBorder(BorderFactory.createEmptyBorder(
                               GAP/2, //top
                               0,     //left
                               GAP/2, //bottom
                               0));   //right
       panel.add(new JSeparator(JSeparator.VERTICAL),
                 BorderLayout.LINE_START);
       panel.add(addressDisplay,
                 BorderLayout.CENTER);
       panel.setPreferredSize(new Dimension(200, 150));
       return panel;
   }
   protected String formatAddress() {
       if (!addressSet) return "No address set.";
       String street = streetField.getText();
       String city = cityField.getText();
       String state = (String)stateSpinner.getValue();
       String zip = zipField.getText();
       String empty = "";
       if ((street == null) || empty.equals(street)) {
           street = "(no street specified)";
       }
       if ((city == null) || empty.equals(city)) {
           city = "(no city specified)";
       }
       if ((state == null) || empty.equals(state)) {
           state = "(no state specified)";
       } else {
           int abbrevIndex = state.indexOf("(") + 1;
           state = state.substring(abbrevIndex,
                                   abbrevIndex + 2);
       }
       if ((zip == null) || empty.equals(zip)) {
           zip = "";
       }
       StringBuffer sb = new StringBuffer();
sb.append("<html>

"); sb.append(street); sb.append("
"); sb.append(city); sb.append(" "); sb.append(state); //should format sb.append(" "); sb.append(zip); sb.append("

</html>");
       return sb.toString();
   }
   //A convenience method for creating a MaskFormatter.
   protected MaskFormatter createFormatter(String s) {
       MaskFormatter formatter = null;
       try {
           formatter = new MaskFormatter(s);
       } catch (java.text.ParseException exc) {
           System.err.println("formatter is bad: " + exc.getMessage());
           System.exit(-1);
       }
       return formatter;
   }
   /**
    * Called when one of the fields gets the focus so that
    * we can select the focused field.
    */
   public void focusGained(FocusEvent e) {
       Component c = e.getComponent();
       if (c instanceof JFormattedTextField) {
           selectItLater(c);
       } else if (c instanceof JTextField) {
           ((JTextField)c).selectAll();
       }
   }
   //Workaround for formatted text field focus side effects.
   protected void selectItLater(Component c) {
       if (c instanceof JFormattedTextField) {
           final JFormattedTextField ftf = (JFormattedTextField)c;
           SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                   ftf.selectAll();
               }
           });
       }
   }
   //Needed for FocusListener interface.
   public void focusLost(FocusEvent e) { } //ignore
   protected JComponent createEntryFields() {
       JPanel panel = new JPanel(new SpringLayout());
       String[] labelStrings = {
           "Street address: ",
           "City: ",
           "State: ",
           "Zip code: "
       };
       JLabel[] labels = new JLabel[labelStrings.length];
       JComponent[] fields = new JComponent[labelStrings.length];
       int fieldNum = 0;
       //Create the text field and set it up.
       streetField  = new JTextField();
       streetField.setColumns(20);
       fields[fieldNum++] = streetField;
       cityField = new JTextField();
       cityField.setColumns(20);
       fields[fieldNum++] = cityField;
       String[] stateStrings = getStateStrings();
       stateSpinner = new JSpinner(new SpinnerListModel(stateStrings));
       fields[fieldNum++] = stateSpinner;
       zipField = new JFormattedTextField(
                           createFormatter("#####"));
       fields[fieldNum++] = zipField;
       //Associate label/field pairs, add everything,
       //and lay it out.
       for (int i = 0; i < labelStrings.length; i++) {
           labels[i] = new JLabel(labelStrings[i],
                                  JLabel.TRAILING);
           labels[i].setLabelFor(fields[i]);
           panel.add(labels[i]);
           panel.add(fields[i]);
           //Add listeners to each field.
           JTextField tf = null;
           if (fields[i] instanceof JSpinner) {
               tf = getTextField((JSpinner)fields[i]);
           } else {
               tf = (JTextField)fields[i];
           }
           tf.addActionListener(this);
           tf.addFocusListener(this);
       }
       SpringUtilities.makeCompactGrid(panel,
                                       labelStrings.length, 2,
                                       GAP, GAP, //init x,y
                                       GAP, GAP/2);//xpad, ypad
       return panel;
   }
   public String[] getStateStrings() {
       String[] stateStrings = {
           "Alabama (AL)",
           "Alaska (AK)",
           "Arizona (AZ)",
           "Arkansas (AR)",
           "California (CA)",
           "Colorado (CO)",
           "Connecticut (CT)",
           "Delaware (DE)",
           "District of Columbia (DC)",
           "Florida (FL)",
           "Georgia (GA)",
           "Hawaii (HI)",
           "Idaho (ID)",
           "Illinois (IL)",
           "Indiana (IN)",
           "Iowa (IA)",
           "Kansas (KS)",
           "Kentucky (KY)",
           "Louisiana (LA)",
           "Maine (ME)",
           "Maryland (MD)",
           "Massachusetts (MA)",
           "Michigan (MI)",
           "Minnesota (MN)",
           "Mississippi (MS)",
           "Missouri (MO)",
           "Montana (MT)",
           "Nebraska (NE)",
           "Nevada (NV)",
           "New Hampshire (NH)",
           "New Jersey (NJ)",
           "New Mexico (NM)",
           "New York (NY)",
           "North Carolina (NC)",
           "North Dakota (ND)",
           "Ohio (OH)",
           "Oklahoma (OK)",
           "Oregon (OR)",
           "Pennsylvania (PA)",
           "Rhode Island (RI)",
           "South Carolina (SC)",
           "South Dakota (SD)",
           "Tennessee (TN)",
           "Texas (TX)",
           "Utah (UT)",
           "Vermont (VT)",
           "Virginia (VA)",
           "Washington (WA)",
           "West Virginia (WV)",
           "Wisconsin (WI)",
           "Wyoming (WY)"
       };
       return stateStrings;
   }
   public JFormattedTextField getTextField(JSpinner spinner) {
       JComponent editor = spinner.getEditor();
       if (editor instanceof JSpinner.DefaultEditor) {
           return ((JSpinner.DefaultEditor)editor).getTextField();
       } else {
           System.err.println("Unexpected editor type: "
                              + spinner.getEditor().getClass()
                              + " isn"t a descendant of DefaultEditor");
           return null;
       }
   }
   /**
    * Create the GUI and show it.  For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    */
   private static void createAndShowGUI() {
       //Make sure we have nice window decorations.
       JFrame.setDefaultLookAndFeelDecorated(true);
       //Create and set up the window.
       JFrame frame = new JFrame("TextInputDemo");
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       //Create and set up the content pane.
       JComponent newContentPane = new TextInputDemo();
       newContentPane.setOpaque(true); //content panes must be opaque
       frame.setContentPane(newContentPane);
       //Display the window.
       frame.pack();
       frame.setVisible(true);
   }
   public static void main(String[] args) {
       //Schedule a job for the event-dispatching thread:
       //creating and showing this application"s GUI.
       javax.swing.SwingUtilities.invokeLater(new Runnable() {
           public void run() {
               createAndShowGUI();
           }
       });
   }

} /**

* A 1.4 file that provides utility methods for
* creating form- or grid-style layouts with SpringLayout.
* These utilities are used by several programs, such as
* SpringBox and SpringCompactGrid.
*/
class SpringUtilities {
   /**
    * A debugging utility that prints to stdout the component"s
    * minimum, preferred, and maximum sizes.
    */
   public static void printSizes(Component c) {
       System.out.println("minimumSize = " + c.getMinimumSize());
       System.out.println("preferredSize = " + c.getPreferredSize());
       System.out.println("maximumSize = " + c.getMaximumSize());
   }
   /**
    * Aligns the first rows * cols
    * components of parent in
    * a grid. Each component is as big as the maximum
    * preferred width and height of the components.
    * The parent is made just big enough to fit them all.
    *
    * @param rows number of rows
    * @param cols number of columns
    * @param initialX x location to start the grid at
    * @param initialY y location to start the grid at
    * @param xPad x padding between cells
    * @param yPad y padding between cells
    */
   public static void makeGrid(Container parent,
                               int rows, int cols,
                               int initialX, int initialY,
                               int xPad, int yPad) {
       SpringLayout layout;
       try {
           layout = (SpringLayout)parent.getLayout();
       } catch (ClassCastException exc) {
           System.err.println("The first argument to makeGrid must use SpringLayout.");
           return;
       }
       Spring xPadSpring = Spring.constant(xPad);
       Spring yPadSpring = Spring.constant(yPad);
       Spring initialXSpring = Spring.constant(initialX);
       Spring initialYSpring = Spring.constant(initialY);
       int max = rows * cols;
       //Calculate Springs that are the max of the width/height so that all
       //cells have the same size.
       Spring maxWidthSpring = layout.getConstraints(parent.getComponent(0)).
                                   getWidth();
       Spring maxHeightSpring = layout.getConstraints(parent.getComponent(0)).
                                   getWidth();
       for (int i = 1; i < max; i++) {
           SpringLayout.Constraints cons = layout.getConstraints(
                                           parent.getComponent(i));
           maxWidthSpring = Spring.max(maxWidthSpring, cons.getWidth());
           maxHeightSpring = Spring.max(maxHeightSpring, cons.getHeight());
       }
       //Apply the new width/height Spring. This forces all the
       //components to have the same size.
       for (int i = 0; i < max; i++) {
           SpringLayout.Constraints cons = layout.getConstraints(
                                           parent.getComponent(i));
           cons.setWidth(maxWidthSpring);
           cons.setHeight(maxHeightSpring);
       }
       //Then adjust the x/y constraints of all the cells so that they
       //are aligned in a grid.
       SpringLayout.Constraints lastCons = null;
       SpringLayout.Constraints lastRowCons = null;
       for (int i = 0; i < max; i++) {
           SpringLayout.Constraints cons = layout.getConstraints(
                                                parent.getComponent(i));
           if (i % cols == 0) { //start of new row
               lastRowCons = lastCons;
               cons.setX(initialXSpring);
           } else { //x position depends on previous component
               cons.setX(Spring.sum(lastCons.getConstraint(SpringLayout.EAST),
                                    xPadSpring));
           }
           if (i / cols == 0) { //first row
               cons.setY(initialYSpring);
           } else { //y position depends on previous row
               cons.setY(Spring.sum(lastRowCons.getConstraint(SpringLayout.SOUTH),
                                    yPadSpring));
           }
           lastCons = cons;
       }
       //Set the parent"s size.
       SpringLayout.Constraints pCons = layout.getConstraints(parent);
       pCons.setConstraint(SpringLayout.SOUTH,
                           Spring.sum(
                               Spring.constant(yPad),
                               lastCons.getConstraint(SpringLayout.SOUTH)));
       pCons.setConstraint(SpringLayout.EAST,
                           Spring.sum(
                               Spring.constant(xPad),
                               lastCons.getConstraint(SpringLayout.EAST)));
   }
   /* Used by makeCompactGrid. */
   private static SpringLayout.Constraints getConstraintsForCell(
                                               int row, int col,
                                               Container parent,
                                               int cols) {
       SpringLayout layout = (SpringLayout) parent.getLayout();
       Component c = parent.getComponent(row * cols + col);
       return layout.getConstraints(c);
   }
   /**
    * Aligns the first rows * cols
    * components of parent in
    * a grid. Each component in a column is as wide as the maximum
    * preferred width of the components in that column;
    * height is similarly determined for each row.
    * The parent is made just big enough to fit them all.
    *
    * @param rows number of rows
    * @param cols number of columns
    * @param initialX x location to start the grid at
    * @param initialY y location to start the grid at
    * @param xPad x padding between cells
    * @param yPad y padding between cells
    */
   public static void makeCompactGrid(Container parent,
                                      int rows, int cols,
                                      int initialX, int initialY,
                                      int xPad, int yPad) {
       SpringLayout layout;
       try {
           layout = (SpringLayout)parent.getLayout();
       } catch (ClassCastException exc) {
           System.err.println("The first argument to makeCompactGrid must use SpringLayout.");
           return;
       }
       //Align all cells in each column and make them the same width.
       Spring x = Spring.constant(initialX);
       for (int c = 0; c < cols; c++) {
           Spring width = Spring.constant(0);
           for (int r = 0; r < rows; r++) {
               width = Spring.max(width,
                                  getConstraintsForCell(r, c, parent, cols).
                                      getWidth());
           }
           for (int r = 0; r < rows; r++) {
               SpringLayout.Constraints constraints =
                       getConstraintsForCell(r, c, parent, cols);
               constraints.setX(x);
               constraints.setWidth(width);
           }
           x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad)));
       }
       //Align all cells in each row and make them the same height.
       Spring y = Spring.constant(initialY);
       for (int r = 0; r < rows; r++) {
           Spring height = Spring.constant(0);
           for (int c = 0; c < cols; c++) {
               height = Spring.max(height,
                                   getConstraintsForCell(r, c, parent, cols).
                                       getHeight());
           }
           for (int c = 0; c < cols; c++) {
               SpringLayout.Constraints constraints =
                       getConstraintsForCell(r, c, parent, cols);
               constraints.setY(y);
               constraints.setHeight(height);
           }
           y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad)));
       }
       //Set the parent"s size.
       SpringLayout.Constraints pCons = layout.getConstraints(parent);
       pCons.setConstraint(SpringLayout.SOUTH, y);
       pCons.setConstraint(SpringLayout.EAST, x);
   }

}


 </source>
   
  
 
  



Wrap textarea

   <source lang="java">

import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class TextAreaFrame extends JFrame implements ActionListener {

 private JButton insertButton = new JButton("Insert");
 private JButton wrapButton = new JButton("Wrap");
 private JButton noWrapButton = new JButton("No wrap");
 private JTextArea textArea = new JTextArea(8, 40);
 private JScrollPane scrollPane = new JScrollPane(textArea);
 public TextAreaFrame() {
   JPanel p = new JPanel();
   p.add(insertButton);
   insertButton.addActionListener(this);
   p.add(wrapButton);
   wrapButton.addActionListener(this);
   p.add(noWrapButton);
   noWrapButton.addActionListener(this);
   getContentPane().add(p, "South");
   getContentPane().add(scrollPane, "Center");
   setTitle("TextAreaTest");
   setSize(300, 300);
   addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   });
 }
 public void actionPerformed(ActionEvent evt) {
   Object source = evt.getSource();
   if (source == insertButton)
     textArea
         .append("The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.");
   else if (source == wrapButton) {
     textArea.setLineWrap(true);
     scrollPane.validate();
   } else if (source == noWrapButton) {
     textArea.setLineWrap(false);
     scrollPane.validate();
   }
 }
 public static void main(String[] args) {
   JFrame f = new TextAreaFrame();
   f.show();
 }

}


 </source>