gpt4 book ai didi

java - 按下按钮并发送消息(Spring Boot 和 Vaadin)

转载 作者:行者123 更新时间:2023-12-01 19:32:31 25 4
gpt4 key购买 nike

我创建了一个聊天,效果很好。仅当我左键单击“发送”按钮时才会发送消息。我想简化使用。如何通过键盘上的“Enter”按钮发送消息?聊天工作没有错误,一切似乎都很好。只剩下这个任务了,这个问题怎么解决呢?

enter image description here

主视图

@StyleSheet("frontend://styles/styles.css")
@Route
@PWA(name = "Vaadin Chat", shortName = "Vaadin Chat")
@Push
public class MainView extends VerticalLayout {
private final UnicastProcessor<Message> publisher;
private final Flux<Message> messages;
private String username;

@Autowired
private RestService restService;

public MainView(UnicastProcessor<Message> publisher,
Flux<Message> messages) {
this.publisher = publisher;
this.messages = messages;

addClassName("main-view");
setSizeFull();
setDefaultHorizontalComponentAlignment(Alignment.CENTER);

H1 header = new H1("Vaadin Chat");
header.getElement().getThemeList().add("dark");

add(header);

askUsername();
}


private void askUsername() {
HorizontalLayout layout = new HorizontalLayout();
TextField usernameField = new TextField();
Button startButton = new Button("Start chat");

layout.add(usernameField, startButton);

startButton.addClickListener(click -> {
username = usernameField.getValue();
remove(layout);
showChat();
});

add(layout);
}

private void showChat() {
MessageList messageList = new MessageList();

add(messageList, createInputLayout());
expand(messageList);

List<Message> lasts = restService.getLast();
for (Message message : lasts)
messageList.add(new Paragraph(message.getFrom() + ": " + message.getMessage()));


messages.subscribe(message -> {
getUI().ifPresent(ui ->
ui.access(() ->
messageList.add(
new Paragraph(message.getFrom() + ": " +
message.getMessage())
)
));

restService.saveMessage(message);
});
}

private Component createInputLayout() {
HorizontalLayout layout = new HorizontalLayout();
layout.setWidth("100%");

TextField messageField = new TextField();
Button sendButton = new Button("Send");
sendButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
sendButton.addClickShortcut(Key.ENTER).listenOn(messageField);

layout.add(messageField, sendButton);
layout.expand(messageField);

sendButton.addClickListener(click -> {
publisher.onNext(new Message(username, messageField.getValue()));
messageField.clear();
messageField.focus();
});
messageField.focus();

return layout;
}

}

最佳答案

从 Vaadin 13 开始,您可以为按钮添加点击快捷方式:someButton.addClickShortcut(someKey)。要限制监听器的范围,使其仅在文本字段获得焦点时使用react,您可以使用 listenOn 对其进行补充。

这就是您的情况所需要的:

sendButton.addClickShortcut(Key.ENTER).listenOn(messageField);

关于java - 按下按钮并发送消息(Spring Boot 和 Vaadin),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59168746/

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