简体   繁体   中英

Move JPanel in JFrame

I'm looking to move a jpanel inside of a JFrame, and it won't seem to budge. I can set it's location in the paint() method, but it won't update in repaint. Please help! Here is my code:

public void paint(Graphics g) {
    g.drawImage(playerImg, x, 50, null);
    this.setLocation(x, 50);
}

public void update() {
    this.repaint();
}


public void keyPressed(KeyEvent key) {
    if(key.getKeyCode() == KeyEvent.VK_UP) {
        x = x + 50;
        System.out.println("e");
        update();
    }
}

"I can set it's location in the paint() method" - Don't, seriously, you should never modify the state of any component within any paint method, in fact, you've broken the paint chain by not calling super.paint , which is going to cause you no end of other problems.

Instead, set the parent containers layout manager to null , you will now find that the component disappears. This is because the layout manager is responsible for setting the size and position of the component, which you will have to take over control of.

Instead of overriding paint you should be overriding paintComponent and calling super.paintComponent . Take a look at Performing Custom Painting for more details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM