scrollComponentToVisible无法按预期运行

时间:2018-11-29 17:40:50

标签: codenameone

我正在构建一个基本的聊天应用程序,该应用程序的右侧是用于您自己的消息的文本框,左侧是用于其他参与者消息的文本框。每个消息都在Box Layout Y_Axis容器的一行中。 发布新消息后,我希望最新消息可见,因此我想在带有消息框(标签)的容器上使用scrollComponentToVisible。但是,无论我提供什么参数,它都只会向上滚动到容器的顶部。这意味着该容器是可滚动的,并且该命令执行了某些操作,但是它向上滚动,而不是向下滚动到我想要看到的内容。

代码段:

            // chat history
            Container chatHistory = new Container(new BoxLayout(BoxLayout.Y_AXIS));
            chatHistory.setScrollableY(true);
            hi.add(BorderLayout.CENTER, chatHistory);

            ...

            // send button and action event for sending message
            sendButton.addActionListener(e ->{

                chatHistory.add(FlowLayout.encloseRight(new Label(chatInput.getText(), null, "chatOwn"))); // TODO word wrap text
                chatInput.setText("");

                Label newMessage = new Label("auto response", null, "chatOther");
                chatHistory.add(FlowLayout.encloseLeftMiddle(newMessage));


                // this is where the magic should happen 
                chatHistory.scrollComponentToVisible(newMessage);
            });

我确实知道在滚动时需要将平滑滚动设置为false,但是将其保留在代码之外以使其尽可能短。

任何有关这里出问题的提示都将受到赞赏。

1 个答案:

答案 0 :(得分:1)

添加组件时,它的大小为0,0,大小为0,0。所以它的工作完全符合预期...

您需要重新验证(或设置布局动画),只有完成后才能滚动到可见的工作。重新验证是立即进行的,因此很容易,只需在重新验证之后使用callSerially()来推迟滚动。