Issue
I want to make a ComboBox which will show other items when I have the mouse over a current item. Also you cannot select an item which has childs inside.
Like this:
Currently I have a ComboBox with items of a String array, but I can't understand how to put the child nodes.
Solution
This looks like a MenuButton
would be a better option than a ComboBox
. You can do something like this:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuButton;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class App extends Application {
@Override
public void start(Stage stage) {
MenuButton menuButton = new MenuButton("Select Item");
Label label = new Label("Selected Item: ");
Menu subMenu = new Menu("Item 1");
for (int i = 1 ; i <= 3 ; i++) {
subMenu.getItems().add(createItem("Child item "+i, label));
}
menuButton.getItems().add(subMenu);
for (int i = 2 ; i <= 5 ; i++) {
menuButton.getItems().add(createItem("Item "+i, label));
}
BorderPane root = new BorderPane(label);
root.setTop(menuButton);
Scene scene = new Scene(root, 400, 400);
stage.setScene(scene);
stage.show();
}
private MenuItem createItem(String text, Label label) {
MenuItem item = new MenuItem(text);
item.setOnAction(e -> label.setText("Selected Item: "+text));
return item ;
}
public static void main(String[] args) {
launch();
}
}
Answered By - James_D