java循环写出多个jlabel,初学者Java的Netbeans:我如何显示循环jlabel?

I have looked on this site and nothing has really answered my question. This is what my code looks like:

// declare user input variables

int min, max;

//assign user input to min and max

min = Integer.parseInt(Min.getText ());

max = Integer.parseInt(Max.getText ());

//use for loop to display the values

for (int n = min; n<= max; n++){

System.out.println(Integer.toString(n));

Output.setText(Integer.toString(n));

}

and the System.out.println () yields the correct answer. for instance, the user inputs 2 and 9, it will say:

run:

2

3

4

5

6

7

8

9

but the jLabel I'm trying to set the text to, Output, only displays 9. I know his might be stupidly simple but hey, I'm a beginner. Any help would be appreciated.

解决方案

The answer "depends".

Do you want each number on a new line or appended to the end of the String. Do you want them displayed individually like a counter?

If you want the numbers display in sequence, then you could use something like this...

JLabel label = new JLabel();

int min = 0;

int max = 10;

StringBuilder sb = new StringBuilder(128);

for (int n = min; n <= max; n++) {

sb.append(n);

}

label.setText(sb.toString());

Which will output something like...

0ZCnK.png

Or if you wanted each number of a new line, you could use...

JLabel label = new JLabel();

int min = 0;

int max = 10;

StringBuilder sb = new StringBuilder(128);

sb.append("");

for (int n = min; n <= max; n++) {

System.out.println(Integer.toString(n));

sb.append(n).append("
");

}

sb.append("");

label.setText(sb.toString());

Which will output something like...

9tOj8.png

Now, if you want this, it would actually be easier to use a JTextArea and simply append each number to it...

JTextArea editor = new JTextArea(10, 10);

editor.setEditable(false);

int min = 0;

int max = 10;

StringBuilder sb = new StringBuilder(128);

for (int n = min; n <= max; n++) {

editor.append(Integer.toString(n) + "\n");

}

Which will output something like...

Cdfeo.png

Now, if you want to animate it, you're going to need to do things different, either using a javax.swing.Timer or SwingWorker

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值