Java SwingWorker 未按预期工作

Java SwingWorker not working as expected

我正在编写一个程序,用于将名称与列表进行匹配。如果没有匹配,我会在 SQLite 数据库中查找名称,将名称信息提取到文本字段中,然后显示卡片(卡片布局)。当我 运行 this 时,我只得到了最后一个不匹配的信息。在研究这个问题时,我认为我可以使用 SwingWorker 来解决这个问题。我把我的 do-while 放在一个 SwingWorker class 中,并在我想显示信息的地方添加了一个 publish() 。我得到相同的结果,只显示最后一个不匹配。

以下是我的代码片段:

   public class processTeeTimes extends SwingWorker <Integer, String>
    {

        @Override
        protected Integer doInBackground() throws Exception
        {
       //   Process all tee times foursome at a time

            String memberGuest;                                     // Member or guest
            do                                                      // Process players in foursome
            {

                .
                .
                .


                    if (!firstOnGHIN())
                    {
                        System.out.print("No match - first (" + tsTime + "): ");
                        printGolfer();                      // Print no match
                        publish(golfer[0]);

                    }

                .
                .
                .

            }
            while (!EOF)


        }

        @Override
        protected void process(List<String> golferList)
        {
            for (int gIndex = 0; gIndex < golferList.size(); gIndex++)
            {
                textFieldRMLast.setText(golferList.get(gIndex));
                cards.show(panelCont, ROSTERMAINT); // Show roster maint card
            }
        }

        @Override
        protected void done()
        {
            .
            .
            .

            System.out.println("All done processing Tee Sheet");
        }

如有任何帮助,我们将不胜感激。

I get the same result, only the last mismatch is displaying.

因为您的代码似乎就是这样做的:

    @Override
    protected void process(List<String> golferList)
    {
        for (int gIndex = 0; gIndex < golferList.size(); gIndex++)
        {
            textFieldRMLast.setText(golferList.get(gIndex));
            cards.show(panelCont, ROSTERMAINT); // Show roster maint card
        }
    }

您正在将数据放入 JTextField,当遇到更多数据时,它会立即用新文本替换以前的文本。如果要显示多行数据,则应使用显示多行数据的组件,例如 JList 或 JTable。

如果您希望在查看 JTextField 中的数据之间有延迟,请考虑在 doInBackground() 方法中调用的 do-while 循环中放置一个 Thread.sleep(...)。不要在上面的这个for循环中放一个Thread.sleep,因为上面的代码是在Swing事件线程上调用的。

请注意,如果此答案不能回答您的问题,那么是的,您需要创建并 post 一个有效的 MCVE.