I would like to ask a small question. Indeed, I want to customize the menu that appears when we make a right click in a textarea or a textfield. My goal would be to keep the basic menu (copy, paste, cut...) by adding the buttons I want.
I found this post that explains how to do it: JavaFX Append to right click menu for TextField
import com.sun.javafx.scene.control.skin.TextFieldSkin;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Stage;
public class GiveMeContext extends Application {
@Override
public void start(final Stage stage) throws Exception {
TextField textField = new TextField();
TextFieldSkin customContextSkin = new TextFieldSkin(textField) {
@Override
public void populateContextMenu(ContextMenu contextMenu) {
super.populateContextMenu(contextMenu);
contextMenu.getItems().add(0, new SeparatorMenuItem());
contextMenu.getItems().add(0, new MenuItem("Register"));
}
};
textField.setSkin(customContextSkin);
stage.setScene(new Scene(textField));
stage.show();
}
public static void main(String[] args) throws Exception {
launch(args);
}
}
After trying, it works perfectly well for java 8, but as they were talking about it at the time, after java 9, it doesn't work anymore.
I tried to replace the problematic method (populateContextMenu) but unfortunately I couldn't find any way.
I would be very thankful if someone shows me how to do it using java 9+
Your code won't work in JavaFX 9+ because of modularization. For details read this. The only thing you can do is to use context menu and fill it with your own values. A full example to do it in JavaFX 17 is below.
Step 1. Create new project.
Pom.xml:
module-info:
Main class:
Step 2. Build you project.
Step 3. Download JavaFX SDK from here.
Step 4 Run you project this way