限制菜单中可见行的数量:JavaFX

时间:2017-06-28 01:05:20

标签: java javafx

有没有办法限制JavaFX中菜单的可见行数?

这是一个工作示例

public class MenuProb extends Application {

    public void start(Stage primaryStage) {
        Group group = new Group();
        Scene scene = new Scene(group, 800, 600);
        MenuBar menuBar = new MenuBar();
        Menu someValues = new Menu("Values");

        for (int i = 0; i < 50; i++) {
            MenuItem item = new MenuItem("Value " + i);
            someValues.getItems().add(item);
        }

        menuBar.getMenus().add(someValues);
        group.getChildren().addAll(menuBar);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

运行上述代码时,会创建一个菜单,其中仅在菜单项超出屏幕高度后才会显示滚动条。

enter image description here

有没有办法将可见行数限制为预先确定的数字?也就是说,如果行数超过该限制,则会出现滚动条。

1 个答案:

答案 0 :(得分:3)

一种方法是使用CustomMenuItemControl来调整大小。以下示例说明ComboBoxsetVisibleRowCount()ListView,其中包含prefWidthPropertyprefHeightProperty

combo

list

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.CustomMenuItem;
import javafx.scene.control.ListView;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.stage.Stage;

/** @see https://stackoverflow.com/q/44792148/230513 */
public class CustomMenuTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        Group group = new Group();
        Scene scene = new Scene(group, 320, 240);

        ComboBox<String> comboBox = new ComboBox<>();
        for (int i = 0; i < 50; i++) {
            comboBox.getItems().add("Value " + i);
        }
        CustomMenuItem comboMenuItem = new CustomMenuItem(comboBox, false);
        comboBox.getSelectionModel().select(0);
        comboBox.setVisibleRowCount(16);

        ObservableList<String> values = FXCollections.observableArrayList();
        for (int i = 0; i < 50; i++) {
            values.add("Value " + i);
        }
        ListView<String> listView = new ListView<>(values);
        CustomMenuItem listMenuItem = new CustomMenuItem(listView, false);

        MenuBar menuBar = new MenuBar();
        Menu comboMenu = new Menu("Combo Values");
        comboMenu.getItems().add(comboMenuItem);
        Menu listMenu = new Menu("List Values");
        listMenu.getItems().add(listMenuItem);
        menuBar.getMenus().addAll(comboMenu, listMenu);
        group.getChildren().addAll(menuBar);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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