Share menu item in System menu and ContextMenu with accelerator - javafx

In my application I want to have the same menu item appear on both the system menu as well as a context menu. For example, the Copy menu item. In the context menu I also like to show the accelerator key (the same as on the system menu).
Here's where the problem occurs: if you set the accelerator on both menus, both menu items get fired. This is, of course, not what I want…
Is there a way to prevent this? My current work-around is to just not show the accelerators for the context menu, but this isn't really what I want either.
So is there any way of having the accelerator show in the menu but not fire?
Sample code with a context menu and system menu.
If you press CMD/CTRL-C it will fire both handlers :-(
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test_menu;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.input.KeyCombination;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
*
* #author Hayo Baan
*/
public class Test_Menu extends Application {
#Override
public void start(Stage primaryStage) {
// Event handler
EventHandler<ActionEvent> eventHandler = (ActionEvent event) -> {
System.out.println("Got event from " + ((MenuItem) event.getSource()).getText());
event.consume();
};
// The system menubar
MenuBar menuBar = new MenuBar();
menuBar.setUseSystemMenuBar(true);
// Edit menu with Copy item
Menu editMenu = new Menu("Edit");
menuBar.getMenus().add(editMenu);
MenuItem editCopy = new MenuItem("Edit Copy");
editCopy.setAccelerator(KeyCombination.keyCombination("Shortcut+C"));
editMenu.getItems().add(editCopy);
editCopy.setOnAction(eventHandler);
// Context menu with copy item
ContextMenu contextMenu = new ContextMenu();
MenuItem contextCopy = new MenuItem("Context Copy");
contextCopy.setAccelerator(KeyCombination.keyCombination("Shortcut+C"));
contextMenu.getItems().add(contextCopy);
contextCopy.setOnAction(eventHandler);
Label label = new Label("Say 'Hello World'");
VBox root = new VBox();
root.getChildren().addAll(menuBar, label);
label.setContextMenu(contextMenu);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}

What you have is two instances of EventHandlers that react on the same key combination. You can circumvent your issue by defining the EventHandler once, use if for both menu types and consume the event:
EventHandler evtHandler = event -> {
System.out.println("Execute copy event");
event.consume();
};
...
editCopy.setOnAction(evtHandler);
...
contextCopy.setOnAction(evtHandler);

Related

JavaFx 11 ListView consumes ESCAPE key pressed event even if is not in editing state

I have a problem with JavaFx ListView component. I'm using popup with TextField and ListView inside of VBox. When TextField is in focus, I can normally close this popup window pressing the Esc key on the keyboard, but when ListView item is in focus popup stays open, nothing happens.
Minimal reproducible example:
package sample;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
MenuItem rightClickItem = new MenuItem("CLICK!");
rightClickItem.setOnAction(a -> showdialog());
ContextMenu menu = new ContextMenu(rightClickItem);
Label text = new Label("Right Click on me");
text.setContextMenu(menu);
StackPane root = new StackPane(text);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("RightClick MenuItem And Dialog");
primaryStage.setScene(scene);
primaryStage.show();
}
private void showdialog() {
Dialog<ButtonType> dialog = new Dialog<>();
dialog.getDialogPane().getButtonTypes().add(ButtonType.CANCEL);
VBox vBox = new VBox();
ListView listView = new ListView();
listView.getItems().add("Item 1");
listView.getItems().add("Item 2");
vBox.getChildren().add(new TextField());
vBox.getChildren().add(listView);
vBox.addEventHandler(KeyEvent.KEY_PRESSED, keyEvent -> System.err.println("Key pressed: " + keyEvent.getCode()));
dialog.getDialogPane().setContent(vBox);
dialog.showAndWait();
}
public static void main(String[] args) {
launch(args);
}
}
It seems to me that Esc key is consumed in ListView, and this cause a problem with closing a popup.
Just to mention, I'm using zulu-11.0.8 JDKFx version.
It seems to me that Esc key is consumed in ListView, and this cause a problem with closing a popup.
That's indeed the problem - happens with all controls that have a consuming KeyMapping to ESCAPE added by their respective Behavior (f.i. also for a TextField with TextFormatter).
There is no clean way to interfere with it (Behavior and InputMap didn't yet make to move into public api). The way to hack around is to remove the KeyMapping from the Behavior's inputMap. Beware: you must be allowed to go dirty, that is use internal api and use reflection!
The steps:
grab the control's skin (available after the control is added to the scenegraph)
reflectively access the skin's behavior
remove the keyMapping from the behavior's inputMap
Example code snippet:
private void tweakInputMap(ListView listView) {
ListViewSkin<?> skin = (ListViewSkin<?>) listView.getSkin();
// use your favorite utility method to reflectively access the private field
ListViewBehavior<?> listBehavior = (ListViewBehavior<?>) FXUtils.invokeGetFieldValue(
ListViewSkin.class, skin, "behavior");
InputMap<?> map = listBehavior.getInputMap();
Optional<Mapping<?>> mapping = map.lookupMapping(new KeyBinding(KeyCode.ESCAPE));
map.getMappings().remove(mapping.get());
}
It's usage:
listView.skinProperty().addListener(ov -> {
tweakInputMap(listView);
});
To avoid using private API, you can use an event filter that, if the ListView is not editing, copies the Escape key event and fires it on the parent. From there, the copied event can propagate to be useful in other handlers such as closing a popup.
Also, if you need this on all ListViews in your application, you can do it in a derived class of ListViewSkin and set that as the -fx-skin for .list-view in your CSS file.
listView.addEventFilter( KeyEvent.KEY_PRESSED, keyEvent -> {
if( keyEvent.getCode() == KeyCode.ESCAPE && !keyEvent.isAltDown() && !keyEvent.isControlDown()
&& !keyEvent.isMetaDown() && !keyEvent.isShiftDown()
) {
if( listView.getEditingIndex() == -1 ) {
// Not editing.
final Parent parent = listView.getParent();
parent.fireEvent( keyEvent.copyFor( parent, parent ) );
}
keyEvent.consume();
}
} );

How to use modal dialog in this case?

I have a question. I need to make a GridPane with a directory choose that will then lead me to a modal dialog showing photos. I cannot figure how to do the modal dialog that also has to be a GridPane or a HBox...so the question is , how do I get to show a Modal Dialog after selecting the Folder and pressing the "Show" Button... Thanks a lot!
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
public class FotoView extends Application {
#Override
public void start(Stage primaryStage) {
TextField tf = new TextField();
Button b1 = new Button("Search");
Button b2 = new Button("Show");
DirectoryChooser dc = new DirectoryChooser();
GridPane gp = new GridPane();
gp.add(tf, 0 , 0);
gp.add(b1, 1, 0);
gp.add(b2, 0, 1);
b1.setOnAction(e-> dc.showDialog(primaryStage));
primaryStage.setScene(new Scene(gp)) ;
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
} ```
Below is a quick example where a first window has a button that opens up a DirectoryChooser. Once a directory has been selected a second smaller window opens up with the Modality set to APPLICATION_MODAL. In this second window you could add the image(s) that you load and add them to the GridPane.
import java.io.File;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.DirectoryChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(final String[] args) {
launch(args);
}
#Override
public void start(final Stage aStage) throws Exception {
final HBox root = new HBox();
final Button browseBtn = new Button("Click to open a Directory chooser");
root.getChildren().add(browseBtn);
browseBtn.setOnAction(e -> {
final DirectoryChooser chooser = new DirectoryChooser();
final File dir = chooser.showDialog(aStage);
openNewModalStage(aStage, dir);
});
final Scene scene = new Scene(root, 500, 500);
aStage.setScene(scene);
aStage.show();
}
private void openNewModalStage(final Stage aStage, final File aDirectory) {
final Stage stage = new Stage();
final GridPane grid = new GridPane();
final Scene scene = new Scene(grid);
grid.setStyle("-fx-background-color:black");
grid.setPrefWidth(400);
grid.setPrefHeight(400);
// get your images from 'aDirectory' and add them to your grid pane.
stage.setScene(scene);
// set the new windows Modality.
stage.initModality(Modality.APPLICATION_MODAL);
stage.show();
}
}
This way you would only need the one button and the dialog would show as soon as you've selected a directory. However, if you would still want a Search and Show button then just store the directory as a variable and add a listener on the 'show' button and move the openNewModalStage call to that one and remove the second argument.
Edit:
Also, depending on how many images and exactly what you want to display in the modal window, you might want to reconsider the GridPane and use a TilePane, or an hbox/vbox inside of a scroll pane. It's just a thought but I don't know what you will be doing with the GridPane.

Wizard with JavaFX Accordions

I'm writing a small configuration-wizard-style JavaFX application. I want to force the user through different steps of configuration panes. So I've chosen an accordion container with a few panels. The user is only allowed to proceed to the NEXT or PREVIOUS accordion panel, but may not jump from panel 1 to 3.
I achived this by adding the "Previous" and "Next" button under the accordion and I set the mouse transparency of the accordion to true. Everything works fine so far. The user can walk from panel 1 to 5 and back...
Unfortunately (for any strange reason) the user cannot configure nothing inside the different panels. Wait... I set the mouse transparency to "true", right... But when I set it to false, the user can jump through the panels without any order.
Any suggestions?
One possible way is to set the collapsible property of all the panes to false, and to set each one to true just when it needs to be expanded or collapsed (which you can do programmatically). This is a little ugly, but here's an example:
import javafx.application.Application;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Accordion;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TitledPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class AccordionBasedWizard extends Application {
#Override
public void start(Stage primaryStage) {
Accordion accordion = new Accordion();
for (int i = 0 ; i < 5 ; i++) {
TitledPane pane = new TitledPane("Page "+(i+1), new Label("Wizard page "+(i+1)));
accordion.getPanes().add(pane);
pane.setCollapsible(false);
}
accordion.setExpandedPane(accordion.getPanes().get(0));
Button previousButton = new Button("Previous");
previousButton.disableProperty().bind(accordion.expandedPaneProperty().isEqualTo(accordion.getPanes().get(0)));
previousButton.setOnAction(e -> {
TitledPane current = accordion.getExpandedPane();
int index = accordion.getPanes().indexOf(current);
TitledPane previous = accordion.getPanes().get(index - 1);
current.setCollapsible(true);
previous.setCollapsible(true);
accordion.setExpandedPane(previous);
previous.setCollapsible(false);
current.setCollapsible(false);
});
Button nextButton = new Button("Next");
nextButton.disableProperty().bind(accordion.expandedPaneProperty().isEqualTo(accordion.getPanes().get(accordion.getPanes().size()-1)));
nextButton.setOnAction(e -> {
TitledPane current = accordion.getExpandedPane();
int index = accordion.getPanes().indexOf(current);
TitledPane next = accordion.getPanes().get(index + 1);
current.setCollapsible(true);
next.setCollapsible(true);
accordion.setExpandedPane(next);
next.setCollapsible(false);
current.setCollapsible(false);
});
HBox buttons = new HBox(5, previousButton, nextButton);
buttons.setAlignment(Pos.CENTER);
buttons.setPadding(new Insets(5));
BorderPane root = new BorderPane(accordion);
root.setBottom(buttons);
primaryStage.setScene(new Scene(root, 400, 400));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
For what it's worth, I probably wouldn't try to use an Accordion as a wizard, and would just use a BorderPane, with the current "wizard page" in the center and next and previous buttons in the bottom. You can add a breadcrumb trail too if you need.

JavaFX ContextMenu doesn't auto-hide

I have a JavaFX ContextMenu assigned to the right mouse button click of a scrollpane. It opens, but it doesn't close when you click outside the scrollpane. I could add another mouse event to the scrollpane in order to hide it, but that solves only 1 problem. The main problem is that when I click on any component of the scrollpane, then the context menu remains open.
Example: Open popup via right mouse button click, then click on the button. The popup menu is still open.
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ScrollPane;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
final ContextMenu contextMenu = new ContextMenu();
MenuItem item1 = new MenuItem("About");
MenuItem item2 = new MenuItem("Preferences");
contextMenu.getItems().addAll(item1, item2);
Rectangle rect = new Rectangle( 100,100,150,150);
Button button = new Button( "Button Text");
// create nodes
Group root = new Group();
root.getChildren().add( rect);
root.getChildren().add( button);
// create scrollpane
ScrollPane sp = new ScrollPane( root);
sp.setOnMousePressed(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if (event.isSecondaryButtonDown()) {
contextMenu.show( sp, event.getScreenX(), event.getScreenY());
}
}
});
// create scene
Scene scene = new Scene(sp, 400, 400, Color.WHITE);
// add scene to primary stage
primaryStage.setScene( scene);
primaryStage.show();
}
}
The documentation says that there's a setAutoHide method, but it doesn't work in my case:
Specifies whether Popups should auto hide. If a popup loses focus and
autoHide is true, then the popup will be hidden automatically. The
only exception is when owner Node is specified using
show(javafx.scene.Node, double, double). Focusing owner Node will not
hide the PopupWindow.
#defaultValue false
Thank you very much!
Interacting with child elements of the parent, will get a focus to that parent. So the context menu will not hide when the button in your code is clicked.
Try these two approaches:
1) Manually manage the visibility of context menu, i.e. hide it on button click:
button.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent arg0) {
contextMenu.hide();
}
});
2) Use setContextMenu() instead of showing the context menu on mouse press event:
sp.setContextMenu(contextMenu);
I know that this is old post, but for any newcomer I found a new solution. I have an jdk 1.8 and I have the same problem as you, but I have a dynamic generated context menu in TableView. So when you right click on the row I need another context menu by the row content. The key for my solution is that you execute show method in the context menu you pass on the window parameter to the method. Example of my code is below:
ContextMenu contextMenu = this.createContextMenu();
contextMenu.show(this.tableView.getScene().getWindow(), mouseEvent.getScreenX(), mouseEvent.getScreenY());
And when I click to another location of my program, the context menu hide.

JavaFX: SplitPane Mouse Handling Breaks After Displaying an Application-Modal Stage

Mouse handling on the SplitPane and ScrollBar controls breaks after displaying an application-modal Stage. The problem goes away after the application window loses and regains focus. Does anyone know a solution or workaround to this problem?
In what way is the mouse handling broken? When you click and start dragging on the control (SplitPane or ScrollBar), the control stops responding to your mouse movements the moment your mouse cursor leaves the control by a single pixel. This requires the user to be impossibly precise with the mouse. You would expect the control to respond to mouse movements, no matter where your mouse cursor happens to be, up until you release the mouse button.
The following code exhibits the problem on Ubuntu Linux and JRE 1.7.0_21. I have seen the problem on other JREs, but I have not tried another OS.
import javafx.application.Application;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.SplitPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.Modality;
public class SplitPaneBug extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
Button button = new Button(
"Move the SplitPane divider, then click here to show the modal"
+ " dialog.");
button.setOnAction(
new EventHandler() {
public void handle(Event event) {
Stage dialog = new ModalDialog();
dialog.showAndWait();
}
});
button.setMaxWidth(Double.MAX_VALUE);
SplitPane splitPane = new SplitPane();
splitPane.getItems().setAll(new BorderPane(), new BorderPane());
VBox vbox = new VBox();
vbox.getChildren().setAll(button, splitPane);
vbox.setVgrow(splitPane, Priority.ALWAYS);
primaryStage.setTitle("SplitPane Bug?");
primaryStage.setScene(new Scene(vbox, 640, 480));
primaryStage.show();
}
class ModalDialog extends Stage {
public ModalDialog() {
Button button = new Button(
"Click here to dismiss this dialog, then move the SplitPane"
+ " divider again.");
button.setOnAction(
new EventHandler() {
public void handle(Event event) {
close();
}
});
BorderPane borderPane = new BorderPane();
borderPane.setCenter(button);
initModality(Modality.APPLICATION_MODAL);
setTitle("Modal Dialog");
setScene(new Scene(borderPane, 600, 100));
sizeToScene();
}
}
}
Are you sure that you use 7u21? Please, set to output VersionInfo.getRuntimeVersion().
I don't reproduce on my ubuntu 12.10 with jdk 7u21(b11) downloaded from official site,
but there is known bug in fx 8.0 - https://javafx-jira.kenai.com/browse/RT-29576

Resources