JFXDialog close on KeyCode.Enter, MouseEvent.Click - button

When i call JFXDialog, the dialog appear with message and button, all beautiful, than i can close it by pressing the button, but i can not close it by using key event on KeyCode.Enter
JFXDialog is control unit of JFoenix in SceneBuilder.
I have used different methods of events, but i don't have succes to close the dialog.
Can anybody help me to solve the problem?
I use soft and machine:
JavaFx, SceneBuilder
Eclipse IDE for Java Developers Version: 2019-12 (4.14.0)
JDK 10.0.2
Setting part:
//create button
JFXButton button = new JFXButton("Hello there!");
//create message layout
JFXDialogLayout dialogLayout = new JFXDialogLayout();
//control dialog
JFXDialog dialog = new JFXDialog(rootPane, dialogLayout,
JFXDialog.DialogTransition.TOP);
dialogLayout.setHeading(new Label("text"));
dialogLayout.setBody(new Text("text"));
dialogLayout.setActions(button);
button.addEventHandler(MouseEvent.MOUSE_CLICKED, (e) ->{
dialog.close();
});
Below are 2 examples of event methods that i have tried to use.
Event part:
//first method
dialogLayout.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent k) {
if (k.getCode().equals(KeyCode.ENTER)) {
button.fire();
}
}
});
//second method
button.addEventHandler(KeyEvent.KEY_PRESSED, event2 -> {
if(event2.getCode() == KeyCode.ENTER) {
button.fire();
event2.consume();
}
});
dialog.show();

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

How to make all buttons having ActionEvent handler handle Enter key in JavaFX?

I have about 50 buttons in my application. For all buttons I created handler this way:
#FXML
protected void handleFooButtonActionEvent(ActionEvent actionEvent) {
...
}
This way user can press buttons using mouse left button or Space key. However, it is normal practice (as I know) to allow user press button using Enter key. Is it possible to make all buttons having ActionEvent handler (see above) handle also Enter key in JavaFX, for example if we have reference to Stage stage, Scene scene or Parent root?
You can configure the Scene to do it:
scene.getAccelerators().put(
KeyCombination.valueOf("Enter"), () -> {
Node focusOwner = scene.getFocusOwner();
if (focusOwner instanceof Button) {
((Button) focusOwner).fire();
}
});
You can also do it with an event handler:
scene.addEventHandler(KeyEvent.KEY_PRESSED, e -> {
if (e.getCode() == KeyCode.ENTER) {
Node focusOwner = scene.getFocusOwner();
if (focusOwner instanceof Button) {
((Button) focusOwner).fire();
}
}
});
Normally I’d agree with James_D that changing the standard behavior of buttons is not a good idea, but I’m finding that all GTK applications allow Enter to trigger a button press, as does Firefox as you’ve mentioned.

JavaFX Cursor wait while loading new anchorPane

I am trying to load a new anchorPane in the existing scene by removing the old anchorPane.Now i need to show the user that loading cursor and the action performed by the user should not happen(like button click or key press).
I have used but Cursor.WAIT but still the action can be performed.
anchorPane.getScene().SetCursor(Cursor.WAIT);
HomeController controller=new HomeController(stage,anchorPane);
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/fxml/home.fxml"));
loader.setController(controller);
Parent root = null;
try {
root=(Parent) loader.load();
} catch (IOException e) {
LOGGER.error("Message is " + e);
e.printStackTrace();
}
anchorPane.getChildren().remove(0);
anchorPane.getChildren().add(root);
I have added Cursor.WAIT before this code.but i doesn't work.
Cursor.WAIT change only the icon of your cursor but it doesn't prevent you to interact with your view. If you want to prevent an user to interact with your view your could disable the elements like btn.setEnabled(false).
To show the user that you are peforming some background actions and he/she should wait until it's complete use tasks and dialogs.
Task task = new Task(new Runnable() { ... do stuff ... });
Dialog dialog = new Alert(AlertType.INFORMATION);
dialog.setTitle("Wait");
dialog.disableButton(ButtonType.OK);
task.stateProperty().addListener(
(observableValue, oldState, newState) -> {
if (newState == Worker.State.SUCCEEDED
|| newState == Worker.State.FAILED
|| newState == Worker.State.CANCELLED) {
dialog.close();
}
});
new Thread(task).start();
dialog.showAndWait();

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 get a JavaFX MenuItem to respond to a TAB KeyPress?

A JavaFX MenuItem can respond to most KeyPress events by setting an ActionEvent EventHandler. However, while the event handler does catch a KeyPress of KeyCode.ENTER, it does not catch a KeyCode.TAB KeyPress event. Apparently, some key events like TAB are handled at a deeper level. For example, the arrow keys enable traversal of the menu.
My ContextMenu is a list of completions of an email address string the user has started typing in a TextField. The users want to press the arrow keys to select the desired item, and the TAB key to execute the completion.
I can attach an event handler to the ContextMenu itself and catch the TAB keypress. But the event's Source is then the ContextMenu, and I can find no variables in the ContextMenu indicating which MenuItem was highlighted when the TAB key was pressed. MenuItem allows css style to control appearance of the menu item in focus, but it does not have any properties telling whether it is in focus or not.
I have tried futzing with the EventDispatchChain via MenuItem buildEventDispatchChain() to no avail. There seems to be no way to intercept the TAB KeyPress or otherwise determine which menu item was in focus when the TAB key was pressed.
Any suggestions?
If I get this right, you want to override the default keypressed listener to add your own response, so for that we have to find where it's applied.
To get this working, we've got to get our hands dirty with private API...
ContextMenu skin (ContextMenuSkin) uses a ContextMenuContent object, as a container with all the items. Each of these items are also in a ContextMenuContent.MenuItemContainer container.
We can override the keypressed listener on the parent container, while we can add a focusedProperty listener to the items on the items container.
Using this private API
import com.sun.javafx.scene.control.skin.ContextMenuContent;
this is working for me:
private ContextMenuContent.MenuItemContainer itemSelected=null;
#Override
public void start(Stage primaryStage) {
MenuItem cmItem1 = new MenuItem("Item 1");
cmItem1.setOnAction(e->System.out.println("Item 1"));
MenuItem cmItem2 = new MenuItem("Item 2");
cmItem2.setOnAction(e->System.out.println("Item 2"));
final ContextMenu cm = new ContextMenu(cmItem1,cmItem2);
Scene scene = new Scene(new StackPane(), 300, 250);
scene.setOnMouseClicked(t -> {
if(t.getButton()==MouseButton.SECONDARY || t.isControlDown()){
cm.show(scene.getWindow(),t.getScreenX(),t.getScreenY());
ContextMenuContent cmc= (ContextMenuContent)cm.getSkin().getNode();
cmc.setOnKeyPressed(ke->{
switch (ke.getCode()) {
case UP: break;
case DOWN: break;
case TAB: ke.consume();
if(itemSelected!=null){
itemSelected.getItem().fire();
}
cm.hide();
break;
default: break;
}
});
VBox itemsContainer = cmc.getItemsContainer();
itemsContainer.getChildren().forEach(n->{
ContextMenuContent.MenuItemContainer item=(ContextMenuContent.MenuItemContainer)n;
item.focusedProperty().addListener((obs,b,b1)->{
if(b1){
itemSelected=item;
}
});
});
}
});
primaryStage.setScene(scene);
primaryStage.show();
}
Excellent! Thank you #jose! I ended up writing somewhat different code but
the key is using com.sun.javafx.scene.control.skin.ContextMenuContent, which provides
access to the ContextMenuContent.MenuItemContainer objects that hold the MenuItems.
In order to not break the existing UP/DOWN key behavior, I added a new handler
to the ContextMenuContent object; this handler only consumes the TAB KeyPress and
everthing else passes through to their normal handlers.
Looking at the ContextMenuContent class, I borrowed their existing method for
finding the focused item, so didn't have to add focusedProperty listeners.
Also, I'm on Java 1.7 and don't have lambdas and I use a very basic programming style.
public class MenuItemHandler_CMC <T extends Event> implements EventHandler {
public ContextMenuContent m_cmc;
public AddressCompletionMenuItemHandler_CMC(ContextMenuContent cmc){
m_cmc = cmc;
}
#Override
public void handle(Event event){
KeyEvent ke = (KeyEvent)event;
switch(ke.getCode()){
case TAB:
ke.consume();
MenuItem focused_menu_item = findFocusedMenuItem();
if(focused_menu_item != null){
focused_menu_item.fire();
}
break;
default: break;
}
}
public MenuItem findFocusedMenuItem() {
VBox items_container = m_cmc.getItemsContainer();
for (int i = 0; i < items_container.getChildren().size(); i++) {
Node n = items_container.getChildren().get(i);
if (n.isFocused()) {
ContextMenuContent.MenuItemContainer menu_item_container = (ContextMenuContent.MenuItemContainer)n;
MenuItem menu_item = menu_item_container.getItem();
return menu_item;
}
}
return null;
}
}
...Attach the additional handler
if(m_context_menu.getSkin() != null){
ContextMenuContent cmc = (ContextMenuContent)m_context_menu.getSkin().getNode();
MenuItemHandler_CMC menu_item_handler_cmc = new MenuItemHandler_CMC(cmc);
cmc.addEventHandler(KeyEvent.KEY_PRESSED, menu_item_handler_cmc);
}

Resources