简体   繁体   English

将 JLabel 文本设置为数字循环

[英]Setting JLabel text to a number loop

I am writing a simple Java application where the user provides two inputs;我正在编写一个简单的 Java 应用程序,其中用户提供两个输入; a starting number and an ending number.一个起始编号和一个结束编号。 Once a button is clicked, the application should display all numbers between the starting number and the ending number on the screen.单击按钮后,应用程序应在屏幕上显示起始编号和结束编号之间的所有数字。

Ex.前任。 (1 2 3 4 5) if starting = 1 and ending = 5 (1 2 3 4 5) 如果starting = 1ending = 5

Here is the loop I am using to output the numbers这是我用来输出数字的循环

Int starting = 1;
Int ending = 5;

for(starting; starting <= ending; starting++){
    //"Output" is a JLabel object
    Output.setText(starting);
}

I would expect this to set the content of Output to 1 2 3 4 5 .我希望这会将Output的内容设置为1 2 3 4 5 Though by the end of the loop, the content of Output is just the last number in the sequence (5 in this case).尽管在循环结束时, Output的内容只是序列中的最后一个数字(在本例中为 5)。

Could someone please explain why I am seeing this behavior?有人可以解释为什么我会看到这种行为吗?

You are overriding the text in the JLabel in every iteration.您将在每次迭代中覆盖 JLabel 中的文本。 That's why the JLabel always shows the last number.这就是为什么 JLabel 总是显示最后一个数字的原因。

Concatenate all the integers in a single string, then after the loop completes, set the text of the JLabel to be the concatenated string.连接单个字符串中的所有整数,然后在循环完成后,将 JLabel 的文本设置为连接字符串。

 String result = "";
    for (int starting = Integer.parseInt(Start.getText()); starting <= ending; starting++){
        result += starting;
    }
    output.setText(result);

Btw: you have syntax errors.顺便说一句:你有语法错误。

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

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