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 20 of 20

Thread: keyListener keyPressed not working

  1. #1
    Junior Member
    Join Date
    Oct 2013
    Posts
    10
    My Mood
    Cynical
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Post keyListener keyPressed not working

    I'm working on a project at school and for some reason can't figure out why my keyListener isn't working. The project is in the CVM(Controller View Model) design.

    here is the view code:

    import javax.swing.JFrame;
    import java.awt.Graphics;
    import javax.swing.JPanel;
    import java.util.ArrayList;
     
    public class View extends JFrame {
        private Controller controller;
        private class MyPanel extends JPanel {
            MyPanel(Controller c) {
                addKeyListener(c);
                addMouseListener(c);
     
            }
            public void paintComponent(Graphics g) {
                controller.update(g);
                revalidate();
            }
        }
        public View(Controller c) throws Exception{
            controller = c;
            setTitle("Assignment 4");
            setSize(1200, 800);
            getContentPane().add(new MyPanel(c));
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
        }
    }

    here is the Controller:

    import java.awt.Graphics;
    import java.io.IOException;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.KeyListener;
    import java.awt.event.MouseEvent;
     
    class Controller implements MouseListener, KeyListener
    {
        private Model model;
        private View view;
        Controller() throws IOException, Exception {
            view = new View(this);
            model = new Model(view.getWidth(), view.getHeight());
            view.requestFocus();
        }
        public void update(Graphics g) {
            if (model != null) {
                model.update(g);
            }
        }    
        public Model getModel() { return model; }
     
        public void mousePressed(MouseEvent e) {
            model.forward();
            view.repaint();
        }
        public void mouseReleased(MouseEvent e) {    }
        public void mouseEntered(MouseEvent e) {    }
        public void mouseExited(MouseEvent e) {    }
        public void mouseClicked(MouseEvent e) {    }
     
        public void keyPressed(KeyEvent e) {
            char s = e.getKeyChar();
            if(s == 'r' || s == 'R') {
                model.initialize();
            }
        }
        public void keyTyped(KeyEvent e) {    }
        public void keyReleased(KeyEvent e) {    }   
        public static void main(String[] args) throws Exception {
            //  Use the following line to determine which directory your program
            //  is being executed from, since that is where the image files will
            //  need to be.
            //System.out.println("cwd=" + System.getProperty("user.dir"));
            new Controller();
        }
    }


    Here is the Model:

    import java.awt.Graphics;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Random;
    import java.util.Iterator;
     
    class Model
    {
        private ArrayList<Sprite> sprites;
        private int width;
        private int height;
        Random r;
     
        Model(int w, int h) throws IOException {
            sprites = new ArrayList<Sprite>();
            width = w;
            height = h;
            r = new Random();
            initialize();
        }    
        public ArrayList<Sprite> getSpriteList() { return sprites; }
        public void initialize() {
            if((sprites != null)&&(!sprites.isEmpty())) {
                Iterator<Sprite> iter = sprites.iterator();
                while(iter.hasNext())
                    sprites.remove(iter);
            }
            for (int i=0; i<50; i++) {
                int newX = r.nextInt(width-50);
                int newY = r.nextInt(height-50);
                if (i%2==0) {
                    sprites.add(new Razorback(newX, newY, width, height));
                } else {
                    sprites.add(new Opponent(newX, newY, width, height));
                }
            }
        }
        public void update(Graphics g) {
            for (Sprite sprite : sprites) {
                sprite.update(g);
            }
        }
        public void forward() {
        	Iterator<Sprite> iter1 = sprites.iterator();
        	while(iter1.hasNext()){
        		Sprite obj1 = iter1.next();
        		if(obj1.shouldRemove()) {
                    iter1.remove();
        		}
        	}
            for (Sprite s : sprites) {
                s.move();
                Iterator<Sprite> iter2 = sprites.iterator();
                while(iter2.hasNext()) {
                    Sprite obj2 = iter2.next();
                    if(s.overlaps(obj2))
                    {
                        if((s instanceof Razorback)&&(obj2 instanceof Opponent)){
                            obj2.hit();
                        }
                        else if((s instanceof Opponent)&&(obj2 instanceof Razorback)){
                            s.hit();
                        }
                    }
                }
            }
        }
    }

    When a key is pressed the model is suppose to be re initialized. Any Idea why the keyListener keyPressed handler is not working?
    Last edited by hogsgonewild; October 13th, 2013 at 11:03 AM. Reason: added requestFocus call on view in the Controller Constructor


  2. #2
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,514
    My Mood
    Grumpy
    Thanks
    0
    Thanked 165 Times in 156 Posts

    Default Re: keyListener keyPressed not working

    Debug your code. Place print statements in the keyPressed method to ensure it is actually being called.
    Try resizing the GUI. If you see changes after that it usually indicates a painting problem.
    Improving the world one idiot at a time!

  3. #3
    Junior Member
    Join Date
    Oct 2013
    Posts
    10
    My Mood
    Cynical
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: keyListener keyPressed not working

    Resized it and still got no response. It seems like my call to initialize is not working right.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,198
    Thanks
    49
    Thanked 2,173 Times in 2,146 Posts

    Default Re: keyListener keyPressed not working

    Does the MyPanel object have the focus?
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Oct 2013
    Posts
    10
    My Mood
    Cynical
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: keyListener keyPressed not working

    I've tried but not sure if I was setting it right. How should I address it in this code?

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,198
    Thanks
    49
    Thanked 2,173 Times in 2,146 Posts

    Default Re: keyListener keyPressed not working

    I've tried but not sure if I was setting it right
    Post the code showing where you are trying.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Oct 2013
    Posts
    10
    My Mood
    Cynical
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: keyListener keyPressed not working

    Added the call to the controller code. Am I calling it right?

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,198
    Thanks
    49
    Thanked 2,173 Times in 2,146 Posts

    Default Re: keyListener keyPressed not working

    Does the View object get the focus? Add a focus listener to see if it gets and keeps the focus by printing out messages when it gets the focus and when it loses the focus.
    What object has the key listener and what object has the focus? It needs to be the same object.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Oct 2013
    Posts
    10
    My Mood
    Cynical
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: keyListener keyPressed not working

    The Panel should be the one with listener. It is also the one I need to have the focus. I am giving the view the focus but its MyPanel that has the listeners and it needs the focus. How do I request the focus for the MyPanel class that is inside the View class?

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,198
    Thanks
    49
    Thanked 2,173 Times in 2,146 Posts

    Default Re: keyListener keyPressed not working

    How do I request the focus for the MyPanel class
    Get a reference to the object and use that to call the method.

    Also you should read the tutorial about focus:
    http://docs.oracle.com/javase/tutori...isc/focus.html
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    Oct 2013
    Posts
    10
    My Mood
    Cynical
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: keyListener keyPressed not working

    Would it be the controller that was used in the Views constructor?

    --- Update ---

    I am looking at that link and it is good info but I can't figure out how to do this in my code.

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,198
    Thanks
    49
    Thanked 2,173 Times in 2,146 Posts

    Default Re: keyListener keyPressed not working

    Where is the MyPanel object created? Use the reference to the object that is created there to call that object's methods. Or do it in the constructor.

    Can the MyPanel object get the focus? Not all components can. You may need to call a method that makes it possible for the MyPanel object to get the focus. It's explained in the tutorial page I linked to in the Making a Custom Component Focusable section.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Junior Member
    Join Date
    Oct 2013
    Posts
    10
    My Mood
    Cynical
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: keyListener keyPressed not working

    Currently the only time MyPanel is created is in the Views constructor and it is done inside a call: getContentPane().add(new MyPanel(c));
    Should I instead make the panel then use it in the getContentPane().add()?

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,198
    Thanks
    49
    Thanked 2,173 Times in 2,146 Posts

    Default Re: keyListener keyPressed not working

    If you want a reference to the MyPanel object you should use an assignment statement with the new operator. Then use that reference to call the methods and to pass the reference to the add() method.

    Or call the methods in the MyPanel's constructor.
    If you don't understand my answer, don't ignore it, ask a question.

  15. #15
    Junior Member
    Join Date
    Oct 2013
    Posts
    10
    My Mood
    Cynical
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: keyListener keyPressed not working

    Still isn't working. Here is the code.

    View:
    import javax.swing.JFrame;
    import java.awt.Graphics;
    import javax.swing.JPanel;
    import java.util.ArrayList;
     
    public class View extends JFrame {
        private Controller controller;
     
        private class MyPanel extends JPanel {
     
            MyPanel(Controller c) {
                addKeyListener(c);
                addMouseListener(c);
            }
     
            public void paintComponent(Graphics g) {
                controller.update(g);
                revalidate();
            }
        }
     
     
        public View(Controller c) throws Exception{
            controller = c;
            MyPanel panel = new MyPanel(c);
            setTitle("Assignment 4");
            setSize(1200, 800);
            getContentPane().add(panel);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            panel.requestFocus();
            setVisible(true);
        }
    }

    Controller:
    import java.awt.Graphics;
    import java.io.IOException;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.KeyListener;
    import java.awt.event.MouseEvent;
     
    class Controller implements MouseListener, KeyListener
    {
        private Model model;
        private View view;
     
        Controller() throws IOException, Exception {
            view = new View(this);
            model = new Model(view.getWidth(), view.getHeight());
        }
     
        public void update(Graphics g) {
            if (model != null) {
                model.update(g);
            }
        }
     
        public Model getModel() { return model; }
     
        public void mousePressed(MouseEvent e) {
            model.forward();
            view.repaint();
        }
        public void mouseReleased(MouseEvent e) {    }
        public void mouseEntered(MouseEvent e) {    }
        public void mouseExited(MouseEvent e) {    }
        public void mouseClicked(MouseEvent e) {    }
     
        @Override
        public void keyPressed(KeyEvent e) {
            char s = e.getKeyChar();
            if(s == 'r' || s == 'R') {
                model.initialize();
            }
        }
        public void keyTyped(KeyEvent e) {    }
        public void keyReleased(KeyEvent e) {    }
     
     
        public static void main(String[] args) throws Exception {
            //  Use the following line to determine which directory your program
            //  is being executed from, since that is where the image files will
            //  need to be.
            //System.out.println("cwd=" + System.getProperty("user.dir"));
            new Controller();
        }
    }

    Model:
    import java.awt.Graphics;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Random;
    import java.util.Iterator;
     
    class Model
    {
        private ArrayList<Sprite> sprites;
        private int width;
        private int height;
        Random r;
     
        Model(int w, int h) throws IOException {
            sprites = new ArrayList<Sprite>();
            width = w;
            height = h;
            r = new Random();
            initialize();
        }
     
        public ArrayList<Sprite> getSpriteList() { return sprites; }
     
        public void initialize() {
            if((sprites != null)&&(!sprites.isEmpty())) {
                Iterator<Sprite> iter = sprites.iterator();
                while(iter.hasNext())
                    sprites.remove(iter);
            }
            for (int i=0; i<50; i++) {
                int newX = r.nextInt(width-50);
                int newY = r.nextInt(height-50);
                if (i%2==0) {
                    sprites.add(new Razorback(newX, newY, width, height));
                } else {
                    sprites.add(new Opponent(newX, newY, width, height));
                }
            }
        }
     
        public void update(Graphics g) {
            for (Sprite sprite : sprites) {
                sprite.update(g);
            }
        }
     
        public void forward() {
        	Iterator<Sprite> iter1 = sprites.iterator();
        	while(iter1.hasNext()){
        		Sprite obj1 = iter1.next();
        		if(obj1.shouldRemove()) {
                    iter1.remove();
        		}
        	}
            for (Sprite s : sprites) {
                s.move();
                Iterator<Sprite> iter2 = sprites.iterator();
                while(iter2.hasNext()) {
                    Sprite obj2 = iter2.next();
                    if(s.overlaps(obj2))
                    {
                        if((s instanceof Razorback)&&(obj2 instanceof Opponent)){
                            obj2.hit();
                        }
                        else if((s instanceof Opponent)&&(obj2 instanceof Razorback)){
                            s.hit();
                        }
                    }
                }
            }
        }
    }

    The end goal is this: The Window will first be blank. when the user clicks inside the window image objects from two classes will be added to the window at random locations. Both classes extend the same abstract class. When the objects of different classes collide the object from one class will turn into a gravestone. the other will go on as is. When the user presses the r key the window will be reset(initialize function).
    it is the key pressed part that I can't seem to get working.

  16. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,198
    Thanks
    49
    Thanked 2,173 Times in 2,146 Posts

    Default Re: keyListener keyPressed not working

    Did you see this from post#12

    Can the MyPanel object get the focus? Not all components can. You may need to call a method that makes it possible for the MyPanel object to get the focus. It's explained in the tutorial page I linked to in the Making a Custom Component Focusable section.

    For debugging you should add a call to the println() method to print a message to show that the keyPressed() method was called.
    If you don't understand my answer, don't ignore it, ask a question.

  17. #17
    Junior Member
    Join Date
    Oct 2013
    Posts
    10
    My Mood
    Cynical
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: keyListener keyPressed not working

    I tried to request the focus on the panel that was created in the view constructor which was used in the getContentPane call.

  18. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,198
    Thanks
    49
    Thanked 2,173 Times in 2,146 Posts

    Default Re: keyListener keyPressed not working

    Is the MyPanel object able to get the focus? See the doc at the link.
    If you don't understand my answer, don't ignore it, ask a question.

  19. #19
    Junior Member
    Join Date
    Oct 2013
    Posts
    10
    My Mood
    Cynical
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: keyListener keyPressed not working

    Just found the error. Should of added the key listener to the view constructor and how initialize was clear out the arraylist was incorrect. I could just set the arraylist to a new one when called and problem solved. Wow was this a small problem made big in my head. Thanks for the help y'all

  20. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,198
    Thanks
    49
    Thanked 2,173 Times in 2,146 Posts

    Default Re: keyListener keyPressed not working

    Adding a key listener to a component that can get the focus will work.
    Adding a key listener to a component that is not configured to take the focus won't work until that component's method is called to allow it to get the focus.

    I guess you found another component that can get the focus instead of using MyPanel.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. KeyListener isn't working while jFrame not active
    By aslanali555 in forum AWT / Java Swing
    Replies: 3
    Last Post: August 22nd, 2013, 01:16 PM
  2. keyListener not working
    By soradogoof in forum Java Applets
    Replies: 2
    Last Post: August 14th, 2012, 05:33 PM
  3. keyPressed method not working?
    By TP-Oreilly in forum What's Wrong With My Code?
    Replies: 5
    Last Post: December 29th, 2011, 08:43 AM
  4. Help with Graphics class and keyPressed method
    By smashX in forum What's Wrong With My Code?
    Replies: 2
    Last Post: April 10th, 2011, 12:46 PM
  5. My KeyListener is not Working!!
    By DarrenReeder in forum What's Wrong With My Code?
    Replies: 2
    Last Post: February 28th, 2010, 04:18 PM

Tags for this Thread