【问题标题】:how to get only the value of textfield into variable如何仅将文本字段的值放入变量中
【发布时间】:2012-09-20 14:17:29
【问题描述】:

您好,我正在尝试在 Java 中绘制对角线,但这无法正常工作..

“value”变量每次都在 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");
    }

}

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

【问题讨论】:

    标签: java swing awt paintcomponent graphic


    【解决方案1】:

    不要在paintComponent 方法中更改value 的值。相反,将其复制到 paintComponent 方法的另一个本地变量中,然后使用并更改 that 变量。这样,每次调用paintComponent(...) 时,它都不会重新设置 value 所持有的 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);
        }
    }
    

    【讨论】:

    • 即使进行了这些更改,我也得到了相同的结果.. 似乎它一直在做一个值 * 2。我应该做类似 localValue += Integer.ParseInt(textfield.getText());使值相同..
    【解决方案2】:

    为什么要修改 value 的值,而您已经有一个循环变量:

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

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

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

    注意:不要更改 paintpaintComponent、... 方法中的状态。您无法控制调用的次数和时间

    【讨论】:

    • @Reshad 通过不调整 paintComponent 方法中的 value 变量。否则,下次触发paintComponent 时,它仍将包含上一次方法调用的值,而不再是从用户输入中检索到的值。
    猜你喜欢
    • 1970-01-01
    • 2011-01-13
    • 2022-12-15
    • 1970-01-01
    • 2022-07-25
    • 2018-07-14
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多