tomtomssi
tomtomssi

Reputation: 1035

Paint method gets called but doesn't redraw

The problem here is that the paintComponent() method gets called, it gets the necessary variables for fillRect() but doesn't actually draw anything after a key is pressed. I don't understand why since the returned value of mato.getPositionX() does get incremented every time the D key is pressed and the incremented value gets passed to fillRect(). Here's the code:

Screen class

public class Screen extends JFrame implements KeyListener {

private Mato mDrawScreensMato;

public Screen() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    pack();
    setVisible(true);
    setLocationRelativeTo(null);
    setSize(400, 400);
    DrawScreen screen = new DrawScreen();
    mDrawScreensMato = screen.getMato();
    addKeyListener(this);
    add(screen);
}

//keyTyped

@Override
public void keyPressed(KeyEvent ke) {
    int c = ke.getKeyCode();
    if (c == KeyEvent.VK_D) {
        mDrawScreensMato.setPositionX(mDrawScreensMato.getPositionX() + 1);
        repaint();
        }
    }

//keyReleased
}

DrawScreen class

public class DrawScreen extends JPanel {

private Mato mato;

public DrawScreen() {
    mato = new Mato();
}

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.setColor(Color.RED);
    System.out.println(mato.getPositionX());
    g2d.fillRect(
            mato.getPositionX(), mato.getPositionY(),
            mato.MATO_WIDTH, mato.MATO_HEIGHT
    );
}

public Mato getMato() {
    return mato;
    }
}

Mato class

public class Mato {
    final int MATO_WIDTH = 20;
    final int MATO_HEIGHT = 20;
    final int MATO_START_POS_X = 20;
    final int MATO_START_POS_Y = 40;

    private int positionX;
    private int positionY;

public Mato(){
        positionX = MATO_START_POS_X;
        positionY = MATO_START_POS_Y;
    }

public void setPositionX(int positionX) {
        this.positionX = positionX;
    }

public int getPositionX() {
        return positionX;
    }

//Get/Set positionY

}

Upvotes: 0

Views: 75

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347214

The main cause of your problem is you are calling setVisible to early...

The general rule of thumb is, call setVisible only after you have prepared the UI

public Screen() {
    DrawScreen screen = new DrawScreen();
    mDrawScreensMato = screen.getMato();
    addKeyListener(this);
    add(screen);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // This is a useless call as DrawScreen
    // does not provide appropriate sizing hints to the layout manager
    pack();
    setSize(400, 400);
    // This needs to be called AFTER the size of window has been determined,
    // as it uses the size of the window to determine it's location
    setLocationRelativeTo(null);
    setVisible(true);
}

KeyListener is notoriously troublesome, you would better of using Key Bindings

Upvotes: 1

Related Questions