Results 1 to 6 of 6
  1. #1
    billq is offline Member
    Join Date
    Dec 2009
    Posts
    25
    Rep Power
    0

    Default KeyAdapter won't fire

    Hello, I have been playing with the following code for about a day now. I cannot figure out why the key adapter won't fire. Any help would be appreciated.
    thanks
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class BoundingBox extends JPanel
    {
        private PongBall ball;
        private PongPaddle leftPaddle;
        private PongPaddle rightPaddle;
        private int interval = 10;
        private Timer timer;
    
        public BoundingBox()
        {
            ball = new PongBall(50,50,2,2);
            leftPaddle = new PongPaddle(10,400, "red");
            rightPaddle = new PongPaddle(970,400, "blue");
            addKeyListener(new MyKeyAdapter());
            setPreferredSize(new Dimension(1000,700));
            setBorder(BorderFactory.createLineBorder(Color.BLACK));
            setBackground(Color.BLACK);
            setDoubleBuffered(true);
            timer = new Timer(interval, new TimerAction());
            timer.start();
    
        }
        public void paint(Graphics g)
        {
            super.paint(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.drawImage(ball.getImage(),ball.getX(), ball.getY(),this);
            g2.drawImage(leftPaddle.getImage(),leftPaddle.getX(), leftPaddle.getY(), this);
            g2.drawImage(rightPaddle.getImage(),rightPaddle.getX(), rightPaddle.getY(), this);
        }
        private class TimerAction implements ActionListener
        {
            public void actionPerformed(ActionEvent e)
            {
                ball.setBounds(getWidth(), getHeight());
                ball.move();
                repaint();
            }//end actionPerformed method
        }//end timerAction inner class
        private class MyKeyAdapter extends KeyAdapter
        {
             public void keyReleased(KeyEvent e)
             {
                 System.out.println("hello");
             }
             public void keyPressed(KeyEvent e)
             {
                 System.out.println("hello");
             }
        }//end KeyActions class
    }//end BoundingBox
    Last edited by Eranga; 04-13-2010 at 05:04 PM. Reason: code tags added

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    1) For better help, it's always best to post compilable code, preferably a small program that compiles, runs, doesn't require outside classes (such as PongBall, or PongPaddle), and demonstrates the problem, an SSCCE (Please see my link in my signature below).

    2) When posting code, please use code tags so that your code is readable and understandable by others. For details on how to do this, please see the link in my signature below.

    3) KeyListeners only work if the component they are added to has the focus. You may need to make your JPanel focusable. Having said this, probably a better solution in your situation is to use key bindings which can work whether or not the component has the focus. For details on how to use these, please check out the Sun Swing tutoral on these.

    Best of luck!

    edit: also, you're not going to want to draw in the JPanel's paint method but rather in its paintComponent method. There are many reasons to do it this way and again the Swing tutorials will explain all.

  3. #3
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,371
    Blog Entries
    1
    Rep Power
    20

    Default

    Quote Originally Posted by Fubarable View Post
    2) When posting code, please use code tags so that your code is readable and understandable by others. For details on how to do this, please see the link in my signature below.
    @OP, I've already added tags in the code. Please pay attention on what Fubarable says.

  4. #4
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,371
    Blog Entries
    1
    Rep Power
    20

    Default

    I wrote a simple code about key listeners. May be it's useful to you,

    Java Code:
    import  javax.swing.*;
    import java.awt.*;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    
    public class TextConverter extends JFrame {
        public TextConverter() throws Exception {
            initComponents();
        }
    
        protected void initComponents() {
            setSize(500, 200);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
    
            JLabel yourName = new JLabel("Typw your name: ");
            JTextField yourNameTextField = new JTextField();
            yourNameTextField.setPreferredSize(new Dimension(300, 20));
            getContentPane().add(yourName);
            getContentPane().add(yourNameTextField);
    
            yourNameTextField.addKeyListener(new KeyAdapter() {
                @Override
                public void keyReleased(KeyEvent e) {
                    JTextField textField = (JTextField) e.getSource();
                    String strText = textField.getText();
                    textField.setText(strText.toUpperCase());
                }
    
                @Override
                public void keyTyped(KeyEvent e) {
                    // Key type event
                }
    
                @Override
                public void keyPressed(KeyEvent e) {
                    // Key pressed event
                }
            });
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    try {
                        new TextConverter().setVisible(true);
                    }
                    catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            });
        }
    }
    If you are required any explanation on my code, let me know.


  5. #5
    billq is offline Member
    Join Date
    Dec 2009
    Posts
    25
    Rep Power
    0

    Default

    Thanks enranga for the reply. I will be careful of the code I post in the future. I am new to this stuff. What is the purpose of the throws Exception with the following method? Is it required to when you use try catch in a method or is it optional?
    thanks
    bill
    public TextConverter() throws Exception {

  6. #6
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,371
    Blog Entries
    1
    Rep Power
    20

    Default

    Exceptions can be handle in two ways, in most of the languages. Either you can catch the exception and able to an appropriate action, or throw the action way in simple words.

    Actually it's a matter of who knows the best what to do when something goes wrong in the code/application. If you can fix the problem, then you should handle the exception with a try-catch. (finally also use based on your implementation) If you can't, generally you
    should pass the exception to upper level. Sometimes you do the both.

Similar Threads

  1. Replies: 2
    Last Post: 04-12-2009, 11:39 AM
  2. Fire j2me 2.0 alpha
    By Java Tip in forum Java Software
    Replies: 0
    Last Post: 07-29-2008, 05:24 PM
  3. Fire j2me 1.2
    By JavaBean in forum Java Software
    Replies: 0
    Last Post: 06-22-2007, 12:46 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •