我将多个字符串存储在列表数组中,然后将它们输出到 JavaFX 场景中的文本区域。这是我希望输出的样子。请注意,无论字符数如何,我的字符串间隔是多么均匀。
acdd abc abcd abcd
ab abcd abcdf abcd
为了输出我的列表,我将其通过 for 循环并将“\n”附加到每一行。
for (String line : lines) {
sb.append(line).append("\n");
}
现在,如果我通过 println 打印 newStr ,它看起来很完美。
System.out.println(listStringJoin(newStr));
acdd abc abcd abcd
ab abcd abcdf abcd
但是,我的问题是当我将 newStr 添加或附加到 JavaFX 场景中的 textArea 时。 myTextArea.appendText(listStringJoin(newStr));
结果,无间隔输出。
acdd abc abcd abcd
ab abcd abcdf abcd
最佳答案
我会首先获取数组中最大的元素,然后向其他较小的元素添加空格。
这是一种从字符串数组生成均匀表格格式的方法:
public static String[] generateTable(ArrayList<String> lines){
// A list to store every single element individually
ArrayList<String> sl = new ArrayList<>();
int length = lines.get(0).split(" ").length; // Number of individual
// elements
// Create an array of every element individually
for (String line : lines) {
String[] sp = line.split(" ");
for (String semiChars : sp)
sl.add(semiChars);
}
// This controls iteration
int j = 1;
for (int i = 0; i < sl.size() / lines.size(); i++) {
int maxLength = 0; // Max length of character within that set
String fixStr = ""; // String with fixed spaces
// Determine maximum length from set
// Compares the element lengths in multiples. Something like:
// (element i, element i+length, element i+length+length.....)
while (j < sl.size()) {
fixStr = sl.get(i + j - 1);
if (maxLength < sl.get(i + j - 1).length())
maxLength = sl.get(i + j - 1).length();
j += length;
}
j = 1; // Ready for another loop
// Add spaces to match max length in set
while (j < sl.size()) {
fixStr = "";
// Gets elements in multiples (same as above loop)
if (sl.get(i + j - 1).length() < maxLength) {
fixStr = sl.get(i + j - 1);
while (fixStr.length() < maxLength)
fixStr += " ";
sl.set(i + j - 1, fixStr);
}
j += length;
}
j = 1; // Ready for another loop
}
// Time to create final array that is returned
String semiElement = ""; // Stores elements as sets of lines
String[] sortedArray = new String[lines.size()]; // The final Array
// Form expression and add it to final Array
for (int i = 0; i < lines.size(); i++) {
j = 0;
while (j < length) {
// Add as many spaces as you want between elements here
semiElement += (sl.get((i * length) + j) + " ");
j++;
}
sortedArray[i] = semiElement;
semiElement = "";
}
return sortedArray;
}
输入(字符串数组):
{ "line1 11111 asd ghdfigh asdi bbb 222",
"line2 2 asdasf gg weew bbb 666",
"line3 22222asdas as rte fhdfh ger 777",
"line4 asdsa 23 as wete f 8888888",
"line5 166 azzfffffffff gjj tyi btb 99000" };
输出:
line1 11111 asd ghdfigh asdi bbb 222
line2 2 asdasf gg weew bbb 666
line3 22222asdas as rte fhdfh ger 777
line4 asdsa 23 as wete f 8888888
line5 166 azzfffffffff gjj tyi btb 99000
关于java - 设置数组格式以将文本以表格格式附加到 TextField 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33978140/