JavaFX disable button - 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.

Related

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

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();

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();
}
}

How to prevent firing ActionEvent when ComboBox value property is changed programmatically?

I'm working with ComboBox control and I want to do something easy with it. I want ComboBox to fire an ActionEvent when its value is changed during mouse click on the ComboBox dropdown list (This is automatically done). In the opposite side, I want ComboBox Not to fire ActionEvent when its value is changed programmatically (e.g. when using comboBox.getSelectionModel().selectFirst()).
Here is a simple code to demonstrate the problem:
#Override
public void start(Stage primaryStage) {
VBox vBox = new VBox();
ComboBox<String> comboBox = new ComboBox<>();
comboBox.setItems(FXCollections.observableArrayList("John", "Josh", "Mosh"));
comboBox.setOnAction(event -> {
System.out.println("Action");
});
Task<Void> task = new Task<Void>() {
#Override
protected Void call() throws Exception {
return null;
}
};
task.setOnSucceeded(e -> comboBox.getSelectionModel().select("John"));
new Thread(task).start();
vBox.getChildren().addAll(comboBox);
vBox.setPrefWidth(200);
vBox.setPrefHeight(200);
vBox.setAlignment(Pos.CENTER);
Scene scene = new Scene(vBox);
Stage stage = new Stage();
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
As you can see, ComboBox has a setOnAction method which should be invoked only when ComboBox value is changed by a mouse click on the dropdown list. Also, there is a Task that does some operations. (Those operations are omitted for code simplicity reasons). After the Task is completed successfully, the ComboBox's value changes and setOnAction method is invoked too, while the value should be changed without invoking setOnAction method. I don't know how to achieve this. Any useful suggestions or tips are greatly appreciated.
I have successfully used Slaw's approach to suppress event firing across multiple controls at once -
set up a boolean field
private boolean programmedAction = false;
in the programmatic method updating the control, set the flag first to suppress actions
private void someMethod(){
programmedAction = true;
// manipulate controls
programmedAction = false;
}
in the control related events, check the boolean before firing
private void someControlsAction(ActionEvent actionEvent) {
if (programmedAction) return;
// do regular action stuff
}

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);
}
}
}

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