ventana sirve showmessagedialog showinputdialog showconfirmdialog que personalizar para mostrar mensaje emergente ejemplos java javafx javafx-8 controlsfx

java - sirve - personalizar joptionpane



controles ¿diálogos en desuso para qué? (2)

Los Dialogs clase ControlsFX están marcados como obsoletos.

¿Qué usar en su lugar?


Ahora, con java 8 update 60, incluso el uso de una versión anterior no obsoleta de controlsfx no funciona. Por lo tanto, la solución está utilizando la API de diálogo nativa de javafx incluida en la actualización 40 de java 8 (no necesita librerías de terceros). No son tan sencillas y están llenas de funciones como los controles fx. Pero para una codificación más rápida, puedes crear una clase contenedora, como esta que hice:

package br.atualy.devolucaodevenda.util; import javafx.scene.control.*; import javafx.scene.control.Label; import javafx.scene.control.TextArea; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.GridPane; import javafx.scene.layout.Priority; import javafx.stage.StageStyle; import java.awt.*; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class FxDialogs { public static void showInformation(String title, String message) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.initStyle(StageStyle.UTILITY); alert.setTitle("Information"); alert.setHeaderText(title); alert.setContentText(message); alert.showAndWait(); } public static void showWarning(String title, String message) { Alert alert = new Alert(Alert.AlertType.WARNING); alert.initStyle(StageStyle.UTILITY); alert.setTitle("Warning"); alert.setHeaderText(title); alert.setContentText(message); alert.showAndWait(); } public static void showError(String title, String message) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.initStyle(StageStyle.UTILITY); alert.setTitle("Error"); alert.setHeaderText(title); alert.setContentText(message); alert.showAndWait(); } public static void showException(String title, String message, Exception exception) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.initStyle(StageStyle.UTILITY); alert.setTitle("Exception"); alert.setHeaderText(title); alert.setContentText(message); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); exception.printStackTrace(pw); String exceptionText = sw.toString(); Label label = new Label("Details:"); TextArea textArea = new TextArea(exceptionText); textArea.setEditable(false); textArea.setWrapText(true); textArea.setMaxWidth(Double.MAX_VALUE); textArea.setMaxHeight(Double.MAX_VALUE); GridPane.setVgrow(textArea, Priority.ALWAYS); GridPane.setHgrow(textArea, Priority.ALWAYS); GridPane expContent = new GridPane(); expContent.setMaxWidth(Double.MAX_VALUE); expContent.add(label, 0, 0); expContent.add(textArea, 0, 1); alert.getDialogPane().setExpandableContent(expContent); alert.showAndWait(); } public static final String YES = "Yes"; public static final String NO = "No"; public static final String OK = "OK"; public static final String CANCEL = "Cancel"; public static String showConfirm(String title, String message, String... options) { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.initStyle(StageStyle.UTILITY); alert.setTitle("Choose an option"); alert.setHeaderText(title); alert.setContentText(message); //To make enter key press the actual focused button, not the first one. Just like pressing "space". alert.getDialogPane().addEventFilter(KeyEvent.KEY_PRESSED, event -> { if (event.getCode().equals(KeyCode.ENTER)) { event.consume(); try { Robot r = new Robot(); r.keyPress(java.awt.event.KeyEvent.VK_SPACE); r.keyRelease(java.awt.event.KeyEvent.VK_SPACE); } catch (Exception e) { e.printStackTrace(); } } }); if (options == null || options.length == 0) { options = new String[]{OK, CANCEL}; } List<ButtonType> buttons = new ArrayList<>(); for (String option : options) { buttons.add(new ButtonType(option)); } alert.getButtonTypes().setAll(buttons); Optional<ButtonType> result = alert.showAndWait(); if (!result.isPresent()) { return CANCEL; } else { return result.get().getText(); } } public static String showTextInput(String title, String message, String defaultValue) { TextInputDialog dialog = new TextInputDialog(defaultValue); dialog.initStyle(StageStyle.UTILITY); dialog.setTitle("Input"); dialog.setHeaderText(title); dialog.setContentText(message); Optional<String> result = dialog.showAndWait(); if (result.isPresent()) { return result.get(); } else { return null; } } }

Para utilizar los diálogos:

FxDialogs.showInformation("Hi", "Good Morning y''all!"); if (FxDialogs.showConfirm("Choose one baby!", "Can i ask you a question?", FxDialogs.YES, FxDialogs.NO).equals(FxDialogs.YES)) { FxDialogs.showWarning(null, "Pay attention to my next question!"); String answer = FxDialogs.showTextInput("Are you a pink elephant disguised as a flying pig?", "Tell me!", "No"); FxDialogs.showError(null, "You should not have said " + answer + "!"); FxDialogs.showException("Now i''m angry", "I''m going home...", new RuntimeException("Exception caused by angry dinossaurs")); }


Esta publicación del blog lo explica todo:

http://fxexperience.com/2014/09/announcing-controlsfx-8-20-7/

Esta versión se ha estado elaborando desde que se lanzó 8.0.6 el 29 de mayo, básicamente cuatro meses. Esto no es típico de nosotros (normalmente tenemos versiones mucho más rápidas), pero tanto Eugene como yo nos distrajimos en una tarea importante: elevar la API de los cuadros de diálogo de ControlsFX a la próxima versión de JavaFX (aparecerá en JavaFX 8u40 , aunque la API es muy diferente de lo que se ve en ControlsFX 8.0.6). El resultado final es que iteramos a través de un montón de trabajo de diseño de API (ver RT-12643) y nada de eso benefició a ControlsFX, pero nos llevó todo nuestro tiempo.

Una vez que se completaron los diálogos de JavaFX 8u40 API (que fue solo a mediados de agosto), desarrollamos un plan sobre cómo proceder con los diálogos de ControlsFX. En esencia, no creíamos que fuera prudente mantener una API de diálogos en ControlsFX que fuera tan diferente a lo que se incluirá en JavaFX 8u40. Por lo tanto, el plan que desarrollamos fue desaprobar la antigua API de ControlsFX, unir la API de diálogos de JavaFX en un nuevo proyecto llamado openjfx-dialogs, y recrear las características adicionales que incluye ControlsFX (pero carecen de JavaFX) usando la nueva API (Esto incluye diálogos como progreso, selector de fuente, enlace de comando, inicio de sesión, etc.).