Can you set icon to a Javafx Alert box? [duplicate] - javafx

I might be missing something very obvious, but I can't find out how to set the Icon for a Dialog component (ProgressDialog to be more precise). I know how to do that for a Stage:
this.primaryStage.getIcons().add(new Image(getClass().getResourceAsStream("/icon/Logo.png")));
But I don't find anything for the Dialog family. And somehow, setting the Stage Icon does not influence the Dialog Icon.
Thanks

There's an excellent tutorial here by Marco Jakob, where you can find not only how to use dialogs, but also how to solve your problem.
Both for the new dialogs (in JDK8u40 early versions or with openjfx-dialogs with JDK 8u25), or for those in ControlsFX, in order to set the icon of your dialog, you can use this solution:
Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow();
stage.getIcons().add(
new Image(this.getClass().getResource("<image>.png").toString()));
This code snippet shows how to use a ProgressDialog, from ControlsFX, and set an icon for the dialog:
#Override
public void start(Stage primaryStage) {
Service<Void> service = new Service<Void>() {
#Override protected Task<Void> createTask() {
return new Task<Void>() {
#Override protected Void call() throws InterruptedException {
updateMessage("Message . . .");
updateProgress(0, 10);
for (int i = 0; i < 10; i++) {
Thread.sleep(300);
updateProgress(i + 1, 10);
updateMessage("Progress " + (i + 1) + " of 10");
}
updateMessage("End task");
return null;
}
};
}
};
Button btn = new Button("Start Service");
btn.setOnAction(e -> {
ProgressDialog dialog = new ProgressDialog(service);
dialog.setTitle("Progress Dialog");
dialog.setHeaderText("Header message");
Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image(this.getClass().getResource("<image>.png").toString()));
service.start();
});
Scene scene = new Scene(new StackPane(btn), 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
}

Just Do like this:
Alert(AlertType.ERROR, "Erreur de connexion! Verifiez vos Identifiants",FINISH); //Cancel..
setTitle("XNotes FX Erreur");
stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("indiza/XnotesErrorIdz.png")); // To add an icon
showAndWait();
Here is the result
**My friends, is it computer science that we do? : No, we do crafts
**

You can easily use the icon of your application for the alert-icon by setting your application-window as owner of the alert box:
#FXML
Button buShow;
...
Alert alert = new Alert(AlertType.INFORMATION, "Nice Box.", ButtonType.CLOSE);
alert.initOwner(buShow.getScene().getWindow()); // Alert uses the Windows Icon
alert.show();

This is a method that I include in my JavaFX projects, simply calling this method and passing the Alert as a parameter will set both the title bar icon and the header graphic.
public class Msg {
public void showInfo(String title, String header, String message) {
Alert alertShowInfo = new Alert(Alert.AlertType.INFORMATION);
addDialogIconTo(alertShowInfo); //add icon and header graphic
alertShowInfo.setTitle(title);
alertShowInfo.setHeaderText(header);
alertShowInfo.setContentText(message);
alertShowInfo.showAndWait();
}
//this adds images to Alert
public void addDialogIconTo(Alert alert) {
// Add custom Image to Dialog's title bar
final Image APPLICATION_ICON = new Image("icon.png");
Stage dialogStage = (Stage) alert.getDialogPane().getScene().getWindow();
dialogStage.getIcons().add(APPLICATION_ICON);
// Add custom ImageView to Dialog's header pane.
final ImageView DIALOG_HEADER_ICON = new ImageView("icon.png");
DIALOG_HEADER_ICON.setFitHeight(48); // Set size to API recommendation.
DIALOG_HEADER_ICON.setFitWidth(48);
alert.getDialogPane().setGraphic(DIALOG_HEADER_ICON);
}
}
Then, in whatever class I wish to use the Alert, it will already have the customized icon and header graphic.
public static void main(String[] args){
Msg msg = new Msg();
// Alert will now include custom icon and header graphic.
msg.showInfo("Sucess!", "Program succeeded", "Now exiting program");
}

Just similar to any dialog, instead this is inside a button handler.
Alert alert = new Alert(
AlertType.WARNING,
"Alert message here.",
ButtonType.OK
);
alert.initOwner(((Button)event.getSource()).getScene().getWindow());
alert.setTitle("Alert window title");
alert.showAndWait();

Related

Key Listener in JavaFX that changes on button press

My controller class has a moveButton method that on button click moves the button to a new location. This works fine and is called by a number of buttons which do the same thing. I want to add a key listener so when a button has been clicked once, until a different button is clicked, the user can use the up arrow to move the button (ie call the same moveButton function). The below is how I have tried to implement it, I also tried putting the key listener in the initialize method but neither seem to be working. Any advice would be greatly appreciated!
public void moveButton(ActionEvent actionEvent) {
Button buttonPressed = (Button) actionEvent.getSource();
double newAnchor = getNewAnchor(AnchorPane.getBottomAnchor(buttonPressed)) // separate method that returns new anchor location
AnchorPane.setBottomAnchor(buttonPressed, newAnchor);
buttonPressed.getScene().setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
if(event.getCode() == KeyCode.UP){
moveButton(actionEvent);
}
}
});
}
Don't treat the events like data that you need to pass around. Use them as triggers to do work. Generally, don't write generic event handlers that are called from multiple events and multiple nodes. Write short event handlers that just call methods to do something, and pass them the minimum from the event that they need to do the job.
If you do this, then it changes your thinking about how all of this stuff works and then it's just plain old Java, with no magic. And it's simple:
public class MoveButton extends Application {
private Node activeButton;
private Pane pane;
#Override
public void start(Stage primaryStage) throws Exception {
pane = new Pane();
Scene scene = new Scene(pane, 1200, 800);
primaryStage.setScene(scene);
primaryStage.show();
Button button1 = new Button("Button 1");
Button button2 = new Button("Button 2");
button2.setTranslateX(80);
button1.setOnAction(evt -> buttonClick(button1));
button2.setOnAction(evt -> buttonClick(button2));
pane.getChildren().addAll(button1, button2);
pane.setOnKeyPressed(evt -> moveButton(evt.getCode()));
}
private void moveButton(KeyCode keyCode) {
switch (keyCode) {
case UP -> activeButton.setTranslateY(activeButton.getTranslateY() - 30);
case RIGHT -> activeButton.setTranslateX(activeButton.getTranslateX() + 30);
case DOWN -> activeButton.setTranslateY(activeButton.getTranslateY() + 30);
case LEFT -> activeButton.setTranslateX(activeButton.getTranslateX() - 30);
}
}
private void buttonClick(Node button) {
activeButton = button;
pane.requestFocus();
}
}

JavaFX custom dialog set Layout of node

We created a Custom Dialog without an FXML file. We are using JavaFX 8.
The dialog loads and functions as expected but we can not move the Buttons and the TextField to enhance the styling.
We have tried to use tf.setLayoutY(50) this has no effect.
We used this tf.setPromptText("This Works ?") and it works.
We would rather not use css to accomplish this styling.
And we will consider a FXML file if we can keep the two event handlers that force data to be entered in the TextField.
So the question is: How to style this Custom Dialog?
The code is a mess as it includes some concepts we tried:
public void CustomDialog() {
Dialog dialog = new Dialog<>();
dialog.setResizable(false);
final Window window = dialog.getDialogPane().getScene().getWindow();
stage = (Stage) window;
stage.setMinHeight(600);
stage.setMinWidth(400);
TextField tf = new TextField();
tf.setLayoutX(10);
tf.setLayoutY(50);
dialog.getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);
dialog.getDialogPane().getChildren().add(tf);
dialog.getDialogPane().setContent(tf);
// Create an event filter that consumes the action if the text is empty
EventHandler<ActionEvent> filter = event -> {
if (tf.getText().isEmpty()) {
event.consume();
}
};
// lookup the buttons
ButtonBase okButton = (Button) dialog.getDialogPane().lookupButton(ButtonType.OK);
Button cancelButton = (Button) dialog.getDialogPane().lookupButton(ButtonType.CANCEL);
// add the event-filter
okButton.addEventFilter(ActionEvent.ACTION, filter);
cancelButton.addEventFilter(ActionEvent.ACTION, filter);
stage.setOnCloseRequest(event -> {
if (tf.getText().isEmpty()) {
event.consume();
}
}
//Scene scene = new Scene(root);
//dialogStage.setScene(scene);
dialog.initModality(Modality.APPLICATION_MODAL);
//dialogStage.setAlwaysOnTop(true);
//dialogStage.setResizable(false);
tf.setPromptText("This Works ?");
tf.requestFocus();// This does not work
dialog.showAndWait();
}
Grendel we enhanced your answer so anyone who comes by and sees the code you posted in your question will understand as you said it was a mess
Your posted answer was real old school but less work perhaps than building a FXML file
Besides it is good to know some old school tricks
public void NewDialog(){
Label lblAmt = new Label("Enter Amount");
Button btnOK = new Button("OK");
TextField txtAmt = new TextField();
AnchorPane secondaryLayout = new AnchorPane();
secondaryLayout.setStyle("-fx-border-color:red;-fx-border-width:10px; -fx-background-color: lightblue;");
secondaryLayout.getChildren().addAll(lblAmt,btnOK,txtAmt);
lblAmt.setLayoutX(30);
lblAmt.setLayoutY(30);
txtAmt.setLayoutX(164);
txtAmt.setLayoutY(25);
txtAmt.setMaxWidth(116);
btnOK.setLayoutX(190);
btnOK.setLayoutY(100);
btnOK.setStyle("-fx-font-size: 18px;-fx-font-weight: bold;");
lblAmt.setStyle("-fx-font-size: 18px;-fx-font-weight: bold;");
txtAmt.setStyle("-fx-font-size: 18px;-fx-font-weight: bold;");
Scene secondScene = new Scene(secondaryLayout, 300, 180);
EventHandler<ActionEvent> filter = event -> {
if(txtAmt.getText().isEmpty()) {
event.consume();
}
};
// New window (Stage)
Stage newWindow = new Stage();
newWindow.initStyle(StageStyle.UNDECORATED);
//newWindow.initModality(Modality.APPLICATION_MODAL);
newWindow.setResizable(false);
newWindow.setTitle("Second Stage");
newWindow.setScene(secondScene);
btnOK.addEventHandler(ActionEvent.ACTION,filter);
btnOK.setOnAction(evt -> {
String str = txtAmt.getText();
System.out.println("################ str "+str);
if(txtAmt.getText().equals("")) {
evt.consume();
txtAmt.requestFocus();
}else{
newWindow.close();
}
});
newWindow.setOnCloseRequest(event -> {
if(txtAmt.getText().isEmpty()) {
event.consume();
}
});
txtAmt.requestFocus();
newWindow.showAndWait();
}

Getting webpage opened in another tab from hyperlink of current webpage in webview of javafx browser

I have developed a very simplified but fully functional JavaFX web browser for illustrating what I want to ask. Here follows the source code.
public class OpenInNewTab extends Application {
#Override
public void start(Stage primaryStage)
{
TabPane tabPane = new TabPane();
WebView webView = new WebView();
Tab tab = new Tab("Home Tab");
tab.setContent(webView);
tabPane.getTabs().add(tab);
webView.getEngine().load("https://www.google.co.in/?gws_rd=ssl#q=javafx");
BorderPane root = new BorderPane();
root.setTop(tabPane);
Scene scene = new Scene(root, 600, 339);
primaryStage.setTitle("Basic browser");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args)
{
launch(args);
} }
This browser loads a web page from this link. I want that when I click on any of the search results, the clicked hyperlink should open in new tab adjacent to the existing "Home tab".
After searching on the internet extensively, I reached nowhere.
Please help me with relevant code. Thanks.
First of all, you need to find a way to handle all outgoing click events on the displayed page. I've made a helper method to achieve that. It creates an event listener for each link, clicking on which will open a new tab.
private void handleUrls(Document doc) {
NodeList links = doc.getElementsByTagName("a");
for (int i = 0; i < links.getLength(); i++) {
EventTarget eventTarget = (EventTarget) links.item(i);
String link = links.item(i).toString();
eventTarget.addEventListener("click", e -> {
WebView webView = new WebView();
alterWebView(webView);
Tab tab = new Tab(link);
tab.setContent(webView);
tab.setClosable(true);
webView.getEngine().load(link);
tabPane.getTabs().add(tab);
e.preventDefault();
}, false);
}
}
You may want to set a better name for your tab... I've used a link as a makeshift solution, but it's long and messy.
webView.getEngine().load(link);
The alterWebView referenced above is another helper function. It's responsible for tracking the loading progress. Once the Worker does nothing, it will add listeners to all urls.
private void alterWebView(WebView webView) {
WebEngine engine = webView.getEngine();
Worker worker = engine.getLoadWorker();
worker.stateProperty().addListener((oldVal, newVal, o) -> {
if (newVal.equals(State.RUNNING)) {
handleUrls(engine.getDocument());
}
});
}
So basically, the logic behind the code above is as follows:
We track our WebEngine's State until the page is fully loaded and then we add event listeners to every url.
These listeners, when invoked, will create a new WebView, handle it accordingly, and add it to the TabPane inside a new Tab.
And here's the complete, working example based on your code:
public class JavaFXTest extends Application {
private TabPane tabPane;
#Override
public void start(Stage primaryStage) {
tabPane = new TabPane();
WebView webView = new WebView();
alterWebView(webView);
Tab tab = new Tab("Home Tab");
tab.setContent(webView);
tab.setClosable(true);
tabPane.getTabs().add(tab);
webView.getEngine().load("https://www.google.co.in/?gws_rd=ssl#q=javafx");
BorderPane root = new BorderPane();
root.setTop(tabPane);
Scene scene = new Scene(root, 600, 339);
primaryStage.setTitle("Basic browser");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
private void alterWebView(WebView webView) {
WebEngine engine = webView.getEngine();
Worker worker = engine.getLoadWorker();
worker.stateProperty().addListener((oldVal, newVal, o) -> {
if (newVal.equals(State.RUNNING)) {
handleUrls(engine.getDocument());
}
});
}
private void handleUrls(Document doc) {
NodeList links = doc.getElementsByTagName("a");
for (int i = 0; i < links.getLength(); i++) {
EventTarget eventTarget = (EventTarget) links.item(i);
String link = links.item(i).toString();
eventTarget.addEventListener("click", e -> {
WebView webView = new WebView();
alterWebView(webView);
Tab tab = new Tab(link);
tab.setContent(webView);
tab.setClosable(true);
webView.getEngine().load(link);
tabPane.getTabs().add(tab);
e.preventDefault();
}, false);
}
}
}

JavaFX disable button

I'm writing a program in netbeans with javaFX
The view has several buttons in it with some bad buttons(like bombs is minesweeper), I'm trying to freeze the program when a bad button is pushed but i don't find how to do it
thanks!
There are various solutions to your problem. 2 among them are simply ignoring the action event or disabling the buttons like this:
public class ButtonAction extends Application {
final BooleanProperty buttonActionProperty = new SimpleBooleanProperty();
public static void main(String[] args) {
Application.launch(args);
}
#Override
public void start(Stage primaryStage) {
FlowPane root = new FlowPane();
CheckBox checkBox = new CheckBox( "Enabled");
checkBox.setSelected(true);
// solution 1: check if action is allowed and process it or not
buttonActionProperty.bind( checkBox.selectedProperty());
Button button = new Button( "Click Me");
button.setOnAction(e -> {
if( buttonActionProperty.get()) {
System.out.println( "Allowed, processing action");
} else {
System.out.println( "Not allowed, no action");
}
});
// solution 2: remove comments to activate the code
// button.disableProperty().bind(buttonActionProperty.not());
root.getChildren().addAll(checkBox, button);
primaryStage.setScene(new Scene(root, 600, 200));
primaryStage.show();
}
}
Add a ROOT typed event filter that consumes all kind of events (mouse, keyboard etc.)
btnThatHasHiddenMine.setOnAction(( ActionEvent event ) ->
{
System.out.println("Ohh no! You just stepped over the mine!");
getGameboardPane().addEventFilter( EventType.ROOT, Event::consume );
});
Add the filter to your GameboardPane only, since we don't want to freeze other part of the app.

How to create a modal window in JavaFX 2.1

I can't figure out how to create a modal window in JavaFX. Basically I have file chooser and I want to ask the user a question when they select a file. I need this information in order to parse the file, so the execution needs to wait for the answer.
I've seen this question but I've not been able to find out how to implement this behavior.
In my opinion this is not good solution, because parent window is all time active.
For example if You want open window as modal after click button...
private void clickShow(ActionEvent event) {
Stage stage = new Stage();
Parent root = FXMLLoader.load(
YourClassController.class.getResource("YourClass.fxml"));
stage.setScene(new Scene(root));
stage.setTitle("My modal window");
stage.initModality(Modality.WINDOW_MODAL);
stage.initOwner(
((Node)event.getSource()).getScene().getWindow() );
stage.show();
}
Now Your new window is REALY modal - parent is block.
also You can use
Modality.APPLICATION_MODAL
Here is link to a solution I created earlier for modal dialogs in JavaFX 2.1
The solution creates a modal stage on top of the current stage and takes action on the dialog results via event handlers for the dialog controls.
JavaFX 8+
The prior linked solution uses a dated event handler approach to take action after a dialog was dismissed. That approach was valid for pre-JavaFX 2.2 implementations. For JavaFX 8+ there is no need for event handers, instead, use the new Stage showAndWait() method. For example:
Stage dialog = new Stage();
// populate dialog with controls.
...
dialog.initOwner(parentStage);
dialog.initModality(Modality.APPLICATION_MODAL);
dialog.showAndWait();
// process result of dialog operation.
...
Note that, in order for things to work as expected, it is important to initialize the owner of the Stage and to initialize the modality of the Stage to either WINDOW_MODAL or APPLICATION_MODAL.
There are some high quality standard UI dialogs in JavaFX 8 and ControlsFX, if they fit your requirements, I advise using those rather than developing your own. Those in-built JavaFX Dialog and Alert classes also have initOwner and initModality and showAndWait methods, so that you can set the modality for them as you wish (note that, by default, the in-built dialogs are application modal).
You can create application like my sample. This is only single file JavaFX application.
public class JavaFXApplication1 extends Application {
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
Stage stage;
stage = new Stage();
final SwingNode swingNode = new SwingNode();
createSwingContent(swingNode);
StackPane pane = new StackPane();
pane.getChildren().add(swingNode);
stage.initModality(Modality.APPLICATION_MODAL);
stage.setTitle("Swing in JavaFX");
stage.setScene(new Scene(pane, 250, 150));
stage.show();
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
private void createSwingContent(final SwingNode swingNode) {
SwingUtilities.invokeLater(() -> {
try {
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
JasperDesign jasperDesign = JRXmlLoader.load(s + "/src/reports/report1.jrxml");
String query = "SELECT * FROM `accounttype`";
JRDesignQuery jrquery = new JRDesignQuery();
jrquery.setText(query);
jasperDesign.setQuery(jrquery);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
JasperPrint JasperPrint = JasperFillManager.fillReport(jasperReport, null, c);
//JRViewer viewer = new JRViewer(JasperPrint);
swingNode.setContent(new JRViewer(JasperPrint));
} catch (JRException ex) {
Logger.getLogger(AccountTypeController.class.getName()).log(Level.SEVERE, null, ex);
}
});
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}

Resources