Java/Swing JFC/Key Stroke

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

Add KeyStroke to JTextArea

   <source lang="java">

/*

* Copyright (c) 1995 - 2008 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:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions 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 nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*

* TextAreaDemo.java requires no other files.
*/

import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.swing.AbstractAction; import javax.swing.ActionMap; import javax.swing.GroupLayout; import javax.swing.InputMap; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.KeyStroke; import javax.swing.LayoutStyle; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.WindowConstants; import javax.swing.GroupLayout.Alignment; import javax.swing.GroupLayout.ParallelGroup; import javax.swing.GroupLayout.SequentialGroup; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.BadLocationException; public class TextAreaDemo extends JFrame implements DocumentListener {

 private JLabel jLabel1;
 private JScrollPane jScrollPane1;
 private JTextArea textArea;
 private static final String COMMIT_ACTION = "commit";
 private static enum Mode {
   INSERT, COMPLETION
 };
 private final List<String> words;
 private Mode mode = Mode.INSERT;
 public TextAreaDemo() {
   super("TextAreaDemo");
   initComponents();
   textArea.getDocument().addDocumentListener(this);
   InputMap im = textArea.getInputMap();
   ActionMap am = textArea.getActionMap();
   im.put(KeyStroke.getKeyStroke("ENTER"), COMMIT_ACTION);
   am.put(COMMIT_ACTION, new CommitAction());
   words = new ArrayList<String>(5);
   words.add("spark");
   words.add("special");
   words.add("spectacles");
   words.add("spectacular");
   words.add("swing");
 }
 private void initComponents() {
   jLabel1 = new JLabel("Try typing "spectacular" or "Swing"...");
   textArea = new JTextArea();
   setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
   textArea.setColumns(20);
   textArea.setLineWrap(true);
   textArea.setRows(5);
   textArea.setWrapStyleWord(true);
   jScrollPane1 = new JScrollPane(textArea);
   GroupLayout layout = new GroupLayout(getContentPane());
   getContentPane().setLayout(layout);
   // Create a parallel group for the horizontal axis
   ParallelGroup hGroup = layout
       .createParallelGroup(GroupLayout.Alignment.LEADING);
   // Create a sequential and a parallel groups
   SequentialGroup h1 = layout.createSequentialGroup();
   ParallelGroup h2 = layout
       .createParallelGroup(GroupLayout.Alignment.TRAILING);
   // Add a scroll panel and a label to the parallel group h2
   h2.addComponent(jScrollPane1, GroupLayout.Alignment.LEADING,
       GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE);
   h2.addComponent(jLabel1, GroupLayout.Alignment.LEADING,
       GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE);
   // Add a container gap to the sequential group h1
   h1.addContainerGap();
   // Add the group h2 to the group h1
   h1.addGroup(h2);
   h1.addContainerGap();
   // Add the group h1 to hGroup
   hGroup.addGroup(Alignment.TRAILING, h1);
   // Create the horizontal group
   layout.setHorizontalGroup(hGroup);
   // Create a parallel group for the vertical axis
   ParallelGroup vGroup = layout
       .createParallelGroup(GroupLayout.Alignment.LEADING);
   // Create a sequential group
   SequentialGroup v1 = layout.createSequentialGroup();
   // Add a container gap to the sequential group v1
   v1.addContainerGap();
   // Add a label to the sequential group v1
   v1.addComponent(jLabel1);
   v1.addPreferredGap(LayoutStyle.ruponentPlacement.RELATED);
   // Add scroll panel to the sequential group v1
   v1.addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 100,
       Short.MAX_VALUE);
   v1.addContainerGap();
   // Add the group v1 to vGroup
   vGroup.addGroup(v1);
   // Create the vertical group
   layout.setVerticalGroup(vGroup);
   pack();
 }
 // Listener methods
 public void changedUpdate(DocumentEvent ev) {
 }
 public void removeUpdate(DocumentEvent ev) {
 }
 public void insertUpdate(DocumentEvent ev) {
   if (ev.getLength() != 1) {
     return;
   }
   int pos = ev.getOffset();
   String content = null;
   try {
     content = textArea.getText(0, pos + 1);
   } catch (BadLocationException e) {
     e.printStackTrace();
   }
   // Find where the word starts
   int w;
   for (w = pos; w >= 0; w--) {
     if (!Character.isLetter(content.charAt(w))) {
       break;
     }
   }
   if (pos - w < 2) {
     // Too few chars
     return;
   }
   String prefix = content.substring(w + 1).toLowerCase();
   int n = Collections.binarySearch(words, prefix);
   if (n < 0 && -n <= words.size()) {
     String match = words.get(-n - 1);
     if (match.startsWith(prefix)) {
       // A completion is found
       String completion = match.substring(pos - w);
       // We cannot modify Document from within notification,
       // so we submit a task that does the change later
       SwingUtilities.invokeLater(new CompletionTask(completion, pos + 1));
     }
   } else {
     // Nothing found
     mode = Mode.INSERT;
   }
 }
 private class CompletionTask implements Runnable {
   String completion;
   int position;
   CompletionTask(String completion, int position) {
     this.rupletion = completion;
     this.position = position;
   }
   public void run() {
     textArea.insert(completion, position);
     textArea.setCaretPosition(position + completion.length());
     textArea.moveCaretPosition(position);
     mode = Mode.ruPLETION;
   }
 }
 private class CommitAction extends AbstractAction {
   public void actionPerformed(ActionEvent ev) {
     if (mode == Mode.ruPLETION) {
       int pos = textArea.getSelectionEnd();
       textArea.insert(" ", pos);
       textArea.setCaretPosition(pos + 1);
       mode = Mode.INSERT;
     } else {
       textArea.replaceSelection("\n");
     }
   }
 }
 public static void main(String args[]) {
   SwingUtilities.invokeLater(new Runnable() {
     public void run() {
       // Turn off metal"s use of bold fonts
       UIManager.put("swing.boldMetal", Boolean.FALSE);
       new TextAreaDemo().setVisible(true);
     }
   });
 }

}

 </source>
   
  
 
  



InputMap and KeyStroke

   <source lang="java">

/*

* Copyright (c) 1995 - 2008 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:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions 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 nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*

* TextComponentDemo.java requires one additional file:
*   DocumentSizeFilter.java
*/

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.UIManager; 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<Object, Action> 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.
   actions = 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();
   textPane.setCaretPosition(0);
   // 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 dispatch 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 on the event dispatch thread. We use
   // invokeLater to schedule the code for execution
   // on the event dispatch 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 = 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 the arrow keys on the keyboard or 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 HashMap<Object, Action> createActionTable(JTextComponent textComponent) {
   HashMap<Object, Action> actions = new HashMap<Object, Action>();
   Action[] actionsArray = textComponent.getActions();
   for (int i = 0; i < actionsArray.length; i++) {
     Action a = actionsArray[i];
     actions.put(a.getValue(Action.NAME), a);
   }
   return actions;
 }
 private Action getActionByName(String name) {
   return 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 dispatch thread.
  */
 private static void createAndShowGUI() {
   // 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 dispatch thread:
   // creating and showing this application"s GUI.
   SwingUtilities.invokeLater(new Runnable() {
     public void run() {
       // Turn off metal"s use of bold fonts
       UIManager.put("swing.boldMetal", Boolean.FALSE);
       createAndShowGUI();
     }
   });
 }

} /*

* Copyright (c) 1995 - 2008 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:
*  - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*  - Redistributions 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 nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
* 
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/

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>
   
  
 
  



Install your own action to text component

   <source lang="java">
 

import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.text.BadLocationException; import javax.swing.text.JTextComponent; class InsertAction extends AbstractAction {

 public InsertAction() {
   super("Insert Space");
 }
 public void actionPerformed(ActionEvent evt) {
   JTextComponent c = (JTextComponent) evt.getSource();
   try {
     c.getDocument().insertString(c.getCaretPosition(), " space", null);
   } catch (BadLocationException e) {
   }
 }

} public class Main {

 public static void main(String[] argv) {
   JTextField component = new JTextField(10);
   InsertAction insertSpaceAction = new InsertAction();
   component.getInputMap(JComponent.WHEN_FOCUSED).put(
       KeyStroke.getKeyStroke(new Character(" "), 0), "none");
   component.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("pressed SPACE"),
       insertSpaceAction.getValue(Action.NAME));
   component.getActionMap().put(insertSpaceAction.getValue(Action.NAME), insertSpaceAction);
   JFrame f = new JFrame();
   f.add(component);
   f.setSize(300, 300);
   f.setVisible(true);
 }

}


 </source>
   
  
 
  



Overriding Many Default Typed Key Bindings in a JTextComponent

   <source lang="java">
 

import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.text.BadLocationException; import javax.swing.text.JTextComponent; class MyKeyListener extends KeyAdapter {

 public void keyTyped(KeyEvent evt) {
   JTextComponent c = (JTextComponent) evt.getSource();
   char ch = evt.getKeyChar();
   if (Character.isLowerCase(ch) == false) {
     return;
   }
   try {
     c.getDocument().insertString(c.getCaretPosition(), "" + Character.toUpperCase(ch), null);
     evt.consume();
   } catch (BadLocationException e) {
   }
 }

} public class Main {

 public static void main(String[] argv) throws Exception {
   JTextField component = new JTextField();
   component.addKeyListener(new MyKeyListener());
   JFrame f = new JFrame();
   f.setSize(300, 300);
   f.setVisible(true);
 }

}


 </source>
   
  
 
  



set Accelerator with KeyStroke

   <source lang="java">

/*

* Copyright (c) 1995 - 2008 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:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions 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 nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.JDesktopPane; import javax.swing.JFrame; import javax.swing.JInternalFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.KeyStroke; /*

* InternalFrameDemo.java requires: MyInternalFrame.java
*/

public class InternalFrameDemo extends JFrame implements ActionListener {

 JDesktopPane desktop;
 public InternalFrameDemo() {
   super("InternalFrameDemo");
   // Make the big window be indented 50 pixels from each edge
   // of the screen.
   int inset = 50;
   Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
   setBounds(inset, inset, screenSize.width - inset * 2, screenSize.height
       - inset * 2);
   // Set up the GUI.
   desktop = new JDesktopPane(); // a specialized layered pane
   createFrame(); // create first "window"
   setContentPane(desktop);
   setJMenuBar(createMenuBar());
   // Make dragging a little faster but perhaps uglier.
   desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
 }
 protected JMenuBar createMenuBar() {
   JMenuBar menuBar = new JMenuBar();
   // Set up the lone menu.
   JMenu menu = new JMenu("Document");
   menu.setMnemonic(KeyEvent.VK_D);
   menuBar.add(menu);
   // Set up the first menu item.
   JMenuItem menuItem = new JMenuItem("New");
   menuItem.setMnemonic(KeyEvent.VK_N);
   menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
       ActionEvent.ALT_MASK));
   menuItem.setActionCommand("new");
   menuItem.addActionListener(this);
   menu.add(menuItem);
   // Set up the second menu item.
   menuItem = new JMenuItem("Quit");
   menuItem.setMnemonic(KeyEvent.VK_Q);
   menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
       ActionEvent.ALT_MASK));
   menuItem.setActionCommand("quit");
   menuItem.addActionListener(this);
   menu.add(menuItem);
   return menuBar;
 }
 // React to menu selections.
 public void actionPerformed(ActionEvent e) {
   if ("new".equals(e.getActionCommand())) { // new
     createFrame();
   } else { // quit
     quit();
   }
 }
 // Create a new internal frame.
 protected void createFrame() {
   MyInternalFrame frame = new MyInternalFrame();
   frame.setVisible(true); // necessary as of 1.3
   desktop.add(frame);
   try {
     frame.setSelected(true);
   } catch (java.beans.PropertyVetoException e) {
   }
 }
 // Quit the application.
 protected void quit() {
   System.exit(0);
 }
 /**
  * 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.
   InternalFrameDemo frame = new InternalFrameDemo();
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   // Display the window.
   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();
     }
   });
 }

} /*

* Copyright (c) 1995 - 2008 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:
*  - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*  - Redistributions 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 nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
* 
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/

class MyInternalFrame extends JInternalFrame {

 static int openFrameCount = 0;
 static final int xOffset = 30, yOffset = 30;
 public MyInternalFrame() {
   super("Document #" + (++openFrameCount), true, // resizable
       true, // closable
       true, // maximizable
       true);// iconifiable
   // ...Create the GUI and put it in the window...
   // ...Then set the window size or call pack...
   setSize(300, 300);
   // Set the window"s location.
   setLocation(xOffset * openFrameCount, yOffset * openFrameCount);
 }

}

 </source>