java在Joptionpane中显示多行?
嗨,我是这个论坛的新成员,也是java的新手,我需要一些关于java入门作业的帮助。我做了大部分的逻辑。问题是要编写一个程序,显示从100到1000的所有数字,每行10个,可以被5和6整除。数字之间只有一个空格。我的教授想把它放在Joptionpane窗口中。当我尝试这样做时,窗口中只会弹出一个答案。如何使我的答案在一行中显示十个,在一个窗口中用一个空格隔开?我的教授希望我们使用一个转义函数来显示答案的行
public class FindFactors {
public static void main(String[] args) {
String message = "";
final int NumbersPerLine = 10; // Display 10 numbers per line
int count = 0; // Count the number of numbers divisible by 5 and 6
// Test all numbers from 100 to 1,000
for (int i = 100; i <= 1000; i++) {
// Test if number is divisible by 5 and 6
message = message + " " + i;
count++;
if (count == 10) {
message = message + "\r\n";
count = 0;
}
if (i % 5 == 0 && i % 6 == 0) {
count++; // increment count
// Test if numbers per line is 10
if (count % NumbersPerLine == 0)
JOptionPane.showMessageDialog(null, i);
else
JOptionPane.showMessageDialog(null, (i + " "));
}
}
}
}
# 1 楼答案
A
JOptionPane
能够显示图像、文本或任何其他组件,对于这种特殊情况,您可能需要创建自己的JPanel
,将每一行数字添加到JLabel
中,然后将JLabel
添加到其中上述程序的输出看起来像(被裁剪或太高):
# 2 楼答案
请参阅下面的方法,对代码稍加修改,即可获得所需的输出