Question

Im currently trying to make my first game and i am having trouble getting the repaint() method to work. I have checked my keyListeners and have confirmed that they are working a ok! The ship that i have created moves but only if i forcibly resize the window by dragging on the sides. If anyone has any tips i would be very greatful!

If you need any more information feel free to ask!

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;




public class Main extends Canvas implements KeyListener{

public static Ship playerShip = new Ship(150,450,"F5S4-Recovered.png");

public int numberOfEnemies = 0;





public static void createFrame(){



   Window frame1 = new Window();

   final JPanel pane = new JPanel(){

     public void paintComponent(Graphics g){

        super.paintComponent(g);
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, 1000, 1000);
        g.drawImage(playerShip.image, playerShip.xPos1, playerShip.yPos1, this);

    }     

  };

   frame1.add(pane);

}

public void keyTyped(KeyEvent e){System.out.println("KeyTyped");}

public void keyPressed(KeyEvent e){

    switch(e.getKeyCode())
    {
        case KeyEvent.VK_LEFT :
            playerShip.xPos1-=2;
            break;
        case KeyEvent.VK_RIGHT:
            playerShip.xPos1+=2;
            break;


    }


    repaint();

}

public void keyReleased(KeyEvent e){}

public static void main(String args[]){

     createFrame();

}   

}

Window class ----------------------------------------------------------

    import javax.swing.*;



    public class Window extends JFrame{


        public Window()
        {
            setTitle("Space Game");
            setSize(800,800);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            addKeyListener(new Main());
            setVisible(true);

        }




    }
Was it helpful?

Solution

Your call to repaint() is repainting the class Canvas, but the painting is done on the JPanel pane. The resizing causes an automatic repaint of the panel. So to fix you want to pane.repaint(), but you can't do that unless you put the panel as a class member, so you can access it from the listener method. Right now, it's currently locally scoped in the createFrame() method.

Also, you should probably add the listener to the panel instead, and not even extend Canvas, since you're not even using it

Other Notes:

  • Look into using Key Bindings instead of low-level KeyListener

  • Swing apps should be run from the Event Dispatch Thread (EDT). You can do so by simply wrapping the code in your main in a SwingUtilities.invokeLate(..). See more at Initial Threads

  • Again, I'll just add, Don't extends Canvas

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top