Show drop down menu on mouse over

Viewed 9310

I want to create drop down menu like this:

enter image description here

I want when I place the mouse over the text to see combo box which I can use to select a value. When I remove the mouse I want to see simple Label. How I can do this?

3 Answers

Unhovered:

xyzzy

On Hover:

xyzzy hover

On Click and Choose:

foobar select

On Choice Complete:

foobar

import javafx.application.Application;
import javafx.geometry.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;

public class Hoverboard extends Application {

    public class TextChooser extends StackPane {
        private Label label = new Label();
        private ComboBox<String> combo = new ComboBox<>();

        public TextChooser(String... options) {
            StackPane.setAlignment(label, Pos.CENTER_LEFT);
            StackPane.setAlignment(combo, Pos.CENTER_LEFT);

            label.textProperty().bind(
                combo.getSelectionModel().selectedItemProperty()
            );
            label.visibleProperty().bind(
                combo.visibleProperty().not()
            );
            label.setPadding(new Insets(0, 0, 0, 9));

            combo.getItems().setAll(options);
            combo.getSelectionModel().select(0);
            combo.setVisible(false);

            label.setOnMouseEntered(event -> combo.setVisible(true));
            combo.showingProperty().addListener(observable -> {
                if (!combo.isShowing()) {
                    combo.setVisible(false);
                }
            });
            combo.setOnMouseExited(event -> {
                if (!combo.isShowing()) {
                    combo.setVisible(false);
                }
            });

            getChildren().setAll(label, combo);
        }
    }

    @Override
    public void start(Stage stage) throws Exception {
        TextChooser textChooser = new TextChooser(
            "xyzzy", "frobozz", "foobar"
        );

        VBox layout = new VBox(textChooser);
        layout.setPadding(new Insets(10));

        stage.setScene(new Scene(layout));
        stage.show();
    }

    public static void main(String[] args) {
        launch(Hoverboard.class);
    }

}

Two potential approaches:

  1. Try to use CSS to modify the look of the ComboBox so it looks like a normal text field; hide the arrow and border, and re-show them on :hover. You'll want to lookup the CSS reference for ComboBox: http://docs.oracle.com/javafx/2/api/javafx/scene/doc-files/cssref.html#combobox

  2. Use a normal TextField, and display a border (and arrow) on :hover. Attach a mouse-listener to the TextField to display a PopupControl on mouse click. Put a ListView inside the PopupControl so it behaves like a ComboBox. You'll need to create a class that implements Skin for your popup control. You should be able to find some examples on the web.

Related