-1

您好,我正在尝试在 Java 中绘制对角线,但这不会像它应该的那样工作..

“值”变量每次都在 for 循环中更新,但它获取下一个值

例如,如果我插入一个 1,我会在控制台中使用 system.out.println(value) 得到这个:

2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304

但变量“值”必须包含我插入的值。我为此使用的代码你可以在下面找到

DrawLines line = new DrawLines();
int value = 0;
public void paintComponent(Graphics g) {

    super.paintComponent(g);

    int xPos = 0;
    int yPos = getHeight() - (getHeight() / 2);

    for(int aantalLines = 0; aantalLines < 10; aantalLines++ ) {
        line.drawLines(g, xPos, yPos + value, getWidth(), getHeight() - value );
        value += value;
        System.out.println(value);
        System.out.println(aantalLines);
    }

}

public void actionPerformed(ActionEvent e) {

    try {
        value = Integer.parseInt(tussenRuimte.getText());
        repaint();
    }
    catch(NumberFormatException err) {
        JOptionPane.showMessageDialog(null, "Number Format Error: Vul alles goed in s.v.p");
    }

}

问题是它不能像这样工作..有人可以解释我做错了什么以及如何解决这个问题吗?

4

2 回答 2

2

不要value在 paintComponent 方法中更改 from 的值。相反,将其复制到 paintComponent 方法的另一个本地变量中,然后使用和更改变量。这样,每次paintComponent(...)调用时,它都不会重新设置值所持有的 int。

例如,

public void paintComponent(Graphics g) {
    super.paintComponent(g);

    int xPos = 0;
    int yPos = getHeight() - (getHeight() / 2);
    int localValue = value;

    for(int aantalLines = 0; aantalLines < 10; aantalLines++ ) {
        line.drawLines(g, xPos, yPos + localValue, getWidth(), getHeight() - localValue );
        localValue += localValue;
        // System.out.println(value);
        // System.out.println(aantalLines);
    }
}
于 2012-09-28T17:11:39.080 回答
1

为什么要修改valuewhile 你已经有一个循环变量的值:

for(int aantalLines = 0; aantalLines < 10; aantalLines++ ) {
  line.drawLines(g, xPos,       yPos +        ((aantalLines + 1) * value), 
                    getWidth(), getHeight() - ((aantalLines + 1) * value) );
}

这应该归结为@Hovercraft 已经建议的内容。

如果这些解决方案都没有帮助,那么您可能在其他地方遇到了问题。

注意:不要更改paint, paintComponent, ... 方法中的状态。您无法控制调用它们的次数和时间

于 2012-09-28T17:44:07.927 回答