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.

Results 1 to 10 of 10

Thread: Need help to map KeyStrokes in ActionMap using CardLayout in a JApplet

  1. #1
    Junior Member
    Join Date
    Jan 2014
    Location
    Uganda
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Need help to map KeyStrokes in ActionMap using CardLayout in a JApplet

    Hi guys. Thanks for your time. Can someone please give a code that maps arrow key KeyStrokes of an ActionMap in AnyClass which extends a JPanel the arrow keys moves a ball in AnyClass

    AnyClass is called in a CardLayoutClass and CardLayoutClass is called in a JApplet.

    I am sorry I cannot post the code because the system says it is my first post and something to do with spam.

    Thanks again for your time

    Ruth Bugembe


  2. #2
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: Need help to map KeyStrokes in ActionMap using CardLayout in a JApplet

    Quote Originally Posted by bugemberuth View Post
    Can someone please give a code that maps arrow key KeyStrokes of an ActionMap in AnyClass which extends a JPanel the arrow keys moves a ball in AnyClass
    Just one question: why do you need to go at the deep level of input/action maps? What's wrong with a basical KeyListener?
    Andrea, www.andbin.netSCJP 5 (91%) – SCWCD 5 (94%)

    Useful links for Java beginnersMy new project Java Examples on Google Code

  3. #3
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Need help to map KeyStrokes in ActionMap using CardLayout in a JApplet

    Welcome to the forum! Please read this topic to learn how to post code in code or highlight tags and other useful info for newcomers.

  4. #4
    Junior Member
    Join Date
    Jan 2014
    Location
    Uganda
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need help to map KeyStrokes in ActionMap using CardLayout in a JApplet

    Thank you andbin thanks for ur time but am no gui expert. I read some where that KeyListener are wore difficult to manage. I need to use the arrow keys in a game I am hosting at Home as an alternative to pressing the buttons. Below is the code that tries to explain what I want to do but failing

    package keymapingincardlayout;
     
    import java.applet.Applet;
     
    import java.awt.BorderLayout;
    import java.lang.reflect.InvocationTargetException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    /**
     *
     * @author Administrator
     */
    @SuppressWarnings("serial")
    public class AppletClass extends javax.swing.JApplet{
     
        static CardlayoutClass cardLayoutClass; 
     
    	@Override
       @SuppressWarnings("static-access")
    	public void init(){
               resize(900, 550); 
                 cardLayoutClass = new CardlayoutClass();
     
           try {
                java.awt.EventQueue.invokeAndWait(new Runnable() {
                        @Override
                        public void run(){
                            getContentPane().add(cardLayoutClass.getMainPanel(), BorderLayout.CENTER);
                            cardLayoutClass.showAnyClass();                      
                        }
                });
            } catch (InterruptedException | InvocationTargetException ex) {
                //<editor-fold defaultstate="collapsed" desc="comment">
     
                //</editor-fold>
             Logger.getLogger(AppletClass.class.getName()).log(Level.SEVERE, null, ex);
            }
         }
    }
     
     
    package keymapingincardlayout;
     
    import java.awt.CardLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import javax.swing.JPanel;
     
    /**
     Calls AnyClass
     */
    class CardlayoutClass {
        static JPanel mainPanel;
        private static JPanel anyClassPanel;
     
        private static AnyClass anyClass;
        private static CardLayout cardLayout = new CardLayout();
        CardlayoutClass()
        {
            mainPanel = new JPanel();
     
            mainPanel.setLayout(cardLayout);
            mainPanel.setPreferredSize(new Dimension(900,550));
            mainPanel.setBackground(Color.blue);       
        }
        /*
         * called by the AppletClass
         */
         public static void showAnyClass()
        {
            anyClassPanel  = new JPanel();
            anyClassPanel.setPreferredSize(new Dimension(500, 500));
     
            anyClass = new AnyClass();           
            anyClassPanel.add(anyClass);
     
            mainPanel.add(anyClassPanel, "anyClas");
            cardLayout.show(mainPanel, "anyClass");
     
            anyClassPanel.setFocusable(true);
            anyClassPanel.requestFocusInWindow();
     
        } 
        /*
         * called by the AppletClass
         */
         public static JPanel getMainPanel()
         {
             return mainPanel;
         }       
    }
     
     
    package keymapingincardlayout;
     
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.AbstractAction;
    import javax.swing.ActionMap;
    import javax.swing.InputMap;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JPanel;
    import javax.swing.KeyStroke;
     
    /**
    Calls Ball
     */
    class AnyClass extends JPanel{
        static  InputMap inputMap;
        static ActionMap actionMap;
        static Ball ball;   
     
        AnyClass()
        {
            setPreferredSize(new Dimension(500, 500));
            setLayout(new FlowLayout(FlowLayout.CENTER));
            setBackground(Color.red);
            createBall();
     
            inputMap = getInputMap();
            actionMap = getActionMap();
            mapKeysToBall();
            setActionMap(actionMap);
            setInputMap(JComponent.WHEN_FOCUSED, inputMap);      
        }
     
          public void paintComponent(Graphics g) {
     
                super.paintComponent(g);          
                ball.drawMyBall(g);                  
            }
          private void createBall() {          
            ball = new Ball(240, 240, 50, 50); 
        } 
     
    //Moves myBall to the right
        public void turnRight() {
            ball.moveRight();
            repaint();
        }
     
        //Moves myBall to the left
        public void turnLeft() {
            ball.moveLeft();
            repaint();
        }
     
        //Moves myBall down
        public void turnSouth() {
            ball.moveDown();
            repaint();
        }
     
        //Moves myBall up
        public void turnNorth() {
            ball.moveUp();
            repaint();
        }
     
        void mapKeysToBall()
        {
            System.out.println("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
            inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "moveright");      	                                          
            actionMap.put("moveright", rightAction);
     
            System.out.println("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
            inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "moveLeft");      	                                           
            actionMap.put("moveLeft", leftAction);
     
            System.out.println("ccccccccccccccccccccccccccccccccccc");
            inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "moveUp");      	                                          
            actionMap.put("moveUp", upAction);
            System.out.println("dddddddddddddddddddddddddddddddddddddddd");
            inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "moveDown");      	                                         
            actionMap.put("moveDown", downAction);
            System.out.println("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
            //setActionMap(actionMap);
            System.out.println("fffffffffffffffffffffffffffffff");
     
        }
          private AbstractAction rightAction = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("111111111111111111111111111111111111");
                turnRight();
     
            }
            }; 
     
           private AbstractAction leftAction = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("22222222222222222222222222222222222222222");
              turnLeft();
            }
            };
     
           private AbstractAction upAction = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("333333333333333333333333333333333333333333");
                turnNorth();
            }
            };
     
           private AbstractAction downAction = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("4444444444444444444444444444");
                turnSouth();
            }
            };   
     
    }
     
     
    package keymapingincardlayout;
     
    import java.awt.Color;
    import java.awt.Graphics;
    import javax.swing.JPanel;
     
    class Ball  extends JPanel{
        int myX;
        static int myY;
        static int xDiameter;
        static int yDiameter;
        static int step;
     
        Ball(int x, int y, int xdmtr, int ydmtr)
        {
            myX = x;
            myY = y;
            xDiameter = xdmtr;
            yDiameter = ydmtr; 
             step = 14;        
        }
     
        /*
         *Moves the player's ball left
         */
        public void moveLeft()
        {
            myX -= step;
        }
     
        /*
         *Moves the player's ball right
         */
        public void moveRight() 
        {
            myX += step;
        }
     
        /*
         *moves the player's ball up
         */
        public void moveUp()
        {
            myY -= step;
        } 
        /*
         *Moves the player's ball down
         */
        public void moveDown() 
        {
            myY += step;
        }
        public void drawMyBall(Graphics g) {
            g.setColor(Color.white);
            g.fillOval(myX, myY, xDiameter, yDiameter);
     
        }
       }

  5. #5
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: Need help to map KeyStrokes in ActionMap using CardLayout in a JApplet

    Quote Originally Posted by bugemberuth View Post
    Below is the code that tries to explain what I want to do but failing
    In your code, movements works (not all correctly, review the code), but you have to give manually the focus. With your code I need to use the TAB key to reach the focusable panel.

    This is because you have done:

    anyClassPanel.requestFocusInWindow();

    while you should do

    anyClass.requestFocusInWindow();

    And apart this, your code is very "smoky", twisted and full of mistakes and inappropriate things. You have used many class (static) variables, which are not appropriate in your case. Then it's not necessary that Ball extends JPanel (you are not using Ball as a "component").
    The use of input/action maps give, as result, a more long and complex code. More long than using a simple KeyListener.
    And there are other bad/inappropriate things that I don't mention now just to avoid a long post .....
    Andrea, www.andbin.netSCJP 5 (91%) – SCWCD 5 (94%)

    Useful links for Java beginnersMy new project Java Examples on Google Code

  6. #6
    Junior Member
    Join Date
    Jan 2014
    Location
    Uganda
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need help to map KeyStrokes in ActionMap using CardLayout in a JApplet

    Hi andbin

    Thank you very much. The code I sent you has worked. Thanks for your time. Ido not know when I transfer it to my project it does not work. I am going to try find out what is wrong. as for KeyListener, I am going to look at it. Gui is new to me

    Ruth

  7. #7
    Junior Member
    Join Date
    Jan 2014
    Location
    Uganda
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need help to map KeyStrokes in ActionMap using CardLayout in a JApplet

    Hi Andrea

    I appreciate the help you have so far given me but I have failed to work my way round about this problem. As stated above the code you gave me works fine. but when I Incorporated it in my project it failes. i believe this has something to do with calling the CardLayoutClass is called more than once. In my project it is called 4 times before the Maze (AnyClass) is displayed. Below is the new code I have put MiddleClass which calls AnyClass. I need to take time to study the KeyListener I am using static variables because I am doing alot of class referencing guess due bad project design

     
    package keymapingincardlayout;
     
    import java.applet.Applet;
     
    import java.awt.BorderLayout;
    import java.lang.reflect.InvocationTargetException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    /**
     *
     * @author Administrator
     */
    @SuppressWarnings("serial")
    public class AppletClass extends javax.swing.JApplet{
     
        static CardlayoutClass cardLayoutClass; 
     
    	@Override
       @SuppressWarnings("static-access")
    	public void init(){
               resize(900, 550); 
                 cardLayoutClass = new CardlayoutClass();
     
           try {
                java.awt.EventQueue.invokeAndWait(new Runnable() {
                        @Override
                        public void run(){
                            getContentPane().add(cardLayoutClass.getMainPanel(), BorderLayout.CENTER);
                            cardLayoutClass.showMiddleClass();
                            //cardLayoutClass.showAnyClass(); 
                        }
                });
            } catch (InterruptedException | InvocationTargetException ex) {
                //<editor-fold defaultstate="collapsed" desc="comment">
     
                //</editor-fold>
             Logger.getLogger(AppletClass.class.getName()).log(Level.SEVERE, null, ex);
            }
         }
    }
     
    package keymapingincardlayout;
     
    import java.awt.CardLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import javax.swing.JPanel;
     
    /**
     Calls AnyClass
     */
    class CardlayoutClass {
        static JPanel mainPanel;
        private static JPanel middleClassPanel;
        private static JPanel anyClassPanel;
     
        private static MiddleClass middleClass;
        private static AnyClass anyClass;
        private static CardLayout cardLayout = new CardLayout();
        CardlayoutClass()
        {
            mainPanel = new JPanel();
            mainPanel.setLayout(cardLayout);
            anyClassPanel  = new JPanel();
            middleClassPanel  = new JPanel();
     
            mainPanel.add(middleClassPanel, "middle");
     
     
            mainPanel.setPreferredSize(new Dimension(900,550));
            mainPanel.setBackground(Color.blue);       
        }
        /*
         * called by the AppletClass
         */
         public static void showAnyClass()
        {
            anyClassPanel  = new JPanel();
           anyClassPanel.setPreferredSize(new Dimension(500, 500)); 
           anyClass = new AnyClass();
           anyClassPanel.add(anyClass); 
     
            mainPanel.add(anyClassPanel, "startClass");
            cardLayout.show(mainPanel, "startClass");      
     
        } 
     
         public static void showMiddleClass()
        {
            middleClassPanel.setPreferredSize(new Dimension(500, 500));
     
            middleClass = new MiddleClass();;       
            middleClassPanel.add(middleClass);
     
     
            cardLayout.show(mainPanel, "middle");
            System.out.println("MiddleClass");
     
        }     
        /*
         * called by the AppletClass
         */
         public static JPanel getMainPanel()
         {
             return mainPanel;
         }       
    }
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JPanel;
     
    /**
     *
     * @author Administrator
     */
    class MiddleClass extends JPanel{
       private static JButton callsAnyClass;
        MiddleClass()
        {
            setPreferredSize(new Dimension(500, 500));
            setLayout(new FlowLayout(FlowLayout.CENTER));       
            setBackground(Color.green);
            add(createCallsAnyClass());
        }
     
        private static JButton createCallsAnyClass()
        {
           callsAnyClass = new JButton("Call AnyClass");
     
           callsAnyClass.setForeground(Color.red);
           callsAnyClass.setBackground(Color.white);
          callsAnyClass.setFont(new Font("sansserif", Font.BOLD, 42));
     
          callsAnyClass.addActionListener(new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
             System.out.println("??????????????????????????");
             CardlayoutClass.showAnyClass(); 
          }
      });
      return callsAnyClass;
     
      }
     
    }
     
     
    package keymapingincardlayout;
     
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.AbstractAction;
    import javax.swing.ActionMap;
    import javax.swing.InputMap;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JPanel;
    import javax.swing.KeyStroke;
     
    /**
    Calls Ball
     */
    class AnyClass extends JPanel{
        static  InputMap inputMap;
        static ActionMap actionMap;
        static Ball ball;   
     
        AnyClass()
        {
            setPreferredSize(new Dimension(500, 500));
            setLayout(new FlowLayout(FlowLayout.CENTER));
            setBackground(Color.red);
            createBall();
     
            inputMap = getInputMap();
            actionMap = getActionMap();
            mapKeysToBall();
            setActionMap(actionMap);
            setInputMap(JComponent.WHEN_FOCUSED, inputMap);      
        }
     
          public void paintComponent(Graphics g) {
     
                super.paintComponent(g);          
                ball.drawMyBall(g);                  
            }
          private void createBall() {          
            ball = new Ball(240, 240, 50, 50); 
        } 
     
    //Moves myBall to the right
        public void turnRight() {
            ball.moveRight();
            repaint();
        }
     
        //Moves myBall to the left
        public void turnLeft() {
            ball.moveLeft();
            repaint();
        }
     
        //Moves myBall down
        public void turnSouth() {
            ball.moveDown();
            repaint();
        }
     
        //Moves myBall up
        public void turnNorth() {
            ball.moveUp();
            repaint();
        }
     
        void mapKeysToBall()
        {
            System.out.println("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
            inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "moveright");      	                                          
            actionMap.put("moveright", rightAction);
     
            System.out.println("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
            inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "moveLeft");      	                                           
            actionMap.put("moveLeft", leftAction);
     
            System.out.println("ccccccccccccccccccccccccccccccccccc");
            inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "moveUp");      	                                          
            actionMap.put("moveUp", upAction);
            System.out.println("dddddddddddddddddddddddddddddddddddddddd");
            inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "moveDown");      	                                         
            actionMap.put("moveDown", downAction);
            System.out.println("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
            //setActionMap(actionMap);
            System.out.println("fffffffffffffffffffffffffffffff");
     
        }
          private AbstractAction rightAction = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("111111111111111111111111111111111111");
                turnRight();
     
            }
            }; 
     
           private AbstractAction leftAction = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("22222222222222222222222222222222222222222");
              turnLeft();
            }
            };
     
           private AbstractAction upAction = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("333333333333333333333333333333333333333333");
                turnNorth();
            }
            };
     
           private AbstractAction downAction = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("4444444444444444444444444444");
                turnSouth();
            }
            };   
     
    }
     
     
     
    package keymapingincardlayout;
     
    import java.awt.Color;
    import java.awt.Graphics;
    import javax.swing.JPanel;
     
    class Ball  extends JPanel{
        int myX;
        static int myY;
        static int xDiameter;
        static int yDiameter;
        static int step;
     
        Ball(int x, int y, int xdmtr, int ydmtr)
        {
            myX = x;
            myY = y;
            xDiameter = xdmtr;
            yDiameter = ydmtr; 
             step = 14;        
        }
     
        /*
         *Moves the player's ball left
         */
        public void moveLeft()
        {
            myX -= step;
        }
     
        /*
         *Moves the player's ball right
         */
        public void moveRight() 
        {
            myX += step;
        }
     
        /*
         *moves the player's ball up
         */
        public void moveUp()
        {
            myY -= step;
        } 
        /*
         *Moves the player's ball down
         */
        public void moveDown() 
        {
            myY += step;
        }
        public void drawMyBall(Graphics g) {
            g.setColor(Color.white);
            g.fillOval(myX, myY, xDiameter, yDiameter);
     
        }
       }

    Thanks you very much

  8. #8
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: Need help to map KeyStrokes in ActionMap using CardLayout in a JApplet

    Quote Originally Posted by bugemberuth View Post
    I appreciate the help you have so far given me but I have failed to work my way round about this problem. As stated above the code you gave me works fine. but when I Incorporated it in my project it failes. i believe this has something to do with calling the CardLayoutClass is called more than once. In my project it is called 4 times before the Maze (AnyClass) is displayed. Below is the new code I have put MiddleClass which calls AnyClass. I need to take time to study the KeyListener I am using static variables because I am doing alot of class referencing guess due bad project design
    Sorry, I can't understand the difficulty you are having, because I can assure you that things are really more simple than your complex, twisted and smoky code.
    Even after my previous conceptual advices, it seems you have not understood and your last code doesn't show any effective improvement.


    The Ball class

    It's quite correct but with some notes to do:
    1) It doesn't need to extend JPanel. I repeat: you are not using Ball as a "component" (and it is not to be used as such!).
    2) It should have instance variables ... not "class" (static) variables! And note: these should be private.
    3) Fix also the namings in order to follow "good" naming conventions. Don't invent parameter names that differ from the fields!


    The PaintPanel class

    I name this "PaintPanel", you can name it as you want, AnyClass, MyPainter, BallPainter ... anything you want.
    The PaintPanel should have:

    1) A public constructor that does (at least) the following things:
    - set the panel as "focusable" (this is required to have the focus).
    - create a Ball instance.
    - register a KeyListener on the panel itself. In the keyPressed method it's sufficient to inspect the KeyEvent to check which key was pressed. Depending on the key, you: 1) invoke the appropriate moveXyz method on Ball and 2) invoke a repaint(). Nothing else.
    - [Optional] any visual/graphical settings: background color, borders, preferred size (if the panel is added in a layout that respects the preferred size).

    Note 1: the KeyListener should be implemented in this PaintPanel, directly in the class (class PaintPanel implements KeyListener) or as an "anonymous" inner class or as a "regular" inner class. It doesn't mind really, these are more "design" choices that doesn't change the final result.

    Note 2: a layout manager like FlowLayout is not necessary: you are not adding components into this panel. This panel is not used as a "container" for other components.

    2) Instance variables (not "class", static variables!) at least for the Ball instance.

    3) paintComponent is ok. It invokes super.paintComponent and then the drawMyBall on the ball.


    Nothing else is really required. This is the "core" that is the bare minimum to create a user-controllable ball.

    Everything else you create around this (putting all this in an applet, or a JFrame, using a CardLayout for any other reasons, etc...) is absolutely "extra" and doesn't change this "core" part. The only notable thing: you have to give the focus to PaintPanel. This can be done into PaintPanel or in some external class. It doesn't mind, it's just sufficient to do this somewhere.


    If after these further advices you can't make real progresses ..... sorry, I don't know how I can help you more than this .....
    Andrea, www.andbin.netSCJP 5 (91%) – SCWCD 5 (94%)

    Useful links for Java beginnersMy new project Java Examples on Google Code

  9. #9
    Junior Member
    Join Date
    Jan 2014
    Location
    Uganda
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need help to map KeyStrokes in ActionMap using CardLayout in a JApplet

    Thank you everybody for taking your time to look at my code - very "complex, twisted and smoky code". i am not a very good programmer. I have found out the solution to my problem. It has nothing to do with Key Mapping or Key Listener. It something to do with Cardlayout or Focus_Cycle inside one Container. Well am no expert but it solved my problem

    below is the magic code;

         EventQueue.invokeLater(new Runnable() {
     
            @Override
            public void run() {
     
                myPanelThatHoldsTheGraphicsInCardLayoutClass.getComponent(indexOfTheGraphicsInstance).requestFocus();
                //i.e mainPanel.getComponent(0).requestFocus();
            }
        });

  10. #10
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: Need help to map KeyStrokes in ActionMap using CardLayout in a JApplet

    Quote Originally Posted by bugemberuth View Post
    It something to do with Cardlayout
    "focus" has, directly and by itself, nothing to do with a layout manager.

    Quote Originally Posted by bugemberuth View Post
    below is the magic code;

                myPanelThatHoldsTheGraphicsInCardLayoutClass.getComponent(indexOfTheGraphicsInstance).requestFocus();
                //i.e mainPanel.getComponent(0).requestFocus();
    Sorry ... there's no "magic" ..... just only the same "twisted" code!

    12 days ago (my answer #5) I told you to use:

    anyClass.requestFocusInWindow();

    And eventually, it's also possible to put the requestFocusInWindow into the AnyClass constructor:

    AnyClass() {
        ..........
        requestFocusInWindow();
    }
    So ... what is (was) the difficulty about this?
    Andrea, www.andbin.netSCJP 5 (91%) – SCWCD 5 (94%)

    Useful links for Java beginnersMy new project Java Examples on Google Code

Similar Threads

  1. Java 2D Game: Implementing Simultaneous Keystrokes
    By AvivC in forum What's Wrong With My Code?
    Replies: 1
    Last Post: January 1st, 2014, 02:35 PM
  2. JPanel not reacting to Keystrokes
    By sonicjr in forum What's Wrong With My Code?
    Replies: 1
    Last Post: November 17th, 2012, 07:10 PM
  3. Replies: 9
    Last Post: September 1st, 2012, 07:25 AM
  4. Regarding Keystrokes
    By esplanade56 in forum Java Theory & Questions
    Replies: 12
    Last Post: May 25th, 2011, 06:46 AM
  5. Cardlayout help
    By phantomswordsmen in forum AWT / Java Swing
    Replies: 1
    Last Post: December 22nd, 2010, 02:36 PM