【问题标题】:repaint only working after resize重绘仅在调整大小后工作
【发布时间】:2013-12-10 20:13:37
【问题描述】:

我想用下面的代码让一个球在屏幕上弹跳。问题是它只在我调整框架大小时移动。所以我的面板方法中有我的paintcomponent。当我的线程正在运行时,我会运行一个循环,在其中移动球、休眠线程并重新绘制。 只有当我调整框架大小时,球才会移动。 谁能帮帮我?

public class SpelPaneel extends JPanel {

    private JLabel spelLabel;
    private JPanel spelPaneel;
    private Image background;
    private Bal bal;

    public SpelPaneel() {
        spelPaneel = new JPanel();
        spelLabel = new JLabel("spel");
        add(spelLabel);
        try {
            background = ImageIO.read(new File("src/Main/images/background2.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        bal = new Bal(spelPaneel, 50, 50, 15);
        bal.start();
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(background, 0, 0, getWidth(), getHeight(), null);
        bal.teken(g, Color.red);
    }
}

class Bal extends Thread {

    private JPanel paneel;
    private int x, y, grootte;
    private int dx, dy;
    private boolean doorgaan;

    public Bal(JPanel paneel, int x, int y, int grootte) {
        this.paneel = paneel;
        this.grootte = grootte;
        this.x = x;
        this.y = y;
        dy = 2;
        doorgaan = true;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public void setX(int x) {
        this.x = x;
    }

    public void setY(int y) {
        this.y = y;
    }

    public void run() {
        while (doorgaan) {
            paneel.repaint();
            slaap(10);
            verplaats();
        }
    }

    public void teken(Graphics g, Color kleur) {
        g.setColor(kleur);
        g.fillOval(x, y, 15, 15);
    }

    public void verplaats() {
        if (x > 335 || x < 50) {
            dx = -dx;
        }
        if (y > 235 || y < 50) {
            dy = -dy;
        }

        x += dx;
        y += dy;
        setX(x);
        setY(y);
    }

    private void slaap(int millisec) {
        try {
            Thread.sleep(millisec);

        } catch (InterruptedException e) {
        }
    }
}

【问题讨论】:

  • 我注意到您没有对由一个线程读取并由另一个线程写入的变量进行同步。我建议你制作xy volatile
  • 您能否将启动Bal 线程的代码添加到您的问题中?
  • 现在添加了完整的代码,这个面板被添加到另一个类中。另一个类是卡片布局

标签: java multithreading swing


【解决方案1】:
spelPaneel = new JPanel(); //

您的 SpelPaneel 类扩展了 JPanel,因此无需创建另一个面板。上面这行代码只是在内存中创建了一个 JPanel,但没有做任何事情。

bal = new Bal(spelPaneel, 50, 50, 15);

然后你创建你的 Bal Thread 并将这个虚拟面板传递给它,然后尝试在这个虚拟面板上重新绘制。

我猜代码应该是:

bal = new Bal(this, 50, 50, 15);

因为“this”指的是您创建的 SeplPaneel 的实际实例。

【讨论】:

  • 非常感谢,这完成了这项工作。早该知道这一点。也感谢其他人的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-20
  • 1970-01-01
  • 2018-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多