I have this key listener in my application, and it wont work. This is my first key listener in an application, however I have done a mouse listener in one before. Anyway here is my code:

import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.*;

public class DropGame extends JPanel implements KeyListener {

	int x = 50, y = 50;
	int velocity = 1;
	int accel = 2;
	int friction = 1;
	
	public void game() {
		// TODO Auto-generated method stub
		
		addKeyListener(this);
		repaint ();
	}

	public void paintComponent (Graphics g){
		super.paintComponent(g);
		
		//g.drawString("In Game", 250, 150);
		g.fillRect (x,y,20,20);
		
	}

	@Override
	public void keyPressed(KeyEvent e) {
		// TODO Auto-generated method stub
		int key = e.getKeyCode();
		
		System.out.print("Move");
		if (key == KeyEvent.VK_D){
			int move;
			velocity += accel;
			move = velocity - friction;
			x += move;
			
		}
		if (key == KeyEvent.VK_LEFT){
			int move;
			velocity += accel;
			move = velocity - friction;
			x -= move;
		}
		repaint();
		
	}

	@Override
	public void keyReleased(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void keyTyped(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	
	
}

for some reason the key pressed method will not activate. I have added the listener and everything.

Thanks for the help.

Does the JPanel have the focus?
Can it receive the focus? Not all components can get the focus. Some times you must "register" the component to receive focus. See the API doc for these two methods:
requestFocus() and setFocusable()

@NormR1

EventQueue.invokeLater(new Runnable() {

   @Override
     public void run() {
         someComponent.grabFocus();
         someComponent.requestFocus();//or inWindow depends if Swing or Atw
     }
});

Edited 5 Years Ago by mKorbel: :-)

@mKorbel
Thanks. Time for me to go back and read the API doc again.
For example: ".. developers are strongly encouraged to use requestFocusInWindow when possible."

Edited 5 Years Ago by NormR1: Added "for me"

Comments
selfreflection ++

something near to this (I hate requestFocusInWindow();, because contains lots of chars, and I don't able to forgot that, nothing else)

really not easy job sending Focus to the decision JComponents and with expected action too,

please take that as joke, because last week I *** *** *** with How To Programaticaly sending *** Focus to some JComponets

import java.awt.*;
import java.awt.event.*;
import java.math.RoundingMode;
import java.text.NumberFormat;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;

public class FormatterLimit {

    private JFrame frame = new JFrame();
    private JPanel pnl = new JPanel();
    private JLabel focusLabel = new JLabel(" focusLost Handle ");
    private JFormattedTextField formTextField;
    private JLabel docLabel = new JLabel(" document Handle ");
    private JFormattedTextField formTextField1;
    private NumberFormat formTextFieldFormat;
    private double amount = 10000.00;

    public FormatterLimit() {
        formTextFieldFormat = NumberFormat.getNumberInstance();
        formTextFieldFormat.setMinimumFractionDigits(2);
        formTextFieldFormat.setMaximumFractionDigits(2);
        formTextFieldFormat.setRoundingMode(RoundingMode.HALF_UP);

        focusLabel.setFont(new Font("Serif", Font.BOLD, 14));
        focusLabel.setForeground(Color.blue);
        focusLabel.setPreferredSize(new Dimension(120, 27));
        formTextField = new JFormattedTextField(formTextFieldFormat);
        formTextField.setValue(amount);
        formTextField.setFont(new Font("Serif", Font.BOLD, 22));
        formTextField.setForeground(Color.black);
        formTextField.setBackground(Color.yellow);
        formTextField.setPreferredSize(new Dimension(120, 27));
        formTextField.setHorizontalAlignment(SwingConstants.RIGHT);
        formTextField.addFocusListener(new FocusListener() {

            @Override
            public void focusGained(FocusEvent e) {
                formTextField.requestFocus();
                formTextField.setText(formTextField.getText());
                formTextField.selectAll();
            }

            @Override
            public void focusLost(FocusEvent e) {
                Runnable doRun = new Runnable() {

                    @Override
                    public void run() {
                        double t1a1 = (((Number) formTextField.getValue()).doubleValue());
                        if (t1a1 < 1000) {
                            formTextField.setValue(amount);
                        }
                    }
                };
                SwingUtilities.invokeLater(doRun);

            }
        });

        docLabel.setFont(new Font("Serif", Font.BOLD, 14));
        docLabel.setForeground(Color.blue);
        docLabel.setPreferredSize(new Dimension(120, 27));

        formTextField1 = new JFormattedTextField(formTextFieldFormat);
        formTextField1.setValue(amount);
        formTextField1.setFont(new Font("Serif", Font.BOLD, 22));
        formTextField1.setForeground(Color.black);
        formTextField1.setBackground(Color.yellow);
        formTextField1.setPreferredSize(new Dimension(120, 27));
        formTextField1.setHorizontalAlignment(SwingConstants.RIGHT);
        formTextField1.addFocusListener(new FocusListener() {

            @Override
            public void focusGained(FocusEvent e) {
                formTextField1.requestFocus();
                formTextField1.setText(formTextField1.getText());
                formTextField1.selectAll();
            }

            @Override
            public void focusLost(FocusEvent e) {
            }
        });
        formTextField1.getDocument().addDocumentListener(docListener);

        pnl = new JPanel();
        pnl.setBorder(new EmptyBorder(2, 2, 2, 2));
        pnl.setLayout(new GridLayout(2, 2));
        pnl.add(focusLabel);
        pnl.add(formTextField);
        pnl.add(docLabel);
        pnl.add(formTextField1);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(pnl, BorderLayout.CENTER);
        frame.setLocation(200, 200);
        frame.pack();
        frame.setVisible(true);
        formTextFieldFocus();
    }
    //
    private DocumentListener docListener = new DocumentListener() {

        @Override
        public void changedUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        @Override
        public void insertUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        @Override
        public void removeUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        private void printIt(DocumentEvent documentEvent) {
            DocumentEvent.EventType type = documentEvent.getType();
            double t1a1 = (((Number) formTextField1.getValue()).doubleValue());
            if (t1a1 < 1000) {
                Runnable doRun = new Runnable() {

                    @Override
                    public void run() {
                        formTextField1.setValue(amount);
                    }
                };
                SwingUtilities.invokeLater(doRun);
            }
        }
    };

    public void formTextFieldFocus1() {
        Runnable doRun = new Runnable() {

            @Override
            public void run() {
                formTextField1.grabFocus();
                formTextField1.requestFocus();
                formTextField1.setText(formTextField1.getText());
                formTextField1.selectAll();
            }
        };
        SwingUtilities.invokeLater(doRun);
    }

    public void formTextFieldFocus() {
        Runnable doRun = new Runnable() {

            @Override
            public void run() {
                formTextField.grabFocus();
                formTextField.requestFocus();
                formTextField.setText(formTextField.getText());
                formTextField.selectAll();
                formTextFieldFocus1();
            }
        };
        SwingUtilities.invokeLater(doRun);
    }

    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                FormatterLimit fl = new FormatterLimit();
            }
        });
    }
}
This question has already been answered. Start a new discussion instead.