Nicholas Eason
Nicholas Eason

Reputation: 300

JPanel repaint not working properly

I have a JPanel, class is called WorldPanel (look below for code), and I'm using a KeyListener() to move it. It moves, so I don't think it's the KeyListener that is at fault. The problem is that when I call repaint() on the JPanel, it slowly stops repainting a portion of the screen. So (in 1's and 0's with 0 being my image, and 1 being parts not being repainted) the image looks like:

000000000000

repaint();

100000000000

repaint();

110000000000

etc.

Eventually, the whole panel stops repainting.

WorldPanel.java:

    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    //This Image is instantiated in the constructor

    //worldImage = ImageIO.read(new File("H:\\Java\\Game\\src\\res\\WorldBase.png"));
    g.drawImage(worldImage, x, y, 6144, 4608, null);
}
public void setX(int x){
    this.x = x;
}
public void setY(int y){
    this.y = y;
}
public int getX(){
    return x;
}
public int getY(){
    return y;
}

Implementation of class:

worldPanel.addKeyListener(new KeyListener(){
        Timer timer = new Timer(10, new ActionListener(){
            public void actionPerformed(ActionEvent e){
                worldPanel.repaint();
                timer.stop();
            }
        });
        @Override
        public void keyPressed(KeyEvent arg0) {
            if(arg0.getKeyCode() == KeyEvent.VK_W && worldPanel.getY() > 0){
                worldPanel.setY(worldPanel.getY() + 1);
                timer.start();
            }
            if(arg0.getKeyCode() == KeyEvent.VK_A && worldPanel.getX() > 0){
                worldPanel.setX(worldPanel.getX() +1);
                timer.start();
            }
            if(arg0.getKeyCode() == KeyEvent.VK_S && worldPanel.getY() < 4608){
                worldPanel.setY(worldPanel.getY() - 1);
                timer.start();
            }
            if(arg0.getKeyCode() == KeyEvent.VK_D && worldPanel.getX() < 6144){
                worldPanel.setX(worldPanel.getX() -1);
                timer.start();
            }
        }
        @Override
        public void keyReleased(KeyEvent arg0) {
        }
        @Override
        public void keyTyped(KeyEvent arg0) {
        }
    });

I looked around, and everything I found either said:

Upvotes: 0

Views: 113

Answers (1)

tenorsax
tenorsax

Reputation: 21233

The problem is that you are overriding JComponent methods getX()/setX()/getY()/setY(). This interferes with calculation of painting area of the panel. Give these methods a different name, ie: setImageX()/getImageX().

Upvotes: 2

Related Questions