InPutMap and actionMap

Hello.
I am currently working on a larger project, where I'd like to make certain JButtons respond to the pressing of certain keys.
To make this simpler, I wrote a smaller program with only one button, just to make the code easier to read.
I've been working with Java for about 8 months now, and still do consider myself a novice, so any help I can get is greatly appreciated.
In the posted example, I have a JButton that changes the text of a JTextField when pressed, however, I'd like to make the button respond when I press "a" on my keyboard,
and for this I should use keybindinds (as far as I've understood). I've tried using inPutMap and actionMap, but haven't had any luck making them work yet.
I added comments in the code, that shows where I'm in doubt. Again, any help is greatly appreciated, and I did read the tutorial at
[http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]
/* The imports */
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
public class inPutExample extends JFrame implements ActionListener {
    /* Initialization */
    private JButton actionButton;
    private JTextField textField;
    /* My main method */
    public static void main (String[] Args) {
        inPutExample frame = new inPutExample();
        frame.setSize(200,120);
        frame.createGUI();
        frame.setVisible(true);
    /* The interface */
    private void createGUI() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        Container window = getContentPane();
        window.setLayout(new FlowLayout());
        /* My button, that needs to respond to a keypress */
        actionButton = new JButton("Press me");
        window.add(actionButton);
        actionButton.addActionListener(this);
        /* The inPutMap for my button.
         In the tutorial, they didn't use
         keyEvent, but simply wrote a letter in quotation marks,
         so I'm a bit confused on that */
        actionButton.getInputMap(JButton.WHEN_IN_FOCUSED_WINDOW)
                .put(KeyStroke.getKeyStroke("a"), actionButton);
        /* The actionMap for my button. I'm confused
         as to what to put after the comma */
        actionButton.getActionMap().put(actionButton, null);
        /* The textfield that allows me to see
         if the button has been pressed */
        textField = new JTextField("Button hasn't been pressed");
        window.add(textField);
    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();
        /* The action that is performed
         when the button is pressed */
        if (source == actionButton) {
            textField.setText("Button has been pressed");
}Any help or constructive criticism will be appreciated and responded to.
Ulverbeast

Compare you code again to the tutorial:
component.getInputMap().put(KeyStroke.getKeyStroke("F2"),
                            "doSomething");
component.getActionMap().put("doSomething",
                             anAction);
//where anAction is a javax.swing.ActionAlthough using the action button as action command (the 'doSomthing') works, that isn't really a good idea - stick with Strings. The crucial thing missing in the actual action though:
Action action = new AbstractAction("Press me") {
  public void actionPerformed(ActionEvent e) {
    textField.setText("Button has been pressed");
button = new JButton(action);
// and put button in action map

Similar Messages

  • HOW to use InputMap and ActionMap for a JButton ?

    Hi,
    I used to call the registredKeyBoardAction to deal with JButton keyBoard actions.
    It is written in the JavaDoc that this method is deprecated, so I try to use the InputMap and ActionMap as described in this doc without success.
    Does anybody has a piece of code that uses
    jButton.getInputMap().put(aKeyStroke, aCommand);
    jButton.getActionMap().put(aCommmand, anAction);
    for the space keyboard key, calling the "foo" actionCommand ?
    Thanks.

    To be more clear, from the API it seems as if you can set an Action for a keystroke. That is only for the component that you set the keystroke for. So if you set it for a button then it would seem that if it does automatically listen for keystrokes it would only do so when that button has focus. try setting the ActionMap for the window.

  • Using InputMap and ActionMap

    Referring to an earlier post "Listening to Keystrokes", I already know how to
    trap keystrokes in a JPanel. I use this line of code:
    this.registerKeyboardAction(this,
          "Exit Task", KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
          JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);[/cpde]
    However, the documentation for registerKeyboardAction() states:
    This method is now obsolete, please use a combination of getActionMap() and
    getInputMap() for similiar behavior. For example, to bind the KeyStroke
    aKeyStroke to the Action anAction now use:
       component.getInputMap().put(aKeyStroke, aCommand);
    component.getActionMap().put(aCommmand, anAction);
    Therefore, I attempt to use the getInputMap() and getActionMap() method. Since the documentation for registerKeyboardAction is:public void registerKeyboardAction(ActionListener anAction,
                                       String aCommand,
                                       KeyStroke aKeyStroke,
                                       int aCondition)I thought inside the JPanel, I only have to add these lines:
    this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "Exit Task");
    this.getActionMap().put("Exit Task", this);Unfortunately, the second line will give compilation errors. Note that the JPanel already implements ActionListener. So I check the documentation for ActionMap and realise that the put() method has two parameters, Object key and Action anAction. It seems that I have to this (a JPanel class) to Action. I thought casting should work since ActionListener is a superinterface to Action, but when I run the program, it will throw a ClassCastException.
    Therefore, I ended up implementing ActionListener AND Action. I also have to implement two abstract methods from Action.
    Did I miss anything? Does the JPanel really need to implement Action? Why can't I cast an ActionListener class to Action?
    Finally, is there a more elegant solution?
    Thank you in advance.

    Hi,
    Hi Shannon,
    Another problem... When we use
    registerKeyboardAction() for a toolbar button, its
    tool tip displays the key stroke used along with any
    text you may have set as the tool tip. So if I have
    JButton oBtn = new JButton();
    oBtn.setIcon(new ImageIcon("SomeIcon.gif"));
    oBtn.setToolTipText("Button Tool Tip");
    oBtn.registerKeyboardAction(handler, null,
    KeyStroke.getKeyStroke(KeyEvent.VK_N,
    InputEvent.CTRL_MASK,
    true),
    JComponent.WHEN_IN_FOCUSED_WINDOW);when I try to view the tool tip, I actually see
    "Button Tool Tip Ctrl-N" with the 'Ctrl-N' in a
    different font and color than the remaining text. But
    when I use the getActionMap() and getInputMap()
    methods, this extra information is not seen in the
    tool tip.Actually, even using getActionMap() and getInputMap(), you will see the control text. For example, the following is the equivalent of your code using getActionMap() and getInputMap():
    oBtn.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
            KeyStroke.getKeyStroke(KeyEvent.VK_N,
            InputEvent.CTRL_MASK,
            true), "handler");
    oBtn.getActionMap().put("handler", new AbstractAction(.....));As you'll see, it also shows the Ctrl-N in the tooltip text.
    Since this behavior has been around since the very early days of Swing, I cannot give you the exact reason for it. However, I suspect it was assumed at the time that if a keystroke is added to a component for WHEN_IN_FOCUSED_WINDOW, then that keystroke is one that will activate the component.
    Now, can I ask why you're adding this keyboard action to the button? Since its WHEN_IN_FOCUSED_WINDOW, you could add it to the contentpane or the rootpane. It doesn't need to be on the button.
    Any help in this case??? My team leader
    would prefer a function that is said to be outdated
    but works so much better, rather than some new fangled
    technique that doesn't give the same help....Just so you know, here's the implementation of registerKeyboardAction:
    public void registerKeyboardAction(ActionListener anAction,
                                       String aCommand,
                                       KeyStroke aKeyStroke,
                                       int aCondition) {
        InputMap inputMap = getInputMap(aCondition, true);
        if (inputMap != null) {
            ActionMap actionMap = getActionMap(true);
            ActionStandin action = new ActionStandin(anAction, aCommand);
            inputMap.put(aKeyStroke, action);
                if (actionMap != null) {
                    actionMap.put(action, action);
        }What am I trying to say? That the old technique simply uses the new technique internally. And it creates an action per keystroke. You might want to reconsider moving over to the new technique. I'd be happy to address any concerns you might have.
    Thanks,
    Shannon Hickey (Swing Team)
    >
    PLEASE HELP!!!
    Regards,
    Shefali

  • Using InputMap and ActionMap to detect any key pressed...plz help

    Hi,
    I am quite new to Java. I have a tiny problem. I wanna put an actionlistener into a JTextField, so it printout something whenever a key is pressed (when the textField is selected).
    I can only get it to print if I assign a specific key to pressed...example below (works):
    JTextField searchBox = new JTextField();
    InputMap imap = searchBox.getInputMap();
    ActionMap amap = searchBox.getActionMap();
    imap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "pressed");
    amap.put("pressed", new AbstractAction() {
              public void actionPerformed(ActionEvent e) {
                   System.out.println("TYPEEEEEEEEEEEEEEE");
    HOWEVER, when i change keystroke to any key pressed, it doesn't work. Example below(doesn't work):
    JTextField searchBox = new JTextField();
    InputMap imap = searchBox.getInputMap();
    ActionMap amap = searchBox.getActionMap();
    imap.put(KeyStroke.getKeyStroke(KeyEvent.KEY_PRESSED, 0), "pressed");
    amap.put("pressed", new AbstractAction() {
              public void actionPerformed(ActionEvent e) {
                   System.out.println("TYPEEEEEEEEEEEEEEE");
    Somebody plz helps me. I am really confused how to use KeyEvent.KEY_PRESSED. I thought it would work the same way as KeyEvent.VK_A...if i can't use KEY_PRESSED for that purpose, what KeyEvent do I use?
    Thank you very much in advance.

    Sounds like you want a KeyListener.
    textField.addKeyListener(new KeyListener() {
        public void keyTyped(KeyEvent e) {
            System.out.println("Key typed.");
        public void keyPressed(KeyEvent e) {
            System.out.println("Key pressed.");
        public void keyReleased(KeyEvent e) {
            System.out.println("Key released.");
    });See the API documentation for more information.

  • NetBeans and ActionMap

    Hi everyone,
    This is probably a stupid question but I will ask anyway.
    I have a set of components that worked fine in Netbeans 3.5.1 but now in Netbeans 3.6 whenever they are dopped on a form (Frame/Panel, etc) they throw the error "Cannot save value for ActionMap" whenever the form is saved.
    Would anyone have any ideas why this is so?
    Thanks.
    Joanna.

    After further investigation....
    It appears that if you cut paste the component onto a form it causes this error....
    But... If you drop it from the palete it does not happen.
    Is this a bug with my component or the IDE?
    Thanks,
    Joanna.

  • Setting global action map and input map.

    I was needing a way to set up the global inputmaps and actionmap. Currently I am grabbing the rootpane of the JFrame and manipulating the input maps there but I was hoping to be able to change the the input maps for whole classes of components such as adding a default to the UI some how so that all buttons respond to an 'Enter' key.
    So far all the solutions invloved modifying individual components, nothing really looked like a way to modify the all JButtons or all JDialogs to add inputmaps/actionmaps.

    Try this fun example.
    Foucs the button. Press some random keys. Press the space key.
    import javax.swing.*;
    * @author Ian Schneider
    public class UIInputDefaults {
        public static void main(String[] args) throws Exception {
            UIManager.getDefaults().put("Button.actionMap",new ActionMap() {
                public Action get(Object key) {
                    Action retValue;
                    System.out.println("action "+ key);
                    retValue = super.get(key);
                    return retValue;
            final InputMap original = (InputMap) UIManager.getDefaults().get("Button.focusInputMap");
            InputMap ours = new InputMap() {
                public Object get(KeyStroke keyStroke) {
                    System.out.println("key " + keyStroke);
                    return super.get(keyStroke);
            KeyStroke[] keys = original.keys();
            for (int i = 0; i < keys.length; i++) {
                ours.put(keys,original.get(keys[i]));
    UIManager.getDefaults().put("Button.focusInputMap", ours);
    JButton b = new JButton("Foo");
    javax.swing.JFrame f = new javax.swing.JFrame();
    f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
    f.getContentPane().add(b);
    f.pack();
    f.setVisible(true);

  • Navigate JTable using Ctrl and arrow combination

    By default, one way to navigate cells in a JTable is by using the arrow keys. I need to change this so that the user must hold down the Ctrl key and then navigate with the arrows. The arrow keys alone will not have any cell navigation functionality... they will only be used for editing cells that contain a JTextField (or some variant).
    Can anyone help me with this? BTW...I am using jdk 1.4.1_03

    To answer my own question:
    Using the InputMap and ActionMap of the JTable, the keybindings can be removed or added, so for moving one column to the right by holding down CTRL and pressing the right arrow, it is as simple as:
    InputMap inputMap = table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    // KeyEvent.VK_RIGHT is the right arrow key, and 2 is the CTRL key mask
    inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 2), "selectNextColumn");Here are some links that were of help:
    http://java.sun.com/j2se/1.4.1/docs/api/javax/swing/doc-files/Key-Index.html
    http://javaalmanac.com/egs/javax.swing/ListKeyBinds.html?l=rel
    http://java.sun.com/products/jfc/tsc/special_report/kestrel/keybindings.html

  • How to use Action/Input maps

    It seems to me that the move to sharing actions menus, buttons, and other components is a logical one, given that it is desirable to have all references to the action reflect its enabled state.
    The question that arises is: which ActionMap object to use as the central store? Do you create your own and pass it on somewhere?
    And, if you try to do anything with homegrown InputMaps then the components stop seeing the events. I wish there was a definitive YOU MUST DO IT THIS WAY tutorial.
    Why is there no factory API that can create UI components pre-attached to actions and with accelerators or mnemonics already set? Then we would not need to write half the code we do now. My solution:
    public class ComponentFactory {
       ActionMap myMap;
       public ComponentFactory(ActionMap map) {
          myMap = map;
       public JButton createButton(String actioncommand) {
           Action a = myMap.get(actioncommand)
           if(a==null)
              return null;
           return new JButton(a);
       public JMenuItem createMenuItem(String actioncommand) {
        // etc...
       public void setAction(Action a) {
           myMap.put(a.getValue(ACTION_COMMAND_KEY),a);
       public void setEnabled(String actioncommand, boolean state) {
           Action a = myMap.get(actioncommand);
           if(a!=null)
               a.setEnabled(state);
    }Is there any concensus as to the best way to handle ActionMaps/InputMaps?

    Hugh,
    >
    The tutorial is a touch short on this subject, whilst
    it is good on how to create and use actions with
    toolbars and the like, the section on InputMaps and
    ActionMaps is far too brief to get the wider picture.
    The API docs on the same is about one paragraph's
    worth.okay, I just checked the tutorial - it's a bit short on the inputMap/actionMap indeed.
    >
    You are mixing up two different issues:
    a) customize a button with an action
    b) bind a keyStroke to an action for an arbitrary
    jComponent
    a) has nothing to do with b)If b) has nothing to do with a) why have MNEMONIC_KEY
    and ACCELERATOR_KEY on the action?Hmm... where do you see a contradiction to my statement? Those keys are part of a) as they are used for customization of the AbstractButtons: the button's mnenmonic/accelerator properties are set to the corresponding values of the action. This propertyChange triggers an update of the keyBinding to the button's "pressed"/"doClick" actions as registered in the actionMap. They are never used (at least not internally by Swing) for b)
    Historically the action is older than the inputMap/actionMap: basically it's an ActionListener (which is more or less a command pattern) plus some (view) state. This "plus" was designed right in the beginning of Swing for a) to enable state sharing between different "buttons" but not really integrated until version 1.4. parallel to that the need for a general mechanism of binding between keyStrokes and "commands" became obvious and inputMap/actionMap were introduced in 1.3. The only action state that's needed for this mechanism to work is the enabled property. All values are ignored - so currently they somehow appear to be overloaded in the context of the inputMap/actionMap. Personally I think they are very powerful because of this extra flexibility.
    >
    There is still not a single diagram; and I maintain
    that it is less than useful to beginners who are not
    familiar with the terminology used. Well, IMO diagrams are not everything - I still think it much easier to understand than the dnd spec or the focus spec f.i.
    >
    you are free to use whatever object you want as akey
    - write a utility method to use the name, if feellike
    doeing so. There is nothing in the framework that
    would single out the name as "the" key to use, The keybindings document specifically states:
    "New actions can be added to a component equally
    easily."
    "The conventional key for an action is it's
    name." If there is a conventional way then it
    should be encouraged with an appropriate API. I get your point. And I definitely agree on following a convention if there is one. Except when the convention is quite immature (to formulate mildly) - and not even followed by Swing internally: most of the default actions registered in the actionMap don't even have a name, the binding is done by string literals ... duplicated in at least two places: the XXLookAndFeel and the ui-delegates.
    Greetings
    Jeanette

  • Suggestion needed: Where to catch the 'Enter' key

    Hi,
    Could someone give me guidance. Below is the background and question of what I would like to do. (Note: There would be so much code I am hoping that someone can understand this without it but I will look later tonight at your possible responses to determine if I need to add some code snippets.)
    BACKGROUND:
    I have an application with a JTabbedPane added to the content pane of the JFrame.
    The JTabbedPane has five JPanels added as tabs each of which extends ActionListener. When it creates each JPanel it passes itself as the argument (this).
    Each of these 'major' JPanel tabs has several (2-4) 'mini' JPanels added to them and all the various JButtons, JComboBoxes, and JTextFields are added to the 'mini' JPanels.
    The JComboBoxes and JTextFields are enclosed in my own separate wrapper classes so I can do some special validation, etc.
    One of the 'mini' JPanels is always named 'buttonPanel' and is where the 'cancel' and 'continue' JButtons are added. The buttons are registered with an ActionListener and allow access to the next 'major' JPanel after some checks are performed. Right now the buttons are caught by the ActionListener of each 'major' JPanel
    I WOULD LIKE TO:
    I would like to have the 'Enter' key perform a 'continue.doClick()' on whatever 'major' JPanel is active (there are many validations to be done on each 'major' panel before the continue button can allow the user access to the next tab). There are from 1-3 other buttons in the same buttonPanel as the 'continue' button so if any of them have the focus then the 'Enter' key action should be handled by them.
    I would like to have the 'Escape' key perform a 'cancel.doClick()' on whatever 'major' JPanel is active. The 'Excape' key does not have to defer to any other button actions like the "Enter" key does.
    Where would I extend the KeyListener? The JTabbedPane has a changeListener method that keeps track of what tab I am on, would this be someplace that could help keep track of what 'major' JPanel continue button should be called?
    Thanks very much.
    hopi

    You can use an InputMap and ActionMap combination to map an action on the JPanel that is currently selected to the Enter key.
    This will allow you to add an ActionListener which is called whenever the enter key is pressed. Then you can cycle through the available buttons and determine which on has focus and call doClick on it. The cycling may require you to place all the buttons in an Array or a Vector.
    ICE

  • Key binding confusion

    I'm trying to use key bindings to navigate a table and do a few other things and I'm totally lost. The first picture in this thread gives you an idea of what my application looks like
    http://www.enginuity.org/viewtopic.php?t=8
    In the JInternalFrame, I have a JToolBar with some JButtons and JTextFields and a JPanel with an array of DataCells (extends JLabel). Basically, I want the arrow keys to move the data cell selection when any component is selected except the text fields.
    If the user types a number and neither text field is selected, I want the second text field to clear and take focus. When the user presses <enter> in that textfield, I want a method to be called (the same as clicking on the set value button). It'd also be nice if pressing a non-numeric (or dot) would not be input in those text fields.
    I'm confused though. How many key bindings do I need to use, and on what component? How many ActionMaps and InputMaps do I need? Do I need to make custom Actions? Sun's key binding "tutorial" just isn't making any sense to me.

    and a JPanel with an array of DataCells (extends JLabel). Use a JTable, it supports navigation using the arrow keys.
    Here is a simple example with InputMaps and ActionMaps:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class PanelActions extends JFrame implements FocusListener
         LayoutManager layout;
         public PanelActions()
              layout = new GridLayout(0, 10);
              JPanel  panel = new JPanel( layout );
              setContentPane( panel );
              Action rightAction = new AbstractAction()
                   public void actionPerformed(ActionEvent e)
                        JComponent c = (JComponent)e.getSource();
                        c.transferFocus();
              for (int i = 0; i < 30; i++)
                   String text = String.valueOf(i);
                   JLabel label = new JLabel( text );
                   label.setFocusable( true );
                   label.addFocusListener( this );
                   panel.add( label );
                 InputMap im = label.getInputMap(JLabel.WHEN_FOCUSED);
                   KeyStroke right = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0);
                   im.put(right, "right");
                   label.getActionMap().put(im.get(right), rightAction);
         public void focusGained(FocusEvent e)
              JLabel l = (JLabel)e.getSource();
              System.out.println(l.getText());
         public void focusLost(FocusEvent e) {}
         public static void main(String[] args)
              PanelActions frame = new PanelActions();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

  • Customize "Tab" key for JTextArea to focus next component.

    Hi,
    I am trying to change the "TAB" key behaviour for JTextArea, by using CustomAction configured via InputMap() and ActionMap(). When the user presses the Tab key, the focus should go the next component instead of tabbing in the same JTextArea component. Here is the code for the CustomAction().
        public static class CustomTabAction extends AbstractAction {
            private JComponent comp;
            public CustomTabAction (JComponent comp) {
                this.comp = comp;
                this.comp.getInputMap().put(KeyStroke.getKeyStroke("TAB"), "TABPressed");
                this.comp.getActionMap().put("TABPressed", this);
            public void actionPerformed(ActionEvent evt) {
                Object source = evt.getSource();
                if (source instanceof Component) {
                    FocusManager.getCurrentKeyboardFocusManager().
                            focusNextComponent((Component) source);
        }This works for most of the cases in my applicaiton. The problem is that it doesn't work with JTable which has a custom cell editor (JTextArea). In JTextArea field of JTable, if the Tab is pressed, nothing happens and the cursor remains in the custom JTextArea exactly at the same place, without even tabbing spaces. Here is the CustomCellEditor code.
        public class DescColCellEditor extends AbstractCellEditor implements TableCellEditor {
    //prepare the component.
            JComponent comp = new JTextArea();
            public Component getTableCellEditorComponent(JTable table, Object value,
                    boolean isSelected, int rowIndex, int vColIndex) {
                // Configure Tab key to focus to next component
                CustomActions.setCustomAction("CustomTabAction", comp);
                // Configure the component with the specified value
                ((JTextArea)comp).setText((String)value);
                // Return the configured component
                return comp;
            // This method is called when editing is completed.
            // It must return the new value to be stored in the cell.
            public Object getCellEditorValue() {
                return ((JTextArea)comp).getText();
        }regards,
    nirvan

    >
    textArea.getInputMap().remove(....);but that won't work because the binding is actually defined in the parent InputMap. So I think you need to use code like:
    textArea.getInputMap().getParent().remove(...);But I'm not sure about this as I've never tried it.I tried removing the VK_TAB key from both the input map and parent input map as shown below. But I still have to press "TAB" twice in order to get out of the JTextArea column in JTable.
                comp.getInputMap().getParent().remove(
                            KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0));
                comp.getInputMap().remove(
                            KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0));after coding this, I am using the setFocusTraversalKeys for adding only "TAB" key as ForwardTraversalKey as given below.
            Set newForwardKeys = new HashSet();
            newForwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0));
            comp.setFocusTraversalKeys(
                        KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,newForwardKeys);
            Set newBackwardKeys = new HashSet();
            newBackwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, KeyEvent.SHIFT_DOWN_MASK));
            comp.setFocusTraversalKeys(
                        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,newBackwardKeys);The only problem that remains now is that I have to press the "TAB" twice in order to get out of the JTextArea column
    regards,
    nirvan.

  • JTextpane question

    HI everybody,
    In my project i have to set some thing in JTextpane.
    What my problem is
    User enter the characters in textpane after press the enter button
    the contents of the textpane is paste in another textpane and first textpane will be clear .
    In this process is going good but after pressing the enter, JTextpane go to the next line.
    I dont want to go next line after pressing the enter button. just clear the text in JTextpane and set cursor in the starting point of the JTextpane This is i want.
    So can any body help this problem.
    awaiting for your reply,

    Ashwini.Kumar.Kulshrestha wrote:
    you must have implemented the key listener for the textPane to trap the Enter key.
    public void keyPressed(KeyEvent e){
    if(e.getKeyCode()==VK_ENTER)
    // pass the text to the other TextPane
    textPane.setCursorPosition(0);
    textPane.setText("");
    e.consume();
    }this should solve the purpose.This is not the recommended way to handle such things. This should be handled with InputMap and ActionMap.
    [http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]
    Here's an example:
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.KeyStroke;
    import javax.swing.text.BadLocationException;
    public class TextPaneActionTest {
        public static void main(String[] args) {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setLayout(new GridLayout(2,0));
            final JTextPane tpOne = new JTextPane();
            final JTextPane tpTwo = new JTextPane();
            KeyStroke enterStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0);
            KeyStroke ctrlEnterStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.ALT_DOWN_MASK);
            Object enterActionKey = tpOne.getInputMap().get(enterStroke);
            Action enterAction = tpOne.getActionMap().get(enterActionKey);
            tpOne.getInputMap().put(ctrlEnterStroke, enterActionKey);
            Action myEnterAction = new AbstractAction() {
                public void actionPerformed(ActionEvent ae) {
                    String text = tpOne.getText();
                    tpOne.setText("");
                    try {
                        tpTwo.getDocument().insertString(tpTwo.getDocument().getLength(), text + "\n", null);
                    } catch (BadLocationException ble) {
                        ble.printStackTrace();
            tpOne.getInputMap().put(enterStroke, myEnterAction);
            f.add(tpOne);
            f.add(new JScrollPane(tpTwo));
            f.setSize(400,300);
            f.setVisible(true);
    }

  • Only focus on items in JTable wich are editable

    Hi,
    I have a jtable with custom renderers and sometimes editors. When I tab through the table I only want it to tab from editable field to editable field thus skip the normal fields. Does anyone know how to do this?
    Thanks is advance,
    Hugo

    This example shows some things you can do with InputMaps and ActionMaps:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableActions extends JFrame
        public TableActions()
            JTable table = new JTable(15, 5)
                public boolean isCellEditable(int row, int column)
                  return column % 2 == 0;
    //              return false;
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            JScrollPane scrollPane = new JScrollPane( table );
            getContentPane().add( scrollPane );
            InputMap im = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
            //  Have the enter key work the same as the tab key
            KeyStroke tab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
            KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
            im.put(enter, im.get(tab));
            //  Disable the right arrow key
            KeyStroke right = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0);
            im.put(right, "none");
            //  Override the default tab behaviour
            //  Tab to the next editable cell. When no editable cells goto next cell.
            final Action oldTabAction = table.getActionMap().get(im.get(tab));
            Action tabAction = new AbstractAction()
                public void actionPerformed(ActionEvent e)
                    oldTabAction.actionPerformed( e );
                    JTable table = (JTable)e.getSource();
                    int rowCount = table.getRowCount();
                    int columnCount = table.getColumnCount();
                    int row = table.getSelectedRow();
                    int column = table.getSelectedColumn();
                    while (! table.isCellEditable(row, column) )
                        column += 1;
                        if (column == columnCount)
                            column = 0;
                            row +=1;
                        if (row == rowCount)
                            row = 0;
                        //  Back to where we started, get out.
                        if (row == table.getSelectedRow()
                        &&  column == table.getSelectedColumn())
                            break;
                    table.changeSelection(row, column, false, false);
            table.getActionMap().put(im.get(tab), tabAction);
        public static void main(String[] args)
            TableActions frame = new TableActions();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
    }

  • Prevent IC user drag table borders in Assignment

    How can I prevent that an incopy user is able to 'drag' table borders within an assignment/?
    I want the user to edit table text and figures but not to edit the layout/size of the table cells.

    To prevent ctrl-c /v /x modify the InputMap (and ActionMap) associated with the JTable.
    Look at SwingUtilities.getUIActionMap(...), SwingUtilities.getUIInputMap(...)
    InputMap map = SwingUtilities.getUIInputMap(myTable,1);
    mapi.remove(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_MASK ));This code remove the ctrl-c for the specified component (myTable).
    I hope this helps,
    Denis

  • Is this possible to Move window, inherited from JWindow instead of JFrame

    Hi
    This is Khurram, I have constructed a class that extends JWindow indtead of JFrame, I m trying to move it on screen (changing Location) through KeyListener (with arow keys). But the Listener is not working,
    I tried very much time,
    If I change just the base class from JWindow to JFrame(dont change any thing else), then all works properly as I required.
    I m pasting the code below,(two files)
    LocationManager.java is required to run MainApp.java.
    The Following MainApp.java is extends JWindow, that is not working properly
    please also check after changing it to JFrame. which will work properly
    ------required keys on keyboard--
    NUMPAD '+' key
    NUMPAD '-' key
    ' - ' key
    ' + ' key
    Arrow Keys 'up','down','left','right'
    ==========================================================
    MainApp.java
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class MainApp extends JWindow {
    static LocationManager appLoc = new LocationManager();
    public MainApp() {
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    public static void main(String[] args) {
    MainApp frm = new MainApp();
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int width = screenSize.width;
    int height = 45;
    //frm.setFocusable(true);
    frm.setSize(width, height);
    frm.setLocation(appLoc.setAppAtBottomCentered(width, height));
    frm.setLocation(appLoc.moveAppUpward(100));
    frm.setVisible(true);
    private void jbInit() throws Exception {
    this.getContentPane().setBackground(Color.white);
    addKeyListener(new java.awt.event.KeyAdapter(){
    int moveSpeed = 4;//must be even
    public void keyPressed(KeyEvent e){
    //JOptionPane.showMessageDialog(null,""+e.getKeyCode());
    if(e.getKeyCode() == KeyEvent.VK_SHIFT)
    if(moveSpeed==4)
    moveSpeed = 12;
    else
    moveSpeed = 4;
    if(e.getKeyCode() == KeyEvent.VK_UP)
    setLocation(appLoc.moveAppUpward(moveSpeed));
    else if(e.getKeyCode() == KeyEvent.VK_DOWN)
    setLocation(appLoc.moveAppDownward(moveSpeed));
    else if(e.getKeyCode() == KeyEvent.VK_LEFT)
    setLocation(appLoc.moveAppToLeft(moveSpeed));
    else if(e.getKeyCode() == KeyEvent.VK_RIGHT)
    setLocation(appLoc.moveAppToRight(moveSpeed));
    else if(e.getKeyCode() == 107) {//NUMPAD '+' Key For Vertically Increasing
    setSize(appLoc.increaseSize(0,moveSpeed));
    setLocation(appLoc.updateLocation());
    else if(e.getKeyCode() == 109) {//NUMPAD '-' Key For Vertically Decreasing
    setSize(appLoc.decreaseSize(0,moveSpeed));
    setLocation(appLoc.updateLocation());
    else if(e.getKeyCode() == 61) {// '+' Key For Horizontal Increasing
    setSize(appLoc.increaseSize(moveSpeed,0));
    setLocation(appLoc.updateLocation());
    else if(e.getKeyCode() == 45) {// '-' Key For Horizontal Decreasing
    setSize(appLoc.decreaseSize(moveSpeed,0));
    setLocation(appLoc.updateLocation());
    ===END MainApp.java=========================================
    =========================================================
    LocationManager.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.sql.*;
    public class LocationManager {
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    static Point newPoint = new Point();
    static Dimension newDim = new Dimension();
    static Dimension minDim = new Dimension();
    /** Creates a new instance of LocationManager */
    public LocationManager() {
    public LocationManager(int width, int height){
    this.setAppCenteredWithDim(width, height);
    public Point setAppCenteredWithDim(int width, int height){
    //Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    newDim.width = width;
    newDim.height = height;
    int sWidth = screenSize.width;
    int sHeight = screenSize.height;
    newPoint.x = (sWidth-width)/2;
    newPoint.y = (sHeight-height)/2;
    return newPoint;
    //return new Point(this.x, this.y);
    public Point setAppAtTopCentered(int width, int height){
    //Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    newDim.width = width;
    newDim.height = height;
    int sWidth = screenSize.width;
    int sHeight = screenSize.height;
    newPoint.x = (sWidth-width)/2;
    newPoint.y = 0;
    return newPoint;
    //return new Point(this.x, this.y);
    public Point setAppAtBottomCentered(int width, int height){
    //Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    newDim.width = width;
    newDim.height = height;
    int sWidth = screenSize.width;
    int sHeight = screenSize.height;
    newPoint.x = (sWidth-width)/2;
    newPoint.y = (sHeight-height);
    return newPoint;
    //return new Point(this.x, this.y);
    public Point setAppAtRightCentered(int width, int height){
    //Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    newDim.width = width;
    newDim.height = height;
    int sWidth = screenSize.width;
    int sHeight = screenSize.height;
    newPoint.x = 0;
    newPoint.y = (sHeight-height)/2;
    return newPoint;
    //return new Point(this.x, this.y);
    public Point setAppAtLeftCentered(int width, int height){
    //Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    newDim.width = width;
    newDim.height = height;
    int sWidth = screenSize.width;
    int sHeight = screenSize.height;
    newPoint.x = (sWidth-width);
    newPoint.y = (sHeight-height)/2;
    return newPoint;
    //return new Point(this.x, this.y);
    public Point moveAppUpward(int step){
    newPoint.y -= step;
    return newPoint;
    //return new Point(this.x, this.y);
    public Point moveAppDownward(int step){
    newPoint.y += step;
    return newPoint;
    //return new Point(this.x, this.y);
    public Point moveAppToLeft(int step){
    newPoint.x -= step;
    return newPoint;
    //return new Point(this.x, this.y);
    public Point moveAppToRight(int step){
    newPoint.x += step;
    return newPoint;
    //return new Point(this.x, this.y);
    public Dimension increaseSize(int w, int h){
    minDim.width = 116;
    minDim.height = 56;
    newDim.width += w;
    newDim.height +=h;
    if(w==0 && newDim.height > minDim.height)
    newPoint.y -= h/2;
    else if(newDim.width > minDim.width )
    newPoint.x -= w/2;
    return newDim;
    public Dimension decreaseSize(int w, int h){
    minDim.width = 116;
    minDim.height = 56;
    if(newDim.width > minDim.width )
    newDim.width -= w;
    if(newDim.height > minDim.height)
    newDim.height -= h;
    if(w==0 && newDim.height > minDim.height)
    newPoint.y += h/2;
    else if(newDim.width > minDim.width)
    newPoint.x += w/2;
    return newDim;
    public Point updateLocation(){
    return newPoint;
    //return new Point(this.x, this.y);
    =============END LocationManager.java=====================================

    Hi,
    There was a problem with using a JWindow without owner : this window can't be focused, so it can't retrieve key events.
    Here is a solution (with some modifications specially with using InputMap and ActionMap) :
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MainApp extends JFrame {
         static LocationManager appLoc = new LocationManager();
         public MainApp() {
              setUndecorated(true);
              getContentPane().setBackground(Color.white);
              registerKeyboardActions();
         public static void main(String[] args) {
              MainApp frm = new MainApp();
              Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
              int width = screenSize.width;
              int height = 45;
              frm.setSize(width, height);
              frm.setLocation(appLoc.setAppAtBottomCentered(width, height));
              frm.setLocation(appLoc.moveAppUpward(100));
              frm.setVisible(true);
         private void registerKeyboardActions() {
              JComponent component = getRootPane();
              InputMap im = component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
              ActionMap am = component.getActionMap();
              im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "moveUp");
              im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "moveDown");
              im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "moveLeft");
              im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "moveRight");
              im.put(KeyStroke.getKeyStroke(107, 0), "increaseWidth");
              im.put(KeyStroke.getKeyStroke(109, 0), "decreaseWidth");
              im.put(KeyStroke.getKeyStroke(61, 0), "increaseHeight");
              im.put(KeyStroke.getKeyStroke(45, 0), "decreaseHeight");
              im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, InputEvent.SHIFT_DOWN_MASK), "moveUpFast");
              im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, InputEvent.SHIFT_DOWN_MASK), "moveDownFast");
              im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, InputEvent.SHIFT_DOWN_MASK), "moveLeftFast");
              im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, InputEvent.SHIFT_DOWN_MASK), "moveRightFast");
              im.put(KeyStroke.getKeyStroke(107, InputEvent.SHIFT_DOWN_MASK), "increaseWidthFast");
              im.put(KeyStroke.getKeyStroke(109, InputEvent.SHIFT_DOWN_MASK), "decreaseWidthFast");
              im.put(KeyStroke.getKeyStroke(61, InputEvent.SHIFT_DOWN_MASK), "increaseHeightFast");
              im.put(KeyStroke.getKeyStroke(45, InputEvent.SHIFT_DOWN_MASK), "decreaseHeightFast");
              am.put("moveUp", new MoveAction(0, 4));
              am.put("moveDown", new MoveAction(1, 4));
              am.put("moveLeft", new MoveAction(2, 4));
              am.put("moveRight", new MoveAction(3, 4));
              am.put("increaseWidth", new ResizeAction(0, 4, 0));
              am.put("decreaseWidth", new ResizeAction(1, 4, 0));
              am.put("increaseHeight", new ResizeAction(0, 0, 4));
              am.put("decreaseHeight", new ResizeAction(1, 0, 4));
              am.put("moveUpFast", new MoveAction(0, 12));
              am.put("moveDownFast", new MoveAction(1, 12));
              am.put("moveLeftFast", new MoveAction(2, 12));
              am.put("moveRightFast", new MoveAction(3, 12));
              am.put("increaseWidthFast", new ResizeAction(0, 12, 0));
              am.put("decreaseWidthFast", new ResizeAction(1, 12, 0));
              am.put("increaseHeightFast", new ResizeAction(0, 0, 12));
              am.put("decreaseHeightFast", new ResizeAction(1, 0, 12));
         private final class MoveAction extends AbstractAction {
              private int direction;
              private int speed;
              public MoveAction(int direction, int speed) {
                   this.direction = direction;
                   this.speed = speed;
              public void actionPerformed(ActionEvent event) {
                   switch (direction) {
                        case 0 :
                             setLocation(appLoc.moveAppUpward(speed));
                             break;
                        case 1 :
                             setLocation(appLoc.moveAppDownward(speed));
                             break;
                        case 2 :
                             setLocation(appLoc.moveAppToLeft(speed));
                             break;
                        case 3 :
                             setLocation(appLoc.moveAppToRight(speed));
                             break;
                        default :
                             break;
         private final class ResizeAction extends AbstractAction {
              private int type;
              private int width;
              private int height;
              public ResizeAction(int type, int width, int height) {
                   this.type = type;
                   this.width = width;
                   this.height = height;
              public void actionPerformed(ActionEvent event) {
                   switch (type) {
                        case 0 :
                             setSize(appLoc.increaseSize(width, height));
                             setLocation(appLoc.updateLocation());
                             validate();
                             break;
                        case 1 :
                             setSize(appLoc.decreaseSize(width, height));
                             setLocation(appLoc.updateLocation());
                             validate();
                             break;
                        default :
                             break;
    }I hope this helps,
    Denis

Maybe you are looking for

  • Transferring iTunes from pc to mac still using my external drive

    I have a pc and an external drive with all of my music and videos stored on it the external drive. How can I transfer the library to my new macbook and still have my songs on my external drive?

  • Mass deletion of document number ranges intervals for several company codes

    Dear experts, We are running version ECC6 and are about to go-live a lot of company codes simultaneously. We would like to delete satndard number ranges intervals for these company codes. Is there a way to delete the number ranges intervals (which ha

  • Query View not available as DataProvider in Report Designer

    Hi experts, I am unable to find any query views when I tried to insert DataProvider in Report Designer. All that is available in InfoAreas view is only queries. When I tried to restrict type to only Query View, they are only visible in History view a

  • Eprint problem

    I connected up my eprint and have a address for it. I sent a photo to the printer. Where do I find the photo to print it? This question was solved. View Solution.

  • Responding to a message from the lock screen

    Hello, I just upgraded to an iphone 6 plus and I wanted to use the feature that allows me to respond to messages on the lock screen.  Right now it is not allowing me to do so.  I upgraded from the iphone 4 and used the data that I had on it to restor