How to move Polygon Object with KeyListener in Java

后端 未结 3 1655
闹比i
闹比i 2020-12-22 06:32

I am working on a 2D game as a learning project and I have hit a bump. I cannot figure out how to move a Polygon object using the KeyListener within a JPanel (which is adde

3条回答
  •  别那么骄傲
    2020-12-22 06:38

    This code has a simple issue:

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;        
    
        frog = new Frog();// <-- !!!!!
    
        // Frog graphics
        g2.setColor(Color.BLACK);
        g2.drawPolygon(frog);
        g2.setColor(new Color(0,150,15));
        g2.fillPolygon(frog);
    }
    

    The marked line overwrites the frog with a new instance, every time the frog is painted, thus reseting it to the original point. Apart from the obvious issue that this is the reason for the unexpected behaviour, never do any unnecessary calculations in the paintComponent(...)-method. Any precomputation, Object-generation, etc. should be done outside of paintComponent!!!

提交回复
热议问题