gpt4 book ai didi

java - Java Swing 中的表

转载 作者:太空宇宙 更新时间:2023-11-04 13:07:33 24 4
gpt4 key购买 nike

我正在开发一个程序,它可以解析文本并打印如下输出

LS  1 -> 3
LS 2 -> 3
LS 3 -> 2
PRP itself -> 2
PRP it -> 5
DT all -> 7
DT All -> 11
DT no -> 9
DT a -> 77
NNP Milwaukee -> 2
NNP D65 -> 1
NNP STD -> 1
NNP Gimp -> 3
NNP Constitution -> 1

相反,我想要类似的东西

enter image description here

我尝试使用 JTable 3 个小时,但仍然无法弄清楚如何将文本排序到表中。请帮忙。

示例代码

public String getTagsList() throws IOException {
String output = "";
for (Map.Entry<String, Map<String, Integer>> entry : tagMap.entrySet()) {
String oa = entry.getKey();
Map<String, Integer> words = entry.getValue();
for (Map.Entry<String, Integer> entryWords : words.entrySet()) {
String ob = entryWords.getKey() + " -> " + entryWords.getValue();
output += oa + "\t" + ob + "\n";
}
}
return output;
}

还有

try {
if (cmd == cmdOpen) {
int code = chooser.showOpenDialog(myPane);
if (code == JFileChooser.APPROVE_OPTION) {
File selectedFile = chooser.getSelectedFile();
fileName = selectedFile.getName();
TagText tagText = new TagText(selectedFile.getAbsolutePath(), 4);
myPane.setText(tagText.getTagsList());
}
}
}

最佳答案

可以有数千种方法来做到这一点。这是我想到的一个..

首先,您可以将项目作为列添加到单独的列表中。并保留一个变量来跟踪列的最大大小。

    List<List<String>> columns = new ArrayList<>();
int maxColumnSize = 0;
for (Map.Entry<String, Map<String, Integer>> entry : tagMap.entrySet()) {
List<String> column = new ArrayList<>();
column.add(entry.getKey());
Map<String, Integer> words = entry.getValue();
for (Map.Entry<String, Integer> entryWords : words.entrySet()) {
String ob = entryWords.getKey() + " -> " + entryWords.getValue();
column.add(ob);
}
columns.add(column);
if (column.size() > maxColumnSize) {
maxColumnSize = column.size();
}
}

然后您可以逐行打印每一列,如下所示..

    String output = "";
for (int i = 0; i < maxColumnSize; i++) {
for (List<String> column : columns) {
String s = " ";
if(i<column.size()){
s = column.get(i);
}
output += s + "\t";
}
output += "\n";
}

这是一个示例代码。您可以编辑打印机制以使您的表格更加美观。 (例如:您可以使用java.util.Formatter来格式化您的String)

关于java - Java Swing 中的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34281059/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com