Hlep in deleting Componantes using Key event listeners.

Hi All,
I am tring to write a GUI program. I am dragging componets from the left side of the panel to the right side of the panel. Everything works well as of now. But i am tring to delete the componets which i placed on the right side of the paenl using key stroke events. Can anyone tell how this can be done. I have like labels and textfield componeets.
Please help
Smitha

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
public class KeyDeletion extends JPanel {
    JComponent selectedComponent;
    public KeyDeletion(JFrame f) {
        setLayout(null);
        Dimension d = new Dimension(65,25);
        for(int j = 0; j < 4; j++) {
            JLabel label = new JLabel("label " + (j+1),
                                       JLabel.CENTER);
            label.setBorder(BorderFactory.createEtchedBorder());
            int x = 20 + j*(d.width + 25);
            int y = 20 + j*(d.height + 75);
            label.setBounds(x, y, d.width, d.height);
            add(label);
        addMouseListener(ma);
        registerKey(f);
    /** Press the "x" key to delete selected label. */
    private void registerKey(JFrame f) {
        JRootPane jrp = f.getRootPane();
        int c = JComponent.WHEN_IN_FOCUSED_WINDOW;
        jrp.getInputMap(c).put(KeyStroke.getKeyStroke("X"), "DELETE");
        jrp.getActionMap().put("DELETE", deleteAction);
    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        KeyDeletion panel = new KeyDeletion(f);
        f.add(panel);
        f.setSize(400,400);
        f.setLocation(200,200);
        f.setVisible(true);
    private MouseAdapter ma = new MouseAdapter() {
        Border etched = BorderFactory.createEtchedBorder();
        Border select = BorderFactory.createLineBorder(Color.red);
        JComponent lastSelection;
        public void mousePressed(MouseEvent e) {
            Point p = e.getPoint();
            Component[] c = getComponents();
            boolean haveSelection = false;
            for(int j = 0; j < c.length; j++) {
                Rectangle r = c[j].getBounds();
                if(r.contains(p)) {
                    setSelection(c[j]);
                    haveSelection = true;
                    break;
            if(!haveSelection && selectedComponent != null) {
                setSelection(null);
        private void setSelection(Component c) {
            selectedComponent = (JComponent)c;
            if(c != null)
                selectedComponent.setBorder(select);
            if(lastSelection != null)
                lastSelection.setBorder(etched);
            lastSelection = selectedComponent;
    private Action deleteAction = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            if(selectedComponent != null) {
                remove(selectedComponent);
                selectedComponent = null;
                repaint();
}

Similar Messages

  • Using Multiple Event Listeners

    Hi,
    I have a movielcip (A) class in which I have used a Tween class effect on a child movieclip (B) scrollRect. The (B) Movieclip in turn has several movieclips whose have tween class effect being executed on thier child movieclips.
    the tweens are all unique to each movieclip
    and the event listeners are taken off once completed.
    This works all well and good in FLASH IDE...
    My problem arises when I try to view this in a browser on a Windows XP
    it doesnt work in
    Opera Version 9.63
    Firefox 2.0
    and Google Chrome 2.0
    The only browser it works fluently in is
    Internet Explorer 7.0.5
    What is happening in most cases it that the animation appears to "stick" but i think what may be happening is the listening or removal of the event listeners. The animations are left incompleted.
    Is there any rule of thumb when using multiple event listeners?
    here is a snippet of some of my code
    on click event from movieclip (A)
    private function scrollToSlidePrev(e:MouseEvent) {
                   if (((slideIndex - 1) >= 0)) {
                        nextButton.mouseEnabled = nextButton.enabled = previousButton.enabled = previousButton.mouseEnabled = false;
                        var position:Number = 0-SLIDEAREA.width;
                        var slide1:TileListSlide = slides[slideIndex] as TileListSlide;
                        var slide2:TileListSlide = slides[--slideIndex] as TileListSlide;
                        scrollSlide(position,slide1,slide2);
    tween animation in movieclip (A) on (B)
    private function scrollSlide(pos:int,slide1:TileListSlide,slide2:TileListSlide) {
                   slide1.resizeSlideTo(0.6); // execute tween on child movie clips in B
                   slide2.resizeSlideTo(1); // same as above;
                   var rect:Rectangle = sliderMc.scrollRect;
                   var tween1:Tween = new Tween(rect,"x",Regular.easeOut,rect.x,rect.x + pos,3,true);
                   tween1.addEventListener(TweenEvent.MOTION_CHANGE,setSliderScroll,false,4);
                   tween1.addEventListener(TweenEvent.MOTION_FINISH,toggleButtonEnabled,false,3);
    tween animation in movieclip (B) children
    public function resizeSlideTo(sc) {
                   var m:Matrix = tileList.transform.matrix as Matrix;
                   var p:Point = new Point (m.a, 0);
                   var tween2:Tween = new Tween(p,"x",Regular.easeOut,p.x,sc,3,true);
                   if (numericStepper != null) {
                        if (sc != 1) {
                             numericStepper.visible = false;
                             tween2.removeEventListener(TweenEvent.MOTION_FINISH,showStepper);
                        if (sc === 1) {
                             tween2.addEventListener(TweenEvent.MOTION_FINISH,showStepper,false,2);
                   tween2.addEventListener(TweenEvent.MOTION_CHANGE,setScaleOnScroll,false,3);
    here is the link
    http://visual_admin.web.aplus.net/ticker/ticker_widget.html
    the effect disables and re-enables the buttons when its done.... then the listeners are removed.
    each one with the exception cretes its own unique tween (obviously this is a custom class built as each clip)
    i really don't know what to make of it guys         

    apparantly making the tween a property of the class rather than a random variable in a function worked.....go figure

  • Focus problem using key event

    Hi!
    There is an application I've created uses key event that needs your help.
    As you know, that setting 'Mnemonic' to a JButton object makes the button accessible by a key mentioned in the parameter as the following ->
                   OkButton.setMnemonic(KeyEvent.VK_O);Now, pressing 'Alt' and 'O' keys together will do the same action as the 'OKButton' does.
    But as of me, I think pressing two keys together is not a complete handy job.
    So, is there any code that will do the same, by pressing only the 'O' key ?
    Ok! I know that there is something to be taken care of; that is, if I want the button to react by pressing only the 'O' key the button must be in focus [value returned by the method [code]isFocusable() for the button must return true.]
    Then how the 'Mnemonic' works ?!! When 'Mnemonic' do something, button does not have any focus.
    Only, I press the Alt+O and the work done successfully! No need to take care wherever the focus is. So, is there any way to do alike, where I don't have to manage the focus subsystem?? I would only press the 'O' key and the task will be done.
    Please send a sample code. Thanks!

    I suggest you look into Key Bindings:
    "How to Use Key Bindings"
    http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html
    Here is a short demo program that uses Key Bindings to do what you describe:
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.*;
    public class PressOTest extends JFrame {
        public PressOTest() {
            super("Press O or C");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            // Action that will be associated with the OK button and with
            // the 'O' key event
            Action okAction = new AbstractAction("Ok") {
                public void actionPerformed(ActionEvent e) {
                    JOptionPane.showMessageDialog(PressOTest.this, "Ok!");
            // Action that will be associated with the Cancel button and with
            // the 'C' key event
            Action cancelAction = new AbstractAction("Cancel") {
                public void actionPerformed(ActionEvent e) {
                    JOptionPane.showMessageDialog(PressOTest.this, "Cancel!");
            // Register Key Bindings for the 'O' and 'C' keys:
            InputMap im = getRootPane().getInputMap(
                    JComponent.WHEN_IN_FOCUSED_WINDOW);
            ActionMap am = getRootPane().getActionMap();
            im.put(KeyStroke.getKeyStroke( KeyEvent.VK_O, 0 ), "ok");
            am.put( "ok", okAction );
            im.put(KeyStroke.getKeyStroke( KeyEvent.VK_C, 0 ), "cancel");
            am.put( "cancel", cancelAction );
            // Create and add OK & Cancel buttons:
            JButton okButton = new JButton(okAction);
            JButton cancelButton = new JButton(cancelAction);
            Box box = Box.createHorizontalBox();
            box.add( Box.createHorizontalGlue() );
            box.add( okButton );
            box.add( Box.createHorizontalStrut(10) );
            box.add( cancelButton );
            box.add( Box.createHorizontalGlue() );
            getContentPane().add( box );
            setSize(300, 300);
            setLocationRelativeTo(null);
        public static void main(String[] args) {
            new PressOTest().setVisible(true);
    }

  • How to block JTree key event listeners

    I have a JToolbar I am managing keyboards events for (e.g. PageUp, PageDown, right, left, up, down). I also have a JTree in another panel. I have to use 'Alt + PageUp' instead of PageUp because, if I use 'PageUp' (without also using the Alt key), and, the JTree gets the focus, then the JTree will respond to 'PageUp' instead of my JToolbar.
    I have my key actions in a 'getKeystrokeActions()' method which I pass the JToolbar into so I tried passing the JTree to the same method. This doesn't quite do what I want as both components now respond to a 'PageUp' key event.
    There must be some way to tell the JTree not to handle key events but I can't seem to find it. Any help much appreciated.

    Remove the key listeners?
    JTree tree = new JTree();
    for(KeyListener listener : tree.getKeyListeners()) {
        tree.removeKeyListener(listener);
    }Another option would be to just do
    tree.setFocasable(false);

  • Is using key events really that hard?

    I am trying to implement a keyListener for my application, and it seems
    way harder than it should be. My application is simple: A JFrame
    with one button and one JPanel upon which I draw. When I click
    in the JPanel and type, I want things to happen.
    After much looking, it seems I have to not only implement KeyListener,
    but also MouseListener, so when the mouse enters I can call
    requestFocusInWindow().
    That seems to work sometimes, but not when I leave and come back,
    and not always when the application first appears.
    So do I also have to implement FocusListener?
    Why is this so hard to do? MouseListener is very easy to implement,
    but KeyListener seems to be a huge pain in the butt.
    Can someone point me to a simple tutorial or example that just
    has a few swing elements, and processes key events?
    I feel like with Java I often try enough things until it finally works,
    and never really understand why, and what it was that fixed it.
    The documentation and API does not fully describe everything one
    needs to know to use the API "properly". Am I the only one frustrated
    by this? I have programmed in Java/Swing for years, and JUST LAST
    WEEK discovered that when implementing paint in swing, one should
    override paintComponent and not paint. But then why does overriding
    paint usually work? There are too many quirks in Java that let you
    get away with doing things wrong, and then suddenly, your application
    is broken. It wouldn't be so bad if the API was more clear on some of
    these suble issues.
    Thanks,
    Chuck.

    How to Use Key Bindings

  • Using key event

    hey, I have an application with multiple frames and dialogs, that are in top of each other, I would like to define a short key (Ctrl+s for example) on the top frame and to handle the event of this key combination, no matter where the focus is, it might be on other dialog... how can I accomplish this?

    [Global Event Listeners|http://www.camick.com/java/blog.html?name=global-event-listeners]

  • How Do I create a Modular Function for use with Event Listeners

    OK I'm very new to AS3 and I'm curious as to how to get
    modular functions to work in AS3.
    for instance if I have this code:
    function snowfall(snowflake:MovieClip, movement:Number):void
    snowflake.y = movement;
    snowfall(snowflake1_mc, 10);
    snowfall(snowflake2_mc, 20);
    snowfall(snowflake3_mc, 30);
    Now on the stage I place 3 instances of a snowflake movie
    clip. Each time I call the "snowfall" function I refer to a new
    instance of the snowflake movie clip and a different amount of
    movement along the y axis.
    This is great but what if I want to use a button to control
    these snowflake movie clips and I want to maintain that modular
    nature? I don't really get how to do this. I created a button with
    an instance name of "myButton" and I've tried this code but it is
    throwing an error I don't really understand:
    myButton.addEventListener(MouseEvent.CLICK,
    snowfall(snowflake3_mc, 30));
    Can I not pass information to a function using an
    EventListener?

    Hi --
    What you want to do on your button is this..
    myButton.addEventListener(MouseEvent.CLICK,snowfall)
    Then in the function you can check which button called the
    function using
    properties of the event..
    function snowfall(event:MouseEvent) {
    trace(event)
    I am not sure off the top of my head of the data available in
    the "event"
    but the trace will show you all the variables you can access.
    As far as the amount of movement -- how is this information
    set? You can
    keep this in a global variable and then read it from inside
    the event
    handler rather than needing to pass it to the event.
    Rich
    "HalcyonCollective" <[email protected]>
    wrote in message
    news:fl695r$l95$[email protected]..
    > OK I'm very new to AS3 and I'm curious as to how to get
    modular functions
    > to
    > work in AS3.
    >
    > for instance if I have this code:
    >
    >
    function snowfall(snowflake:MovieClip, movement:Number):void
    > {
    > snowflake.y = movement;
    > }
    >
    > snowfall(snowflake1_mc, 10);
    > snowfall(snowflake2_mc, 20);
    > snowfall(snowflake3_mc, 30);
    >
    > Now on the stage I place 3 instances of a snowflake
    movie clip. Each time
    > I
    > call the "snowfall" function I refer to a new instance
    of the snowflake
    > movie
    > clip and a different amount of movement along the y
    axis.
    >
    > This is great but what if I want to use a button to
    control these
    > snowflake
    > movie clips and I want to maintain that modular nature?
    I don't really get
    > how
    > to do this. I created a button with an instance name of
    "myButton" and
    > I've
    > tried this code but it is throwing an error I don't
    really understand:
    >
    >
    myButton.addEventListener(MouseEvent.CLICK,
    snowfall(snowflake3_mc,
    > 30));
    >
    > Can I not pass information to a function using an
    EventListener?
    >

  • Associating key events to a TextBox

    Hello All!
    Can anybody tell me how to associate key events with a TextBox? Something like when a certain key is pressed and released, a certain combinations of characters is inserted e.g. =-)
    I am trying to develop a simple application that allows users to type text with non-English characters, e.g. Russian and for that I have created a canvas and I am using key events i.e. KeyPressed and KeyReleased methods. Using a canvas is a bit insufficient because users cannot move the cursor freely through the text.
    I have read on te web that I can create a CustomeItem and override the KeyPressed methods but I could not do it; I could not find any simlar code example.
    Can anybody help me by providing me with a simple example or suggesting me an alternative way?
    Many thanks in advance

    {color:#008080}*Hello again!*
    I managed to create a CustomItem that overrides KeyPressed method, but now I am having difficulties making my textBox reacts to my keyPressed method.
    The early version of this CustomeItem overrides the KeyPressed method by assigning each key to a certain collection of chars. When a key is pressed, a string of these chars is drawn on the Canvas, which works fine. Now because I want to be able to edit the text, e.g. delete a certain char in the middle of the string, I want to use a TextBox or a TextField. The current problem is that my TextBox does not react to my key presses the way I want (I used setString() method); it reacts to the original key presses which print the original chars (from A through to Z and 1 through to 9).
    Is it possible to set the contents of a TextBox or TextField depending on my key presses? Could you suggest me an alternative way?
    Many thanks in advance!!{color}

  • Help with understanding key event propagation

    Hello,
    I am hoping someone can help me understand a few things which are not clear to me with respect to handling of key events by Swing components. My understanding is summarized as:
    (1) Components have 3 input maps which map keys to actions
    one for when they are the focused component
    one for when they are an ancestor of the focused component
    one for when they are in the same window as the focused component
    (2) Components have a single action map which contains actions to be fired by key events
    (3) Key events go to the currently focused component
    (4) Key events are consumed by the first matching action that is found
    (5) Key events are sent up the containment hierarchy up to the window (in which case components with a matching mapping in the WHEN_IN_FOCUSED_WINDOW map are searched for)
    (6) The first matching action handles the event which does not propagate further
    I have a test class (source below) and I obtained the following console output:
    Printing keyboard map for Cancel button
    Level 0
    Key: pressed C
    Key: released SPACE
    Key: pressed SPACE
    Level 1
    Key: pressed SPACE
    Key: released SPACE
    Printing keyboard map for Save button
    Level 0
    Key: pressed SPACE
    Key: released SPACE
    Level 1
    Key: pressed SPACE
    Key: released SPACE
    Printing keyboard map for Main panel
    Event: cancel // typed SPACE with Cancel button having focus
    Event: save // typed SPACE with Save button having focus
    Event: panel // typed 'C' with panel having focus
    Event: panel // typed 'C' with Cancel button having focus
    Event: panel // typed 'C' with Save button having focus
    I do not understand the following aspects of its behaviour (tested on MacOSX although I believe the behaviour is not platform dependent):
    (1) I assume that the actions are mapped to SPACE since the spacebar clicks the focused component but I don't explicitly set it?
    (2) assuming (1) is as I described why are there two mappings, one for key pressed and one for key released yet the 'C' key action only has a key pressed set?
    (3) assuming (1) and (2) are true then why don't I get the action fired twice when I typed the spacebar, once when I pressed SPACE and again when I released SPACE?
    (4) I read that adding a dummy action with the value "none" (i.e. the action is the string 'none') should hide the underlying mappings for the given key, 'C' the my example so why when I focus the Cancel button and press the 'C' key do I get a console message from the underlying panel action (the last but one line in the output)?
    Any help appreciated. The source is:
    import javax.swing.*;
    public class FocusTest extends JFrame {
         public FocusTest ()     {
              initComponents();
              setTitle ("FocusTest");
              setLocationRelativeTo (null);
              setSize(325, 160);
              setVisible (true);
         public static void main (String[] args) {
              new FocusTest();
    private void initComponents()
         JPanel panTop = new JPanel();
              panTop.setBackground (java.awt.Color.RED);
    JLabel lblBanner = new javax.swing.JLabel ("PROPERTY TABLE");
    lblBanner.setFont(new java.awt.Font ("Lucida Grande", 1, 14));
    lblBanner.setHorizontalAlignment (javax.swing.SwingConstants.CENTER);
              panTop.add (lblBanner);
              JPanel panMain = new JPanel ();
              JLabel lblKey = new JLabel ("Key:");
              lblKey.setFocusable (true);
              JLabel lblValue = new JLabel ("Value:");
    JTextField tfKey = new JTextField(20);
    JTextField tfValue = new JTextField(20);
    JButton btnCancel = new JButton (createAction("cancel"));     // Add a cancel action.
    JButton btnSave = new JButton (createAction("save"));          // Add a sve action.
              panMain.add (lblKey);
              panMain.add (tfKey);
              panMain.add (lblValue);
              panMain.add (tfValue);
              panMain.add (btnCancel);
              panMain.add (btnSave);
              add (panTop, java.awt.BorderLayout.NORTH);
              add (panMain, java.awt.BorderLayout.CENTER);
    setDefaultCloseOperation (javax.swing.WindowConstants.EXIT_ON_CLOSE);
    // Add an action to the panel for the C key.
              panMain.getInputMap (JComponent.WHEN_IN_FOCUSED_WINDOW).put (KeyStroke.getKeyStroke (java.awt.event.KeyEvent.VK_C, 0), "panel");
              panMain.getActionMap ().put ("panel", createAction("panel"));
              // FAILS ???
              // Add an empty action to the Cancel button to block the underlying panel C key action.
    btnCancel.getInputMap().put (KeyStroke.getKeyStroke (java.awt.event.KeyEvent.VK_C, 0), "none");
    // Print out the input map contents for the Cancel and Save buttons.
    System.out.println ("\nPrinting keyboard map for Cancel button");
    printInputMaps (btnCancel);
    System.out.println ("\nPrinting keyboard map for Save button");
    printInputMaps (btnSave);
              // FAILS NullPointer because the map contents are null ???
    System.out.println ("\nPrinting keyboard map for Main panel");
    // printInputMaps (panMain);
    private AbstractAction createAction (final String actionName) {
         return new AbstractAction (actionName) {
              public void actionPerformed (java.awt.event.ActionEvent evt) {
                   System.out.println ("Event: " + actionName);
    private void printInputMaps (JComponent comp) {
         InputMap map = comp.getInputMap();
         printInputMap (map, 0);
    private void printInputMap (InputMap map, int level) {
         System.out.println ("Level " + level);
         InputMap parent = map.getParent();
         Object[] keys = map.allKeys();
         for (Object key : keys) {
              if (key.equals (parent)) {
                   continue;
              System.out.println ("Key: " + key);
         if (parent != null) {
              level++;
              printInputMap (parent, level);
    Thanks,
    Tim Mowlem

    Use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the posted code retains its original formatting.
    1) In the Metal LAF the space bar activates the button. In the Windows LAF the Enter key is used to activate the button. Therefore these bindings are added by the LAF.
    2) The pressed binding paints the button in its pressed state. The released binding paint the button in its normal state. Thats why the LAF adds two bindings.
    In your case you only added a single binding.
    3) The ActionEvent is only fired when the key is released. Same as a mouse click. You can hold the mouse down as long as you want and the ActionEvent isn't generated until you release the mouse. In fact, if you move the mouse off of the button before releasing the button, the ActionEvent isn't even fired at all. The mouse pressed/released my be generated by the same component.
    4) Read (or reread) the [url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html#howto]How to Remove Key Bindings section. "none" is only used to override the default action of a component, it does not prevent the key stroke from being passed on to its parent.

  • Delete fotos in iPhoto events not used in Foto Book

    the problem with this issue is that there is no "indicator" in or on the pictures in the event the foto book was made from which says: this was USED in the foto book/project and this was NOT USED in the foto book/project. So, how to delete those in the event which were NOT USED?
    If you invoke all the fotos of the event on the side of the foto book selection screen those you USED are flagged, the one NOT USED are unflagged, but the iPhoto does not allow at that stage to delete multiple images by using the Command click method suggested when you are viewing the event pictures.

    Do you want to must remove the unplaced pictures form the book or from the library?  If it's from the library and you don't use the ratings try the following:
    Bring up the unplaced photos tray, select one at a time and give it a rating (this works as long as you don't use ratings).  Then create a smart album with the criteria Rating is X.  All of the photos with that rating will be displayed. 
    Select them and use the key combination Command+Option+Delete to move them to the iPhoto Trash bin. Then empty the trash bin.
    Warning:  This will delete the photos completely from the library.  Make sure this is what you want because they'll be gone for good then.
    OT

  • How to capture backspave and delete key events

    Hi ,
    i would like perform some javascript code on pressing backspace or delete key.
    initially i thought of adf clientlsitener keypress event.but this is not capturing backsapce key event
    what is the alternate way capture backspace or delete key event?
    please help

    Hi
    the following script cancels the input event when the back key is pressed
           function keyTrap(inputEvent){
             var keycode = inputEvent.getKeyCode();
             if(keycode ==8){
               inputEvent.cancel();
           }Use a clientListener
            <af:inputText label="Label 4" id="it7">
              <af:clientListener method="keyTrap" type="keyDown"/>
            </af:inputText>Frank

  • I need to reprogram the delete and enter key to the left side of a external keyboard for the ipad mini. don't need the caps/lock or ctrl key and due to an injury my daughter can only use her left hand to type. She is using a text to speech app to verbaliz

    I need to reprogram the delete and enter key to the left side of a external keyboard for the ipad mini. I don't need the caps/lock or ctrl key. Due to a brain injury my daughter can only use her left hand to type. She also uses a text to speech app to verbalize all of her needs since her speech isn't intelligible any longer either. And her vision was significantly affected also, so the keyboard has to be mounted about 6 inches from her face. So to reach across the keyboard with her left hand to the right side delete and enter button is physically difficult and causes typing errors, which cause people to not understand what shes trying to say.
    The best keyboard so far is the Zagg folio mini. I just had to make stickers to enlarge the letters on the key buttons.
    Does anyone know how I can reprogram these two keys? Or where I can buy a wireless mini keyboard for Ipad made for lefthanders with these two functions on the left side. I have searched for days and days. It's sooooo important to me that she be able to contribute her voice again. Imagine if you got in a car accident and couldn't speak clearly any longer, but understood everything still. Thanks for any help and suggestions you all take the time to share with me. I really appreciate the kindness of strangers to help me help my daughter.
    Sami's mom

    Sami\'s mom wrote:
    I need to reprogram the delete and enter key to the left side of a external keyboard for the ipad mini.
    You cannot.

  • Is there a way to trigger button's action listeners from key events?

    I rarely do GUI programming, especially not in Java. But now I am working on a GUI app and would like to get some help.
    Say I have a simple GUI consists of a JFrame, and a bunch of buttons on its JToolBar. The buttons on the JToolBar are for navigation of a set of documents, first, prev, next, last etc. All buttons are assigned action command strings, and their all trigger the same instance of action listener. inside of the action listener, it does the correct navigation based on the action command from the event.
    but some users want to be able to use the keyboard to do the navigation, because they think clicking the buttons are too slow.
    So is there a graceful way to receive the different key press events and trigger corresponding navigation actions (hopefully it reuses the code that is already there, e.g. the action listener)? thanks.
    -- Jim

    but some users want to be able to use the keyboard to do the navigation, because they think clicking the buttons are too slow. That is always the case in any GUI. Any application should be designed to use either the mouse or the keyboard.
    All buttons are assigned action command strings,That is not the way the GUI should be designed.
    Instead you should be creating Actions. Then you can add the Action to a button and you can associate the Action with a KeyStroke which is called "Key Binding". This is the way all Swing components work. You can read the [url http://download.oracle.com/javase/tutorial/uiswing/TOC.html]Swing tutorial for more information and examples. Start with the section on:
    a) How to Use Actions
    b) How to Use Key Bindings

  • How to detect the key enter with a numerical control without using loop event?

    I want to accept a numerical value only when the key enter is pressed, but without using the event. How to detect the char "enter" with a numerical control?
    Thanks!

    When the user edits a numeric control with a keyboard, its property "key focus" is true. When the user hits enter, key focus becomes false. Poll the property to latch the control valuse at the true-false transition. That won't work if the user modify the control using up and down arrows.
    LabVIEW, C'est LabVIEW

  • How to listen a key event without having any window component

    Hi all,
    I would like to know how can I listen key events from an application that doesn't use windows
    Thanks

    yoiu can make a Thread run inside your application. This will listen for inputs in the command line. For examplethis is part of a chat server (on the console) with let the server manager to enter messages or commands.
    The message or command entered on the console by the user is catched and processed as a String. The string is passed to the processConsole() method, you must define yourself.
    Th Thread is never stopped, so the user may enter any message at any time
    The core of you application should also be a Thread for better performance, but maybe it will also work without. Jst try and provide needed importstatements.
    Runnable runInput = new Runnable() {
            public void run() {
              while(true) {
                try {
                  byte buffer[] = new byte[255];
                  System.out.print(prompt);
                  System.in.read(buffer);//, 0, 255);
                  String inputString = new String(buffer, "Default");
                  processConsole(inputString);
                catch(NullPointerException npe) {
                  System.out.println("Syntax error");
                catch(Exception e) {e.printStackTrace(); }
          Thread inputThread = new Thread(runInput);
          inputThread.start();

Maybe you are looking for

  • I was propmted to download a software update and now my ipad has frozen

    I set the ipad to download the software update as prompted. I was prompted to connect the ipad to the mains electricity before running the update. I inadvertently (stupidly) forgot to switch on at the wall socket and left the download to run overnigh

  • Macbook Pro will not power on without battery installed

    Hi there, I have a Macbook Pro A1226 that fails to power on without a battery installed. i.e. will not run off AC power on its own. I have tried 2 other power adapters, no change. All 3 adapters are outputting the correct voltage without fluctuations

  • UPGRADED FROM PRE 3.0 TO PRE 10...WAS THIS A MISTAKE????

    I have a windows 7 operating system with a (c) drive with over 200gb, a separate slave drive with over 100gb, and 4 gb memory. My Video card is up to date, and quite large since I am an avid online game player. I love to write, and create videos, and

  • Photo/print question

    Another likely "dumb question" from a rookie ID user: I've imported a photo and the color looks off (on my screen) -- should I be concerned about photo print quality? The photo seems to look OK when printed off my printer, but it will eventually be p

  • Wire: Function Conflict, Static VI Reference

    Hello Community, Sorry if this has already been answered before, but I have spent an hour searching. I am trying to learn a little about using subVIs to clean up my code. I'm trying to connect a static VI reference of a Gaussian function that I made