简体   繁体   English

在JFrame中移动JPanel

[英]Move JPanel in JFrame

I'm looking to move a jpanel inside of a JFrame, and it won't seem to budge. 我想在JFrame中移动一个jpanel,它似乎不会让步。 I can set it's location in the paint() method, but it won't update in repaint. 我可以在paint()方法中设置它的位置,但它不会在重绘时更新。 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. “我可以在paint()方法中设置它的位置” - 严格来说,你不应该修改任何paint方法中任何组件的状态,事实上,你通过不调用super.paint破坏了paint链。 ,这将导致你没有其他问题的结束。

Instead, set the parent containers layout manager to null , you will now find that the component disappears. 相反,将父容器布局管理器设置为null ,您现在将发现该组件消失。 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 . 您应该重写paintComponent并调用super.paintComponent而不是覆盖paint Take a look at Performing Custom Painting for more details 有关更多详细信息,请参阅执行自定义绘画

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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