Display custom color dialog directly- JavaFX ColorPicker

后端 未结 3 2012
谎友^
谎友^ 2020-12-06 14:41


I need to show a \"continuous\" color palette for color selection inside a ContextMenu. Similar to CustomColorDialog that pops up on ColorPicker.
Is there a differ

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-06 15:03

    Here is how I use com.sun.javafx.scene.control.skin.CustomColorDialog:

    public Color showColorDialog(String title, Color initialColor) {
    
    CountDownLatch countDownLatch = new CountDownLatch(1);
    
    ObjectHolder selectedColorHolder = new ObjectHolder<>();
    
    Platform.runLater(new Runnable() {
        @Override
        public void run() {
        try {
            final CustomColorDialog customColorDialog = new CustomColorDialog(getWindow());
            customColorDialog.setCurrentColor(initialColor);
    
            // remove save button
            VBox controllBox = (VBox) customColorDialog.getChildren().get(1);
            HBox buttonBox = (HBox) controllBox.getChildren().get(2);
            buttonBox.getChildren().remove(0);
    
            Runnable saveUseRunnable = new Runnable() {
            @Override
            public void run() {
                try {
                Field customColorPropertyField = CustomColorDialog.class
                    .getDeclaredField("customColorProperty"); //$NON-NLS-1$
                customColorPropertyField.setAccessible(true);
                @SuppressWarnings("unchecked")
                ObjectProperty customColorPropertyValue = (ObjectProperty) customColorPropertyField
                    .get(customColorDialog);
                selectedColorHolder.setObject(customColorPropertyValue.getValue());
                } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) {
                LOG.error(e, e);
                }
            }
            };
    
            customColorDialog.setOnUse(saveUseRunnable);
    
            customColorDialog.setOnHidden(new EventHandler() {
            @Override
            public void handle(WindowEvent event) {
                countDownLatch.countDown();
            }
            });
    
            Field dialogField = CustomColorDialog.class.getDeclaredField("dialog"); //$NON-NLS-1$
            dialogField.setAccessible(true);
            Stage dialog = (Stage) dialogField.get(customColorDialog);
    
            dialog.setTitle(title);
            customColorDialog.show();
            dialog.centerOnScreen();
        } catch (Exception e) {
            LOG.error(e, e);
            countDownLatch.countDown();
        }
        }
    });
    
    try {
        countDownLatch.await();
    } catch (InterruptedException e) {
        LOG.error(e, e);
    }
    
    return selectedColorHolder.getObject();
    }
    

提交回复
热议问题