I am attaching my complete code, which I was currently developing. I am not able to get why doesn't my KeyListener work. None of the KeyListener events are fires on pressing the keyboard. Please have a look and tell me the flaws in my code

Path.java

Recommended Answers

All 13 Replies

Does the component with the listener have the focus? Can it get the focus?
Have you clicked on the component to give it the focus before pressing any keys?
Please post the code here where we can see it and not have to download it.

Here is the complete code

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */



import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;

/**
 *
 * @author gunjan
 * @copyright gunjan 2011
 */
public class Path extends JPanel implements ActionListener,KeyListener
{
    Dimension screenSize;
    ArrayList<Point> eightPoints;
    ArrayList<ArrayList<Point>> eightList;
    ArrayList<ArrayList<Point>> ringList;
    ArrayList<Point> ringPoints;
    ArrayList<ArrayList<Point>> loitreList;
    ArrayList<Point> loitrePoints;
    String statusBar,mouseCoord;
    private int currentFig =0;
    Point currentPoint;
    public static void main(String[] args)
    {
        Path path = new Path();
    }
    public Path()
    {
        JFrame frame = new JFrame();
        screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setSize(screenSize);
        frame.setUndecorated(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               
        this.setBackground(Color.black);
        addKeyListener(this);
        frame.getContentPane().add(this);
        statusBar = "Ready";
        ringPoints = new ArrayList<Point>();
        ringList = new ArrayList<ArrayList<Point>>();
        eightPoints = new ArrayList<Point>();
        eightList = new ArrayList<ArrayList<Point>>();
        loitrePoints = new ArrayList<Point>();
        loitreList = new ArrayList<ArrayList<Point>>();
        setMouseCoord(MouseInfo.getPointerInfo().getLocation());
        this.createPopupMenu();
        
        frame.setVisible(true);
    }
    private void setMouseCoord(Point p)
    {
        mouseCoord = "X: "+(int)p.getX()+"  Y: "+(int)p.getY();
    }
    @Override
    public void paint(Graphics g)
    {
        super.paint(g);
        Graphics2D g2d = (Graphics2D)g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2d.setStroke(new BasicStroke(2));
        for(int i=0;i<loitreList.size();i++)
        {
            ArrayList<Point> pointList = loitreList.get(i);
            Point point1 = pointList.get(0);
            Point point2 = pointList.get(1);

            double radius = point1.distance(point2);
            g2d.setColor(Color.white);
            g2d.fillOval((int)point1.getX()-3, (int)point1.getY()-3, 6,6);
            g2d.drawOval((int)(point1.getX()-radius), (int)(point1.getY()-radius),(int)(2*radius), (int) (2 * radius));
            
        }
        for(int i=0;i<eightList.size();i++)
        {
            ArrayList<Point> pointList = eightList.get(i);
            Point point1 = pointList.get(0);
            Point point2 = pointList.get(1);
            g2d.setColor(Color.white);
            g2d.fillOval((int)point1.getX()-3, (int)point1.getY()-3, 6,6);
            g2d.fillOval((int)point2.getX()-3, (int)point2.getY()-3, 6,6);
            //g2d.drawLine((int)point1.getX(),(int)point1.getY(),(int)point2.getX(),(int)point2.getY());
            double radius = point2.distance(point1)/2;

            g2d.drawOval((int)(point1.getX()-radius), (int)(point1.getY()-radius),(int)(2*radius), (int) (2 * radius));
            g2d.drawOval((int)(point2.getX()-radius), (int)(point2.getY()-radius),(int)(2*radius), (int) (2 * radius));
            
        }
        for(int i=0;i<ringList.size();i++)
        {
            ArrayList<Point> pointList = ringList.get(i);
            Point point1 = pointList.get(0);
            Point point2 = pointList.get(1);
            Point point3 = pointList.get(2);
            double radius = point1.distance(point3);
            g2d.setColor(Color.white);
            g2d.fillOval((int)point1.getX()-3, (int)point1.getY()-3, 6,6);
            g2d.fillOval((int)point2.getX()-3, (int)point2.getY()-3, 6,6);
            //g2d.drawLine((int)point1.getX(),(int)point1.getY(),(int)point2.getX(),(int)point2.getY());
            double deltaX= point2.getX()-point1.getX();
            double deltaY= point2.getY()-point1.getY();
            double theta = Math.atan2(deltaY, deltaX);            
            //g2d.drawArc(i, i, i, i, ABORT, ABORT)
            g2d.drawArc((int)(point1.getX()-radius), (int)(point1.getY()-radius),(int)(2*radius), (int) (2 * radius), 90-(int) Math.toDegrees(theta),180);
            g2d.drawArc((int)(point2.getX()-radius), (int)(point2.getY()-radius),(int)(2*radius), (int) (2 * radius),90-(int) Math.toDegrees(theta),-180);
            int X1 = (int)(point1.getX()-radius*Math.cos(Math.PI/2+theta));
            int Y1 = (int)(point1.getY()-radius*Math.sin(Math.PI/2+theta));
            int X2 = (int)(point2.getX()-radius*Math.cos(Math.PI/2+theta));
            int Y2 = (int)(point2.getY()-radius*Math.sin(Math.PI/2+theta));
            int X3 = (int)(point1.getX()+radius*Math.cos(Math.PI/2+theta));
            int Y3 = (int)(point1.getY()+radius*Math.sin(Math.PI/2+theta));
            int X4 = (int)(point2.getX()+radius*Math.cos(Math.PI/2+theta));
            int Y4 = (int)(point2.getY()+radius*Math.sin(Math.PI/2+theta));
            g2d.drawLine(X1,Y1,X2,Y2);
            g2d.drawLine(X3,Y3,X4,Y4);
        }
        if(!eightPoints.isEmpty() && currentFig ==2)
        {
            g2d.setColor(Color.white);
            for(int i=0;i<eightPoints.size();i++)
            {
                Point currPoint = eightPoints.get(i);
                g2d.fillOval((int)currPoint.getX()-3, (int)currPoint.getY()-3, 6,6);
            }
        }
        if(!ringPoints.isEmpty() && currentFig ==3)
        {
            g2d.setColor(Color.white);
            for(int i=0;i<ringPoints.size();i++)
            {
                Point currPoint = ringPoints.get(i);
                g2d.fillOval((int)currPoint.getX()-3, (int)currPoint.getY()-3, 6,6);
            }
        }
        if(ringPoints.size()==2 && currentPoint != null)
        {
            g2d.setColor(Color.white);
            g2d.drawLine((int)ringPoints.get(0).getX(), (int)ringPoints.get(0).getY(), (int)currentPoint.getX(), (int) currentPoint.getY());
        }
        if(loitrePoints.size()==1 && currentPoint != null)
        {
            g2d.setColor(Color.white);
            g2d.drawLine((int)loitrePoints.get(0).getX(), (int)loitrePoints.get(0).getY(), (int)currentPoint.getX(), (int) currentPoint.getY());
        }
        g2d.setColor(Color.black);
        g2d.fillRect(0,(int)screenSize.getHeight()-20,(int)screenSize.getWidth(),20);
        g2d.setFont(new Font("Arial",Font.BOLD,14));
        g2d.setColor(Color.white);
        g2d.drawString(statusBar, 10,(int)screenSize.getHeight()-5);
        g2d.drawString(mouseCoord, (int)screenSize.getWidth()-100,(int)screenSize.getHeight()-5);

    }
	public void keyTyped(KeyEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");
        System.out.println(e);
    }

    public void keyPressed(KeyEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");
        System.out.println(e);
    }

    public void keyReleased(KeyEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");
        System.out.println(e);
    }
    public void createPopupMenu() {
        JMenuItem menuItem;

        //Create the popup menu.
        JPopupMenu popup = new JPopupMenu();
        menuItem = new JMenuItem("Loitre");
        menuItem.addActionListener(this);

        popup.add(menuItem);
        menuItem = new JMenuItem("Eight");
        menuItem.addActionListener(this);
        popup.add(menuItem);

        menuItem = new JMenuItem("Ring");
        menuItem.addActionListener(this);
        popup.add(menuItem);
        //Add listener to the text area so the popup menu can come up.
        PopupListener popupListener = new PopupListener(popup);
        this.addMouseListener(popupListener);
        this.addMouseMotionListener(popupListener);
        //this.addKeyListener(popupListener);
    }

    public void actionPerformed(ActionEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");
//System.out.println(e);
        if(e.getActionCommand().equalsIgnoreCase("Loitre"))
        {
            statusBar="Select Center";
            loitrePoints = new ArrayList<Point>();
            repaint();
            currentFig = 1;
        }
        else if(e.getActionCommand().equalsIgnoreCase("Eight"))
        {
            
            statusBar="Select First Point";
            eightPoints = new ArrayList<Point>();
            repaint();
            currentFig = 2;
        }
        else if(e.getActionCommand().equalsIgnoreCase("Ring"))
        {

            statusBar="Select First Point";
            ringPoints = new ArrayList<Point>();
            repaint();
            currentFig = 3;
        }
    }

   
   class PopupListener implements MouseListener,MouseMotionListener {
        JPopupMenu popup;

        PopupListener(JPopupMenu popupMenu) {
            popup = popupMenu;
        }

        public void mousePressed(MouseEvent e) {
            //System.out.println(e.getButton()+"\t"+currentFig);
            
            if(e.getButton()==MouseEvent.BUTTON1 && currentFig==2)
            {
                //System.out.println(e.getButton());
                if(eightPoints.isEmpty())
                {
                    eightPoints.add(e.getPoint());
                    statusBar="Select Second Point";
                    repaint();
                }
                else
                {
                    eightPoints.add(e.getPoint());
                    eightList.add(eightPoints);
                    statusBar="Ready";
                    repaint();
                    currentFig=0;
                }
            }
            if(e.getButton()==MouseEvent.BUTTON1 && currentFig==3)
            {
                //System.out.println(e.getButton());
                if(ringPoints.isEmpty())
                {
                    ringPoints.add(e.getPoint());
                    currentPoint = e.getPoint();
                    statusBar="Select Second Point";
                    repaint();
                }
                else if(ringPoints.size()==1)
                {
                    ringPoints.add(e.getPoint());
                    //eightList.add(eightPoints);
                    statusBar="Select Radius";
                    setCursor(new Cursor(Cursor.SE_RESIZE_CURSOR));
                    repaint();                    
                }
                else
                {
                    ringPoints.add(e.getPoint());
                    ringList.add(ringPoints);
                    statusBar="Ready";
                    setCursor(Cursor.getDefaultCursor());
                    repaint();
                    currentFig=0;
                }
            }
            if(e.getButton()==MouseEvent.BUTTON1 && currentFig==1)
            {
                //System.out.println(e.getButton());
                if(loitrePoints.isEmpty())
                {
                    loitrePoints.add(e.getPoint());
                    currentPoint = e.getPoint();
                    statusBar="Select Radius";
                    setCursor(new Cursor(Cursor.SE_RESIZE_CURSOR));
                    repaint();
                }
                else
                {
                    loitrePoints.add(e.getPoint());
                    loitreList.add(loitrePoints);
                    statusBar="Ready";
                    setCursor(Cursor.getDefaultCursor());
                    repaint();
                    currentFig=0;
                }

            }
            maybeShowPopup(e);
        }

        public void mouseReleased(MouseEvent e) {

            maybeShowPopup(e);
        }

        private void maybeShowPopup(MouseEvent e) {

            if (e.getButton()==MouseEvent.BUTTON3) {
                popup.show(e.getComponent(),
                           e.getX(), e.getY());
            }

        }

        public void mouseClicked(MouseEvent e) {
            //throw new UnsupportedOperationException("Not supported yet.");
        }

        public void mouseEntered(MouseEvent e) {
            //throw new UnsupportedOperationException("Not supported yet.");
        }

        public void mouseExited(MouseEvent e) {
            //throw new UnsupportedOperationException("Not supported yet.");
        }

        public void mouseDragged(MouseEvent e) {
            //throw new UnsupportedOperationException("Not supported yet.");
            
        }

        public void mouseMoved(MouseEvent e) {
            //throw new UnsupportedOperationException("Not supported yet.");
            NumberFormat formatter = new DecimalFormat("0.###");
            if(currentFig==3 && ringPoints.size()==2)
            {
                currentPoint = e.getPoint();
                statusBar = "Select Radius:  "+formatter.format(ringPoints.get(0).distance(currentPoint));
            }
            if(currentFig==1 && loitrePoints.size()==1)
            {
                currentPoint = e.getPoint();
                statusBar = "Select Radius:  "+formatter.format(loitrePoints.get(0).distance(currentPoint));
            }
            setMouseCoord(e.getPoint());
            repaint();
        }
         
    }
   
}
The Component in this code is the panel itself. I am not sure it gets focus or not. Its the main Panel so it should have focus

Can JPanel components get the focus?

and change KeyListener to the KeyBindings

Here is a simple form if my code with KeyListener not working. Listener is added to my main panel. The main Panel has the focus but still keyListner is not working. Have a look at it

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */



import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;

/**
 *
 * @author gunjan
 * @copyright gunjan 2011
 */
public class Example extends JPanel implements ActionListener,KeyListener
{
    Dimension screenSize;
    Point currentPoint;
    public static void main(String[] args)
    {
        Example path = new Example();
    }
    public Example()
    {
        
            JFrame frame = new JFrame();
            screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            frame.setSize(screenSize);
            frame.setUndecorated(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setBackground(Color.black);
            addKeyListener(this);
            frame.getContentPane().add(this);
            this.createPopupMenu();
            
            frame.setVisible(true);
        
    }
    
    public void keyTyped(KeyEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");
        System.out.println(e);
    }

    public void keyPressed(KeyEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");
        System.out.println(e);
    }

    public void keyReleased(KeyEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");
        System.out.println(e);
    }
    @Override
    public void paint(Graphics g)
    {
        super.paint(g);
        Graphics2D g2d = (Graphics2D)g;
        
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        if(currentPoint!=null)
        {
            g2d.setColor(Color.white);
            g2d.fillOval((int) (currentPoint.getX() - 3), (int) (currentPoint.getY() - 3), 6,6);
        }

    }
    public void createPopupMenu() {
        JMenuItem menuItem;

        //Create the popup menu.
        JPopupMenu popup = new JPopupMenu();
        menuItem = new JMenuItem("Loitre");
        menuItem.addActionListener(this);

        popup.add(menuItem);
        menuItem = new JMenuItem("Eight");
        menuItem.addActionListener(this);
        popup.add(menuItem);

        menuItem = new JMenuItem("Ring");
        menuItem.addActionListener(this);
        popup.add(menuItem);
        //Add listener to the text area so the popup menu can come up.
        PopupListener popupListener = new PopupListener(popup);
        this.addMouseListener(popupListener);
        this.addMouseMotionListener(popupListener);
        
    }

    public void actionPerformed(ActionEvent e) {
        System.out.println(e.getActionCommand());
    }

   
   class PopupListener implements MouseListener,MouseMotionListener {
        JPopupMenu popup;

        PopupListener(JPopupMenu popupMenu) {
            popup = popupMenu;
        }

        public void mousePressed(MouseEvent e) {
            //System.out.println(e.getButton()+"\t"+currentFig);
            
            
            maybeShowPopup(e);
        }

        public void mouseReleased(MouseEvent e) {

            maybeShowPopup(e);
        }

        private void maybeShowPopup(MouseEvent e) {

            if (e.getButton()==MouseEvent.BUTTON3) {
                popup.show(e.getComponent(),
                           e.getX(), e.getY());
            }
            else if(e.getButton()==MouseEvent.BUTTON1)
            {
                currentPoint = e.getPoint();
                repaint();
            }
        }

        public void mouseClicked(MouseEvent e) {
            //throw new UnsupportedOperationException("Not supported yet.");
        }

        public void mouseEntered(MouseEvent e) {
            //throw new UnsupportedOperationException("Not supported yet.");
        }

        public void mouseExited(MouseEvent e) {
            //throw new UnsupportedOperationException("Not supported yet.");
        }

        public void mouseDragged(MouseEvent e) {
            //throw new UnsupportedOperationException("Not supported yet.");
            
        }

        public void mouseMoved(MouseEvent e) {
            //throw new UnsupportedOperationException("Not supported yet.");
            
       }
    }
   
}

You may need to setFocusable(true); on your JPanel followed by requestFocus();

You may need to setFocusable(true); on your JPanel followed by requestFocus();

Thanks that worked perfectly fine. I assumed that JPanel must be having the focus but it didn't.

Great! Mark this "solved" so other people can see the solution.

@JamesCherrill

not (-:please to stop to catch the Focus:-) if you'd implements KeyBinding then you could stop to care about Focus, FocusRecycle, SubSystem Fosuc, this best Swing Listener for HardWare KeyBoard, (-: and in all cases better as memoninic as you suggested in other thread:-)

... if you'd implements KeyBinding then you could stop to care about ..

Yes, I agree.
For some reasons key bindings are presented as an "advanced" or "low-level" tool, and students are taught ordinary key listeners first, so for a beginner I think it's less confusing to go with the ordinary listener. For the more advanced developer, or in real-life full-size apps key bindings have many advantages.

@JamesCherrill

not (-:please to stop to catch the Focus:-) if you'd implements KeyBinding then you could stop to care about Focus, FocusRecycle, SubSystem Fosuc, this best Swing Listener for HardWare KeyBoard, (-: and in all cases better as memoninic as you suggested in other thread:-)

Thanks I will try to that also . Can you give me a good working example of how to implement KeyBinding. I was trying to use Oracle one but could not get it working.

I don't have anything to hand that could be used in isolation, sorry. Maybe mKorbel has something?

I got it working. Thanks mKorbel. With KeyBindings I don't have to care upon Focusable

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.