【问题标题】:Tables in Java SwingJava Swing 中的表格
【发布时间】:2016-03-20 18:16:49
【问题描述】:

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

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

相反,我想要类似的东西

我尝试使用 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());
        }
    }
}

【问题讨论】:

  • 行之间的关系是什么?如果您按LS 列排序,将如何影响其他列?
  • 3小时不算长..!
  • 是的...对蜉蝣...
  • 行之间没有关系,如果它是一个LS,它应该属于一行。 @Ramesh-X:为什么有更多的人试图变得如此消极?每个人在他们的一生中都是菜鸟,我正在努力学习一些东西。我没有要求完整的代码。我只是想知道如何最好地完成它,以便我可以实施它。和平:)
  • 我想我弄错了。 LS 代表列表项标记,它打印出文件中的所有 LS 和出现次数。并且有 34 个不同的术语,如 LS。所以我想把它们列在一个表格中,标题在上面,内容在下面

标签: java swing for-loop dictionary


【解决方案1】:

有成千上万种方法可以做到这一点。这是我想到的。。

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

    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

【讨论】:

    猜你喜欢
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 2011-10-30
    相关资源
    最近更新 更多