为什么drawString不更新值?

时间:2014-03-27 03:00:09

标签: java draw paintcomponent

我正在绘制它(在paint方法中):

g.drawString("NumPipes: " + numPipes + "   " + "DeletedPipes: " + deletedPipes + "    moved: " + numMoved, 0 , 10);

输出以下方法中定义的值:

public void addPipe() {
    for (int i = 0; i < pipe.length; i++) {
        if (pipe[i] == null) {
            pipe[i] = new Pipe(this.width, (int) Math.random() * (this.height - 200));
            System.out.println("Pipe Added.");
            numPipes += 1;
        }
    }
}

public void deletePipe() {
    for (int i = 0; i < pipe.length; i++) {
        if (pipe[i] != null && pipe[i].returnX() <= 0) {
            pipe[i] = null;
            System.out.println("Pipe Deleted.");
            deletedPipes += 1;
        }
    }
}

public void movePipe(int speed) {
    for (int i = 0; i < pipe.length; i++) {
        if (pipe[i] != null) {
            pipe[i].move(speed);
            numMoved = numMoved + 1;
            System.out.println(numMoved);
        }
    }
}

现在当我检查控制台输出numMoved的值时,值正在增加/更新,但它们在JFrame中保持不变(参见下图,控制台显示{的值{1}} numMoved显示JFrame值。发生了什么/为什么这样做?

enter image description here

1 个答案:

答案 0 :(得分:0)

您似乎没有打电话给repaint,因此该组件不知道它应该更新值......

例如......

public void addPipe() {
    for (int i = 0; i < pipe.length; i++) {
        if (pipe[i] == null) {
            pipe[i] = new Pipe(this.width, (int) Math.random() * (this.height - 200));
            System.out.println("Pipe Added.");
            numPipes += 1;
        }
    }
    repaint();
}

现在,您可以在repaint之后放置numPipes += 1,但由于repaint的工作方式,它可能无法发挥作用......

这假设addPipe所属的类是某种组件,但您没有提供足够的信息来进行正确的诊断...