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

Similar Messages

  • 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);
    }

  • Sync one folder two machines - Is it really that hard.

    Sync one folder two machines - Is it really that hard.
    I have one folder (with a bunch of subfolders totally 3k of image files) I'd like to mirror them on both my laptop and desktop machines.
    I'd like the Desktop machine to mirror everything on the laptop and when I travel with the laptop I add images once I return everything new will be copied over.
    Things I don't want in this system
    • Third party software, If the OSX 10.4.8 can do it all the better
    • Having to Manually hit a sync button. (But willing to budge on this one)
    • It Making a duplicate copy of the folder each and everytime it connects.
    I have looked at a few free items on mac's website:
    Auto-backup Script (written in 2000)
    http://www.apple.com/applescript/folderactions/05.html
    Sync Folders 0.9 (written in 2004)
    http://www.apple.com/downloads/macosx/automator/syncfolders.html
    But I can't seem to get either to work on my machines The script is asking me to do something that I can't even phyically do anymore in 10.4.8
    any idea's or suggestions?
    Thanks
    Robert Dall
    iMac G4, iBook G4   Mac OS X (10.4.8)   80g video ipod (black is back baby!)

    So much for other people having lives to live...
    I'd help you out if I knew anything about rsync, and
    I'm sure many others would, too, but apparently the
    ones who do know are doing other things. Considering
    it's a weekend, that really shouldn't be surprising.
    There are people and companies that give such
    immediate service for a fee. Look around and I'm sure
    you'll find one that'll offer to not only advise you
    but will also create the solution for you. They'll
    even you let you have the solution, for a price.
    Azqi, please don't belittle me about how the captitalism works in the world. I might been in a small community outside Vancouver that doesn't even have a large MAC dealership who could answer my question. I was already at the shop that does deal in mac because I wanted to SHOP LOCAL. I am perfectly aware I am on a FREE forum and have a life outside of this forum also! I waited four days before I said what I said and before my little question was lost in the forums. If I had 300 responses to my question like yours I'd never return. . . .
    I am just saying that it has been a bit of a cold welcome to these forums, as this isn't the first question that has gone unanswered. . . . and thanks to some helpful folks it isn't.

  • 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();
    }

  • 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]

  • 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}

  • How to distinguish is cell get key event or mouse event in table?

    Hi!
    I have a JTable.
    1.Select cell and double click. As result caret is show
    2.Select cell and start type. As result caret is show
    How distinguish is caret is show, because cell get mouse event or key event?
    Thank you.

    Hm ...
    the problem with the key events is, that they are partically taking place in an editor component - but the double click of the mouse clicked on a cell, which is not currently edited, can be get by a MouseListener added to the JTable.
    My idea to that is as follows - hold the double_clicked state in a boolean variable hold by your JTable subclass - it is set by a MouseListener added to the JTable - and reset by the overwritten prepareEditor(...) method. This method should do the following:
    // say, double_clicked is a boolean field in your JTable subclass
    public Component prepareEditor(TableCellEditor editor,int row,int column) {
    Component c = super.prepareEditor(editor,row,column);
    if ((!double_clicked)&&(c instanceof JTextField)) { ((JTextField) c).setText(""); }
    double_clicked = false;
    return c;
    }now you have only to implement an add a MouseListener to your JTable subclass which detects this double click and sets the double_clicked field accordingly.
    This is an idea on the fly - hope it is helpful for you.
    greetings Marsian

  • 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

  • Trying to use a new, larger external hard drive for my Time Machine backup.  However, every time I start the backup, it gets started then fails.  And, I can't delete the few files that did save on the external.  Sort of a catch 22.  Any ideas?

    Trying to use a new, larger external hard drive for my Time Machine backup.  However, every time I start the backup, it gets started then fails.  And, I can't delete the few files that did save on the external.  Sort of a catch 22.  Any ideas?

    Is it a USB hard drive?  USB hard drives have the problem of not giving full speed if they are hooked up on the same bus as keyboards and mice.  Double check your profiler to make sure that is not a problem.  If it is Firewire, make sure there aren't other firewire devices in use at the same time.  I recommend not only keeping a Time Machine backup, but also a clone, and if you do use Time Machine, to make sure the Time Machine drive or partition is at least twice the size of the original drive.

  • How to use an Event Structure responding to an image control that belongs to a parent VI.

    Hi
    I am loading a subpanel vi by pressing a button located in the user interface of the main vi which also contains an image display. Subpanel vi opens up on the side and doesn't hide the image display of the main vi. Subpanel vi contains an event structure that needs to respond to user clicking on the image display of main vi.
    Since the bug that occured while creating an image reference control isn't fixed, I am passing the main vi pane reference onto the subpanel vi. From that point I've tried to edit event structure and have it respond to the image control/pane that belongs to main vi but I don't know how.
    Any help would be appreciated.
    Thanks

    Post a screenshot of your subVI code where you register the events.
    André
    Regards,
    André
    Using whatever version of LV the customer requires. (LV5.1-LV2012) (www.carya.nl)

  • On my Macbook pro 15 2011, System Profiler is suggesting that it uses SATA III for the hard drive and SATA II for the Optical Drive.  Is that true?

    On my Macbook pro 15, 2011, System Profiler is suggesting that it uses SATA III for the hard drive and SATA II for the Optical Drive.  Is that true?

    That is correct. The tech specs indicate:
    Hard Drive Interface
    6.0 Gbps Serial ATA (SATA)
    Optical Drive Interface
    3.0 or 6.0 Gbps Serial ATA (SATA)

  • If I already have an Airport Express Base Station, can i hook an external hard drive into it's USB port and use that hard drive with Time Machine?

    If I already have an Airport Express Base Station, can i hook an external hard drive into it's USB port and use that hard drive with Time Machine?

    No, and that shouldn't be done with an AirPort Extreme or Time Capsule.
    (66017)

  • I need to back up my imac running Tiger (no time machine) so that we can upgrade OS. It is set up for multiple accounts.  How do I capture all files in each account using newly purchased USB external hard drive?

    I need to back up my imac running Tiger (no time machine) so that we can upgrade OS. It is set up for multiple accounts.  How do I capture all files in each account using newly purchased USB external hard drive?  Thanks!

    Backup Software Recommendations
    Carbon Copy Cloner
    Data Backup
    Deja Vu
    SuperDuper!
    Synk Pro
    Tri-Backup
    Others may be found at VersionTracker or MacUpdate.
    Visit The XLab FAQs and read the FAQ on backup and restore.  Also read How to Back Up and Restore Your Files.
    Or you can simply use the Restore option of Disk Utility to clone the drive to the backup:
    Clone using Restore Option of Disk Utility
    Open Disk Utility from the Utilities folder.
    Select the destination volume from the left side list.
    Click on the Restore tab in the DU main window.
    Check the box labeled Erase destination.
    Select the destination volume from the left side list and drag it to the Destination entry field.
    Select the source volume from the left side list and drag it to the Source entry field.
    Double-check you got it right, then click on the Restore button.
    Destination means the external backup drive. Source means the internal startup drive.

  • What are main events in that are used in ALV reports

    hi gurus
    what are main events in that are used in ALV reports....
    regards
    baskar

    hi
    i think this will help u.
    Events in alv and their FM    The main events in alv and their FM and why we use these: 
    1. SLIS_PRINT_ALV. 
    2. SLIS_T_LISTHEADER. 
    3. SLIS_T_EVENT. 
    4. SLIS_T_SORTINFO_ALV. 
    5. SLIS_T_LAYOUT_ALV. 
    6. SLIS_T_FIELDCAT_ALV. 
    and in classic reports what is the sequence of events:   === Events are 
    At selection-screen output. 
    Initialization. 
    At selection-screen on field 
    At selection-screen on end of field 
    At selection-screen on Radiobutton Group R1. (If you have any radio buttons) 
    At selection-screen on block b1. (If you have any blocks) 
    Start-of-selection. 
    Get node. (if the data is retreived from a logical database) 
    Get node late. (if the data is retreived from a logical database) 
    Top-of-page. (if the write statement is in the end-of-selection event or we can say that before the first write statement) 
    end-of-selection. 
    and fuction modules are 
    LISTHEADER - Is used to print the header information in the ALV List. Name, Date, Time, ALV Name and other details are called as Header information.   EVENT - Basically this is the FM to handle Event's. When the user needs to do some event operation like when double clicking the a particular field we need to perform some operation.   These events are captured by this FM.   LAYOUT - This FM is used to define the layout of the List. There are many options available in this FM to define the Layout style.   FIELDCAT - These are used to populate the List header. We can change them according to our req. 
    User-defined Text Output Event
        Application
          print_end_of_list
        Define output text to be printed at the end of the entire list
          print_top_of_list
        Define output text to be printed at the beginning of the entire list
          print_end_of_page
        Define output text to be printed at the end of each page
          print_top_of_page
        Define output text to be printed at the beginning of each page
          subtotal_text
        Define self-defined subtotals texts
    Mouse-controlled Actions in the Grid Control Event
        Application
          button_click
        Query a click on a pushbutton in the ALV Grid Control
          double_click
        Query a double-click on a cell of the ALV Grid control 
          hotspot_click
        Query a hotspot click on columns defined for this purpose in advance
          onDrag
        Collect information when elements of the ALV Grid Control are dragged 
          onDrop
        Process information when elements of the ALV Grid Control are dropped 
          onDropComplete
        Perform final actions after successful Drag&Drop 
          onDropGetFlavor
        Distinguish between options for Drag&Drop behavior
    Processing of Self-defined and Standard Functions Event
        Application
          before_user_command
        Query self-defined and standard function codes
          user_command
        Query self-defined function codes
          after_user_command
        Query self-defined and standard function codes
    Definition of Self-defined Functions Event
        Application
          toolbar
        Change, delete or add GUI elements in the toolbar
          menu_button
        Define menus for menu buttons in the toolbar
          context_menu_request
        Change context menu
          onf1
        Define self-defined F1 help
    All of these can be found under type group SLIS.
    Events
    SLIS_EV_ITEM_DATA_EXPAND        TYPE SLIS_FORMNAME VALUE 'ITEM_DATA_EXPAND',
    SLIS_EV_REPREP_SEL_MODIFY       TYPE SLIS_FORMNAME VALUE 'REPREP_SEL_MODIFY', SLIS_EV_CALLER_EXIT_AT_START TYPE SLIS_FORMNAME VALUE 'CALLER_EXIT',
    SLIS_EV_USER_COMMAND              TYPE SLIS_FORMNAME VALUE 'USER_COMMAND',
    SLIS_EV_TOP_OF_PAGE                     TYPE SLIS_FORMNAME VALUE 'TOP_OF_PAGE',
    SLIS_EV_DATA_CHANGED                TYPE SLIS_FORMNAME VALUE 'DATA_CHANGED',
    SLIS_EV_TOP_OF_COVERPAGE       TYPE SLIS_FORMNAME VALUE 'TOP_OF_COVERPAGE',
    SLIS_EV_END_OF_COVERPAGE       TYPE SLIS_FORMNAME VALUE 'END_OF_COVERPAGE',
    SLIS_EV_FOREIGN_TOP_OF_PAGE TYPE SLIS_FORMNAME
    VALUE 'FOREIGN_TOP_OF_PAGE', SLIS_EV_FOREIGN_END_OF_PAGE TYPE SLIS_FORMNAME
    VALUE 'FOREIGN_END_OF_PAGE',
    SLIS_EV_PF_STATUS_SET                  TYPE SLIS_FORMNAME VALUE 'PF_STATUS_SET',
    SLIS_EV_LIST_MODIFY                      TYPE SLIS_FORMNAME VALUE 'LIST_MODIFY',
    SLIS_EV_TOP_OF_LIST                       TYPE SLIS_FORMNAME VALUE 'TOP_OF_LIST',
    SLIS_EV_END_OF_PAGE                    TYPE SLIS_FORMNAME VALUE 'END_OF_PAGE',
    SLIS_EV_END_OF_LIST                      TYPE SLIS_FORMNAME VALUE 'END_OF_LIST',
    SLIS_EV_AFTER_LINE_OUTPUT       TYPE SLIS_FORMNAME VALUE 'AFTER_LINE_OUTPUT', SLIS_EV_BEFORE_LINE_OUTPUT     TYPE SLIS_FORMNAME VALUE 'BEFORE_LINE_OUTPUT',
    SLIS_EV_SUBTOTAL_TEXT                TYPE SLIS_FORMNAME VALUE 'SUBTOTAL_TEXT'.
    with regards
    sravani
    award points if found useful.

  • There were no results for Hi there, I have been using gmail Id and that has been changed by someone into a hotmail apple id whenever I wanted to sign into my account. I am really really troubled a lot. I have also successfully created another apple ID and

    I have been using gmail Id and that has been changed by someone into a hotmail apple id whenever I wanted to sign into my account. I am really really troubled a lot. I have also successfully created another apple ID and password after a lengthy process and tried to go and get downloads, I was asked for my apple id and again the same problem came back and I couldn't be able to use my new account and use apple downloads from iTunes , etc. please, help me as soon as possible. Yimenu

    Apss are forever tied to the Apple ID under which they were originally purchased. If you forgot the password to your original Apple ID, you can retrive it here:
    https://iforgot.apple.com

Maybe you are looking for

  • How to make single column scrollable in ALV report (for long Text)

    I have a 20 columns which we need to display in ALV grid, including one column for long text. In long text column currently it showing 40 character. I tried to change output length of field catalog but it's not working. Can any one help me .... Thank

  • Help with SAT L305D will not boot up

    Satallite L305D-S5897 This morning I went to use my lap top and it will not load windows, goes into recovery screen or start normal. I have pressed F2,F8,F10,and F12 tried safe mode, safe mode with networking, and safe mode with command prompt all fa

  • Update trigger is not working...

    Hi I am writing an update trigger. We have a two DB, one is application DB and other is reporting DB. We are writing trigger on Reporting DB. There is a job schedule for synchronizing the application data to reporting DB , this daly basis synchroniza

  • Ii cant download netflix in my ipad.

    I cant download netflix on my ipad and i dont know why. Everytime i go to itunes and serch for it it doesen't apear and if i go to the netflix web page and press the link it takes me to the app store and the screen stays white forever and never charg

  • Getting xml webservices using soap on xcode

    there is some error in the code , i dont know how to correct it !! *frustated* #import "XYZViewController.h" @interface XYZViewController () @end @implementation XYZViewController @synthesize UserName,Password; #define startActivityIndicator  [[UIApp