gpt4 book ai didi

java - 如何使 JavaFX Web 浏览器显示警报和确认消息

转载 作者:行者123 更新时间:2023-11-30 06:59:07 25 4
gpt4 key购买 nike

我的 java web 浏览器不显示 alert("message");并确认(“消息”);要么,我通常使用 c# web 浏览器组件,它工作得很好,但我是新手。

public void  openPage(String url){
JFXPanel jfxPanel = new JFXPanel();
JFrame frame = new JFrame("");
frame.add(jfxPanel);
Platform.runLater(() -> {
WebView webView = new WebView();
jfxPanel.setScene(new Scene(webView));
webView.getEngine().load(url);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}

最佳答案

对于alert,注册一个onAlert handler与网络引擎。对于确认,注册一个confirmHandler与网络引擎。请参阅 WebEngine documentation 的“用户界面回调”部分.

这是一个简单的例子:

import java.util.Optional;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.layout.BorderPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class WebViewWithAlertAndConfirm extends Application {

private WebEngine engine;

@Override
public void start(Stage primaryStage) {
WebView webView = new WebView();
engine = webView.getEngine();

engine.setOnAlert(event -> showAlert(event.getData()));
engine.setConfirmHandler(message -> showConfirm(message));

String content =
"<html>"
+ "<head>"
+ "<script language='javascript'>"
+ "function doConfirm() {"
+ " var accepted = confirm('Are you sure?');"
+ " if (accepted) {"
+ " document.getElementById('result').innerHTML = 'Accepted';"
+ " } else {"
+ " document.getElementById('result').innerHTML = 'Declined';"
+ " }"
+ "}"
+ "</script>"
+ "<body>"
+ "<div><button onclick='alert(\"This is an alert!\")'>Show alert</button>"
+ "<button onclick='doConfirm()'>Confirm</button>"
+ "</div>"
+ "<div id='result'/>"
+ "</body>"
+ "</html>";

engine.loadContent(content);

primaryStage.setScene(new Scene(new BorderPane(webView)));
primaryStage.show();
}

private void showAlert(String message) {
Dialog<Void> alert = new Dialog<>();
alert.getDialogPane().setContentText(message);
alert.getDialogPane().getButtonTypes().add(ButtonType.OK);
alert.showAndWait();
}

private boolean showConfirm(String message) {
Dialog<ButtonType> confirm = new Dialog<>();
confirm.getDialogPane().setContentText(message);
confirm.getDialogPane().getButtonTypes().addAll(ButtonType.YES, ButtonType.NO);
boolean result = confirm.showAndWait().filter(ButtonType.YES::equals).isPresent();

// for debugging:
System.out.println(result);

return result ;
}

public static void main(String[] args) {
launch(args);
}
}

关于java - 如何使 JavaFX Web 浏览器显示警报和确认消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31880186/

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