Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 1 of 2 12 LastLast
Results 1 to 25 of 33

Thread: KeyListeners: Automatic Focus?

  1. #1
    Member
    Join Date
    Jun 2011
    Posts
    182
    My Mood
    Where
    Thanks
    15
    Thanked 8 Times in 8 Posts

    Default KeyListeners: Automatic Focus?

    There are three grids of buttons on my JFrame. Each of those grids has its own JPanel. Right now, the buttons are stored in ArrayLists and each one gets an actionListener and keyListener assigned to it through a for loop.

    My problem is that the keys don't register until you click one of the buttons. How can I make the keys have the focus for the entire JFrame regardless of which grid they are in?

    If you would like to see a certain portion of code, just specify which part and I will post it.


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: KeyListeners: Automatic Focus?

    Can't you just add the KeyListener to the JFrame? Or use KeyBindings instead?
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    Member
    Join Date
    Jun 2011
    Posts
    182
    My Mood
    Where
    Thanks
    15
    Thanked 8 Times in 8 Posts

    Default Re: KeyListeners: Automatic Focus?

    I need a way for pressed keys to make the same method (actionPerformed) fire with the correct value.

    Ideally, I want the buttons to actually be "pressed" by the key events.

    I don't know much about KeyBinding. I will look it up but you might have to help me out

  4. #4
    Member
    Join Date
    Jun 2011
    Posts
    182
    My Mood
    Where
    Thanks
    15
    Thanked 8 Times in 8 Posts

    Default Re: KeyListeners: Automatic Focus?

    Ok I read up some on KeyBindings on the API as well as in the Java Tutorials. However, I'm kind of confused on how to use ActionMaps?

    Here is an example from my code:
     
        for(int i=0;i<12;i++) {
          JButton b = new JButton();
          if(i == 0) {b.setText("7");}
          else if(i == 1) {b.setText("8");}
          else if(i == 2) {b.setText("9");}
          else if(i == 3) {b.setText("4");}
          else if(i == 4) {b.setText("5");}
          else if(i == 5) {b.setText("6");}
          else if(i == 6) {b.setText("1");}
          else if(i == 7) {b.setText("2");}
          else if(i == 8) {b.setText("3");}
          else if(i == 9) {b.setText("0");}
          else if(i == 10) {b.setText(".");b.setFont(spec);}
          else if(i == 11) {b.setText("-");b.setFont(spec);}
          if(i!=10&&i!=11) {b.setFont(jcfont);}
          mainButtonList.add(b);
          center.add(b);
          b.addActionListener(new ListenForMain());
        }

    The buttons are located in array lists. Their actionPerformed methods use getSource to find the source, find the reference in the ArrayList, get that object as a button, and get the text to identify the button for the rest of the program.

    How would I add KeyBindings to a situation like this with the ArrayList approach?

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: KeyListeners: Automatic Focus?

    A suggestion on your code. When I see regular code like you have I think array. Put the text for the buttons in an array in the order you want to index them:
    String[] btnTexts = new String[] {"7", "8", "9", "4", ...".", "-"};
    Then get the desired text:
    b.setText(btnTexts[i]); // get text for this button
    How would I add KeyBindings to a situation like this with the ArrayList approach?
    The key bindings would replace the addActionListener method call. The actionPerformed() method calls would be the same.

  6. #6
    Member
    Join Date
    Jun 2011
    Posts
    182
    My Mood
    Where
    Thanks
    15
    Thanked 8 Times in 8 Posts

    Default Re: KeyListeners: Automatic Focus?

    Quote Originally Posted by Norm View Post
    A suggestion on your code. When I see regular code like you have I think array. Put the text for the buttons in an array in the order you want to index them:
    String[] btnTexts = new String[] {"7", "8", "9", "4", ...".", "-"};
    Then get the desired text:
    b.setText(btnTexts[i]); // get text for this button

    The key bindings would replace the addActionListener method call. The actionPerformed() method calls would be the same.
    Erm.... Seeing as the amount of code that is in this program involving the ArrayLists I would rather not go back and completely change that unless you REALLY think there is no other way.

    Like I said, how do I add KeyBindings to a situation with the ArrayList approach?

    Oh and just out of curiosity, what exactly is "regular code"?

    EDIT: And by how I mean I don't understand ActionMaps. If you could help with that, I would appreciate it. Thanks!
    Last edited by bgroenks96; June 22nd, 2011 at 08:52 PM.

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: KeyListeners: Automatic Focus?

    I don't see what bearing the use of ArrayLists to hold references makes to whether you use key listeners vs key binding.
    what exactly is "regular code"?
    I guess repetative code would have been a better way to say it.

    Here's a sample of how to use keybindings:
            add(player1);
    //        player1.addKeyListener(this);
    //        player1.setFocusable( true );    //<<<< Need these for KeyListener, not for bindings!!!
    //        player1.requestFocus();
     
            // This will trigger call for Ctrl-Z
            addKeyAccelerator(this, new ActionButUp(), "ctrlZ", 'Z', Event.CTRL_MASK);
            // This for 'y' alone
            addKeyAccelerator(this, new ActionButUp(), "JustY", 'Y', 0);
     
        }
        //-----------------------------------------------------------
        private class ActionButUp extends  AbstractAction {
            public void actionPerformed(ActionEvent evt) {
                System.out.println("bound evt=" + evt);
            }
        }
     
        // For Key bindings
        private void addKeyAccelerator(JComponent c, AbstractAction act, String actionName, 
                                             int keyCode, int mask) {
            KeyStroke ks = KeyStroke.getKeyStroke(keyCode, mask);
            c.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ks, actionName);
            c.getActionMap().put(actionName, act); 
        }

    Try this in your program to see what happens.
    Last edited by Norm; June 23rd, 2011 at 09:04 AM. Reason: Invalid action names

  8. #8
    Member
    Join Date
    Jun 2011
    Posts
    182
    My Mood
    Where
    Thanks
    15
    Thanked 8 Times in 8 Posts

    Default Re: KeyListeners: Automatic Focus?

    Here is the class from my code that reads the button actions.
    [CODE]
      class ListenForMain extends AbstractAction implements ActionListener {
        public void actionPerformed(ActionEvent e) {
          Object userPressed = e.getSource();
          int i = mainButtonList.indexOf(userPressed);
          JButton b = mainButtonList.get(i);
          input = b.getText();
          String currentOutput = output.getText();   
          if(Mathematics.userNum == 0 && !currentOutput.equals("")) {
            output.setText(""); 
          }
          if(display.getText().equals(operator)||display.getText().equals(passive)||display.getText().equals("^")) {
            display.setText("");
            lastOp = true;
          } else {
            lastOp = false;
          }
          display.append(input);
        }
      }
    [/CODE]

    I am having trouble adding your example of KeyBindings to the program. If I want the same thing to happen with that key binding as when the buttons are pressed, can I just do this?
    [CODE]
    addKeyAccelerator(mainFrame, new ListenForMain(), "0",'0',0)
    //Is there a way to bind all of the NumPad numbers or something?  I'm lazy...
    public void addKeyAccelerator(JComponent c,AbstractAction action, String keyName, int keyCode, int mask) {
    //Rest of the method code...
    [/CODE]

    If I make the ListenForMain method extend AbstractAction will it work with KeyBindings?

    And what do I need to add to the actionPerformed method in ListenForMain?

    Does the addKeyAccelerator method need to have something like this?
    [CODE]
    //this is the rest of the method code...
    KeyStroke ks = KeyStroke.getKeyStroke(keyCode,mask);
    //Here I want the buttons to respond to the key stroke.  If this is wrong and it needs to use the same "c" reference or the "JButton" class name, let me know.
    c.getInputMap(b.WHEN_IN_FOCUSED_WINDOW).put(ks,actionName);
    c.getActionMap().put(actionName, action);
    [/CODE]

    Additional:
    And I am getting an error that this:
    addKeyAccelerator(mainFrame, new ListenForMain(), "0", 0,0);
    cannot be applied to this:
    private void addKeyAccelerator(JComponent c, AbstractAction act, String actionName, int keyCode, int mask) {

    I'm not sure why...
    Scratch that. I just realized that JFrame doesn't extend JComponent.
    Last edited by bgroenks96; June 23rd, 2011 at 12:04 PM. Reason: Adding information + highlights

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: KeyListeners: Automatic Focus?

    I am having trouble adding your example of KeyBindings to the program.
    What I posted was for a quick and easy demo. I was hoping that you could copy and paste it as is.
    Then test it by executing your code and pressing Ctrl-Z or the Y and have a message printed.
    Did you try that? Did it print out?

    can I just do this?
    Try it and see what happens.
    If I make the ListenForMain method extend AbstractAction will it work with KeyBindings?
    Try it and see.

  10. #10
    Member
    Join Date
    Jun 2011
    Posts
    182
    My Mood
    Where
    Thanks
    15
    Thanked 8 Times in 8 Posts

    Default Re: KeyListeners: Automatic Focus?

    Quote Originally Posted by Norm View Post
    What I posted was for a quick and easy demo. I was hoping that you could copy and paste it as is.
    Then test it by executing your code and pressing Ctrl-Z or the Y and have a message printed.
    Did you try that? Did it print out?


    Try it and see what happens.

    Try it and see.
    No doesn't work. I'm pretty sure I need something in the actionPerformed method to process the key event. But I don't know what.

    And do you mean copy it into my current program as is? There is no "player1" reference existing inside of it...

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: KeyListeners: Automatic Focus?

    No doesn't work.
    Sorry, there are so many ways for a program to "not work" that I have no idea what the problem is.

    Sorry, I meant to say: Replace "player1" with a component in your code that is being displayed.

  12. #12
    Member
    Join Date
    Jun 2011
    Posts
    182
    My Mood
    Where
    Thanks
    15
    Thanked 8 Times in 8 Posts

    Default Re: KeyListeners: Automatic Focus?

    Quote Originally Posted by Norm View Post
    What I posted was for a quick and easy demo. I was hoping that you could copy and paste it as is.
    Then test it by executing your code and pressing Ctrl-Z or the Y and have a message printed.
    Did you try that? Did it print out?


    Try it and see what happens.

    Try it and see.
    Do you mean copy it into my program? Some of those variables don't exist in it... I'm not sure now that would work.

    And I have tried those things. They don't work. I'm pretty sure I need something added to those actionPerformed methods in order for them to recognize the KeyStrokes.

    I just don't know what....

    And was my addKeyAccelerator correct?

  13. #13
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: KeyListeners: Automatic Focus?

    ome of those variables don't exist
    I thought that player1 was the only one. The add(player1); line should be commented out as are the ones underneath it.
    addKeyAccelerator(this
    The "this" refers to the JPanel that the code is in.

  14. #14
    Member
    Join Date
    Jun 2011
    Posts
    182
    My Mood
    Where
    Thanks
    15
    Thanked 8 Times in 8 Posts

    Default Re: KeyListeners: Automatic Focus?

    Quote Originally Posted by Norm View Post
    I thought that player1 was the only one. The add(player1); line should be commented out as are the ones underneath it.

    The "this" refers to the JPanel that the code is in.
    Sorry double posted there. Didn't even see your posts.... the thread glitched.

    I don't want to frustrate you, but I think I'm missing your point.

    To clarify, I have action listeners for two JPanels containing grids of buttons. That works perfectly. I just need keys to execute the same actionPerformed method the buttons do.

    I got how to add the key accelerator, make the method and identify the key strokes. But, how do I integrate the key binding into the buttons' action performed method?

    Also, for the sake of being lazy, is there any way to bind the whole numpad in one statement or do i have to go through and do each individually?

  15. #15
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: KeyListeners: Automatic Focus?

    If you use key bindings you may be able to bind the key events to the container that all the components are in.
    how do I integrate the key binding into the buttons' action performed method?
    The key binding's actionPerformed method could call the actionPerformed method used by the buttons.
    Or the key binding's AbstractAction could be the same actionPerformed method as the one the buttons use.

    Can you make a small simple program that compiles and executes with a few buttons in a panel to demonstrate this problem?

  16. #16
    Member
    Join Date
    Jun 2011
    Posts
    182
    My Mood
    Where
    Thanks
    15
    Thanked 8 Times in 8 Posts

    Default Re: KeyListeners: Automatic Focus?

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
     
    class KeyTime {
      ArrayList<JButton> buttons;
      JFrame frame;
      JPanel panel;
      JPanel buttonPanel;
      JTextArea main;
      public void setUpWindow() {
        frame = new JFrame("Key Problem Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        panel = new JPanel();
        main = new JTextArea(50,70);
        panel.add(main);
        buttonPanel = new JPanel();
        buttons = new ArrayList<JButton>();
        for(int i=0;i<2;i++) {
          JButton b = new JButton();
          if(i==0) {b.setText("Click me!");}
          else if(i==1) {b.setText("Me too!");}
          b.addActionListener(new ListenForButtons());
          buttons.add(b);
          buttonPanel.add(b);
        }
        addKeyAccelerator(buttonPanel, new ListenForButtons(),"action",0,0);
        frame.getContentPane().add(BorderLayout.SOUTH, buttonPanel);
        frame.add(BorderLayout.CENTER, panel);
        frame.setBounds(30,30,500,500);
        frame.pack();
        frame.setVisible(true);
      }
      public void addKeyAccelerator(JComponent c, AbstractAction act, String name, int keyCode, int mask) {
        KeyStroke key = KeyStroke.getKeyStroke(keyCode, mask);
        c.getInputMap(buttons.get(0).WHEN_IN_FOCUSED_WINDOW).put(key,name);
        c.getActionMap().put(name,act);
      }
      public static void main(String[] args) {
        KeyTime kt = new KeyTime();
        kt.setUpWindow();
      }
      class ListenForButtons extends AbstractAction implements ActionListener {
        public void actionPerformed(ActionEvent e) {
          Object userPressed = e.getSource();
          int i = buttons.indexOf(userPressed);
          JButton b = buttons.get(i);
          String line = b.getText();
          if(line.equals("Click me!")) {
            main.setText("");
            main.append("Both buttons call the same actionPerformed method.  \n That method determines which button was pressed.");
            main.append("\n Only the 'Click Me!' button should respond to the key stroke of the number '0'");
          } else if(line.equals("Me too!")) {
            main.setText("");
            main.append("Unfortunately neither respond.");
            main.append("\n Does this actionPerformed method need a way to receive the key stroke perhaps?");
          }
        }
      }
    }

    Will this suffice?

  17. #17
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: KeyListeners: Automatic Focus?

    How is it supposed to work? What key presses are supposed to do what?

    Here's my version that will react when the 'a' key is pressed.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
     
    class KeyTime              {
      ArrayList<JButton> buttons;
      JFrame frame;
      JPanel panel;
      JPanel buttonPanel;
      JTextArea main;
     
      public void setUpWindow() {
        frame = new JFrame("Key Problem Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        panel = new JPanel();
        main = new JTextArea(20,70);
        main.setEditable(false); //<<<<<<< To keep from getting focus
        panel.add(main);         //<<<<<<<<<<<<<<<<< THIS GETS the focus!!!
     
        buttonPanel = new JPanel();
        buttons = new ArrayList<JButton>();
     
        for(int i=0;i<2;i++) {
          JButton b = new JButton();
          if(i==0) {b.setText("Click me!");}
          else if(i==1) {b.setText("Me too!");}
     
          b.addActionListener(new ListenForButtons());
          buttons.add(b);
          buttonPanel.add(b);
        }
     
        // Call listener when the a key is pressed
        addKeyAccelerator(buttonPanel, new ListenForButtons(), "action", 'A', 0);
     
        frame.getContentPane().add(BorderLayout.SOUTH, buttonPanel);
        frame.add(BorderLayout.CENTER, panel);
        frame.setBounds(30,30,500,300);
        frame.pack();
        frame.setVisible(true);
      }
     
     
      public void addKeyAccelerator(JComponent c, AbstractAction act, String name, int keyCode, int mask) {
        KeyStroke key = KeyStroke.getKeyStroke(keyCode, mask);
        c.getInputMap(buttons.get(0).WHEN_IN_FOCUSED_WINDOW).put(key,name);
        c.getActionMap().put(name,act);
      }
      public static void main(String[] args) {
        KeyTime kt = new KeyTime();
        kt.setUpWindow();
      }
     
      //----------------------------------------------------------------------------
      class ListenForButtons extends AbstractAction implements ActionListener {
        public void actionPerformed(ActionEvent e) {
          System.out.println("aP e=" + e);  // aP e=java.awt.event.ActionEvent[ACTION_PERFORMED,cmd=a,w...
          Object userPressed = e.getSource();
          System.out.println("uP=" + userPressed); // uP=javax.swing.JPanel[,0,330,780x36,layout=java.awt.FlowLayout,alignmentX=0.0,a
          int i = buttons.indexOf(userPressed);
          System.out.println("i=" + i); // i=-1
     
          JButton b = buttons.get(i);
          String line = b.getText();
          if(line.equals("Click me!")) {
            main.setText("");
            main.append("Both buttons call the same actionPerformed method.  \n That method determines which button was pressed.");
            main.append("\n Only the 'Click Me!' button should respond to the key stroke of the number '0'");
          } else if(line.equals("Me too!")) {
            main.setText("");
            main.append("Unfortunately neither respond.");
            main.append("\n Does this actionPerformed method need a way to receive the key stroke perhaps?");
          }
        }
      }
    }
    Last edited by Norm; June 23rd, 2011 at 09:15 PM.

  18. #18
    Member
    Join Date
    Jun 2011
    Posts
    182
    My Mood
    Where
    Thanks
    15
    Thanked 8 Times in 8 Posts

    Default Re: KeyListeners: Automatic Focus?

    The program you wrote throws this exception at runtime (it's an Array Index out of bounds):
    Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException:
     -1
            at java.util.ArrayList.get(ArrayList.java:324)
            at KeyTime$ListenForButtons.actionPerformed(KeyTime.java:64)
            at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1639)
            at javax.swing.JComponent.processKeyBinding(JComponent.java:2851)
            at javax.swing.KeyboardManager.fireBinding(KeyboardManager.java:267)
            at javax.swing.KeyboardManager.fireKeyboardAction(KeyboardManager.java:2
    16)
            at javax.swing.JComponent.processKeyBindingsForAllComponents(JComponent.
    java:2928)
            at javax.swing.JComponent.processKeyBindings(JComponent.java:2920)
            at javax.swing.JComponent.processKeyEvent(JComponent.java:2814)
            at java.awt.Component.processEvent(Component.java:6065)
            at java.awt.Container.processEvent(Container.java:2041)
            at java.awt.Component.dispatchEventImpl(Component.java:4651)
            at java.awt.Container.dispatchEventImpl(Container.java:2099)
            at java.awt.Component.dispatchEvent(Component.java:4481)
            at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.ja
    va:1850)
            at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboard
    FocusManager.java:712)
            at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeybo
    ardFocusManager.java:990)
            at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeybo
    ardFocusManager.java:855)
            at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFoc
    usManager.java:676)
            at java.awt.Component.dispatchEventImpl(Component.java:4523)
            at java.awt.Container.dispatchEventImpl(Container.java:2099)
            at java.awt.Window.dispatchEventImpl(Window.java:2478)
            at java.awt.Component.dispatchEvent(Component.java:4481)
            at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:643)
            at java.awt.EventQueue.access$000(EventQueue.java:84)
            at java.awt.EventQueue$1.run(EventQueue.java:602)
            at java.awt.EventQueue$1.run(EventQueue.java:600)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessCo
    ntrolContext.java:87)
            at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessCo
    ntrolContext.java:98)
            at java.awt.EventQueue$2.run(EventQueue.java:616)
            at java.awt.EventQueue$2.run(EventQueue.java:614)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessCo
    ntrolContext.java:87)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:613)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThre
    ad.java:269)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.
    java:184)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
    ad.java:174)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
     
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
     
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

    What did you do? That didn't happen in my version...

    And to answer your question, the program was supposed to activate the "Click Me!" button when 0 is pressed. Click Me! and Me too! display different messages.

  19. #19
    Member
    Join Date
    Jun 2011
    Posts
    182
    My Mood
    Where
    Thanks
    15
    Thanked 8 Times in 8 Posts

    Default Re: KeyListeners: Automatic Focus?

    What if I had key listeners instead of bindings that performed the doClick method on their respective buttons?

  20. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: KeyListeners: Automatic Focus?

    Ok. There were no comments in the code, so all I could do was have the key press go to the action listener. I didn't know what to do then. The listener needs to recognize how it was called (button click or key press) and react accordingly. Right now it assumes that it is ONLY called by button press. It doesn't know what to do when called with the key press.

  21. #21
    Member
    Join Date
    Jun 2011
    Posts
    182
    My Mood
    Where
    Thanks
    15
    Thanked 8 Times in 8 Posts

    Default Re: KeyListeners: Automatic Focus?

    Quote Originally Posted by Norm View Post
    Ok. There were no comments in the code, so all I could do was have the key press go to the action listener. I didn't know what to do then. The listener needs to recognize how it was called (button click or key press) and react accordingly. Right now it assumes that it is ONLY called by button press. It doesn't know what to do when called with the key press.
    Would it maybe be easier to have separate key listeners in the main frame that respond by calling the doClick method on their respective buttons? That would fire the actionPerformed method right?

    (Btw I'm not in any class I'm doing Java on my own so you aren't doing my homework by giving me answers )

  22. #22
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: KeyListeners: Automatic Focus?

    Here's another version:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
     
    @SuppressWarnings("serial")
     
     
    public class KeyTime              {
      ArrayList<JButton> buttons;
      JFrame frame;
      JPanel panel;
      JPanel buttonPanel;
      JTextArea main;
     
      public void setUpWindow() {
        frame = new JFrame("Key Problem Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        panel = new JPanel();
        main = new JTextArea(20,70);
        main.setEditable(false); //<<<<<<< To keep from getting focus
        panel.add(main);         //<<<<<<<<<<<<<<<<< THIS GETS the focus!!!
     
        buttonPanel = new JPanel();
        buttons = new ArrayList<JButton>();
     
        ListenForButtons lfb = new ListenForButtons();
     
        for(int i=0;i<2;i++) {
          JButton b = new JButton();
          if(i==0) {b.setText("Click me!");}
          else if(i==1) {b.setText("Me too!");}
     
          b.addActionListener(lfb);
          buttons.add(b);
          buttonPanel.add(b);
        }
     
        // Call listener when the '0' key is pressed
        DoBtnClick dbc = new DoBtnClick(buttons.get(0));
        addKeyAccelerator(buttonPanel, dbc, "action", '0', 0);
        addKeyAccelerator(buttonPanel, dbc, "action", KeyEvent.VK_NUMPAD0, 0);   // Number pad is different
     
        frame.getContentPane().add(BorderLayout.SOUTH, buttonPanel);
        frame.add(BorderLayout.CENTER, panel);
        frame.setBounds(30,30,500,300);
        frame.pack();
        frame.setVisible(true);
      }
     
      // Class to click button when a key is pressed
      private class DoBtnClick extends  AbstractAction {
         JButton btn;
         public DoBtnClick(JButton btn) {
             this.btn = btn;    // Save the button we're to click
         }
         public void actionPerformed(ActionEvent evt) {
             System.out.println("bound evt=" + evt);
             btn.doClick();
         }
      } // end class DoBtnClick
     
     
      public void addKeyAccelerator(JComponent c, AbstractAction act, String name, int keyCode, int mask) {
        KeyStroke key = KeyStroke.getKeyStroke(keyCode, mask);
        c.getInputMap(buttons.get(0).WHEN_IN_FOCUSED_WINDOW).put(key,name);
        c.getActionMap().put(name,act);
      }
     
      //---------------------------------------
      public static void main(String[] args) {
        KeyTime kt = new KeyTime();
        kt.setUpWindow();
      }
     
      //----------------------------------------------------------------------------
      class ListenForButtons extends AbstractAction implements ActionListener {
        public void actionPerformed(ActionEvent e) {
          System.out.println("aP e=" + e);  
    //aP e=java.awt.event.ActionEvent[ACTION_PERFORMED,cmd=0,when=1308913543812,modifiers=] on javax.swing.JPanel[,0,330,780x36,layout=java.awt.FlowLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=393,maximumSize=,minimumSize=,preferredSize=]
     
          Object userPressed = e.getSource();
          System.out.println("uP=" + userPressed); // uP=javax.swing.JPanel[,0,330,780x36,layout=java.awt.FlowLayout,alignmentX=0.0,a
           int i = buttons.indexOf(userPressed);
           System.out.println("i=" + i); // i=-1
     
           JButton b = buttons.get(i);
           String line = b.getText();
     
          if(line.equals("Click me!")) {
            main.setText("");
            main.append("Both buttons call the same actionPerformed method.  \n That method determines which button was pressed.");
            main.append("\n Only the 'Click Me!' button should respond to the key stroke of the number '0'");
          } else if(line.equals("Me too!")) {
            main.setText("");
            main.append("Unfortunately neither respond.");
            main.append("\n Does this actionPerformed method need a way to receive the key stroke perhaps?");
          }
        }
      }
    }

  23. #23
    Member
    Join Date
    Jun 2011
    Posts
    182
    My Mood
    Where
    Thanks
    15
    Thanked 8 Times in 8 Posts

    Default Re: KeyListeners: Automatic Focus?

    <Double-Post>
    Last edited by bgroenks96; June 24th, 2011 at 11:10 AM. Reason: Double-post (accidental!)

  24. #24
    Member
    Join Date
    Jun 2011
    Posts
    182
    My Mood
    Where
    Thanks
    15
    Thanked 8 Times in 8 Posts

    Default Re: KeyListeners: Automatic Focus?

    Interesting idea with the KeyAccelerator calling the action class.... although I'm not sure if it will work in my program.

    I need to be able to identify the key pressed ahead of time in order to select which button to click. I've been testing using keyListeners assigned to the JFrame but haven't had any luck yet.

    If the keyListener is assigned to the JFrame, all sub components should recognize the action correct?

  25. #25
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: KeyListeners: Automatic Focus?

    I need to be able to identify the key pressed ahead of time
    Before when?
    Are you looking at my post #22?

Page 1 of 2 12 LastLast

Similar Threads

  1. Replies: 0
    Last Post: December 26th, 2010, 10:15 AM
  2. Maintain focus on JFrame
    By nik_meback in forum AWT / Java Swing
    Replies: 1
    Last Post: December 15th, 2010, 08:49 AM
  3. [SOLVED] JTextPane focus problem
    By LeonLanford in forum AWT / Java Swing
    Replies: 3
    Last Post: June 21st, 2010, 11:50 PM
  4. switch focus to another window
    By tuansoibk in forum AWT / Java Swing
    Replies: 1
    Last Post: November 13th, 2009, 02:02 PM
  5. Automatic correction of brightness and contrast
    By Mirko in forum Java Theory & Questions
    Replies: 1
    Last Post: September 16th, 2009, 06:26 PM