java awt color chooser does't show in proper way in JavaFx

741 views Asked by At
@FXML
Private void handleItemBackAction(ActionEvent eve)
{  
    java.awt.Color color=JColorChooser.showDialog(null,"Select a color",java.awt.Color.CYAN);

    String hex = Integer.toHexString(color.getRGB() & 0xffffff);

    hex="#"+hex;
    Text.setText(hex);
    ShortcutButton.setStyle("-fx-background-color: " + hex + ";");
}

When I run this window and click on button at first time color chooser goes behind my actual pane.

When I click on button second time while running it shows at top of all other pane which is correct and so on it works properly.

Then why color chooser not shows in front first time on button click?

1

There are 1 answers

7
VGR On BEST ANSWER

The first argument to JColorChooser.showDialog is the parent component of the dialog. You told that method to show the dialog with no parent, so it doesn't know about your other windows.

Instead of using JColorChooser.showDialog, you'll need to embed a JColorChooser instance inside a JavaFX dialog or window:

JColorChooser colorChooser = new JColorChooser(java.awt.Color.CYAN);

SwingNode colorChooserNode = new SwingNode();
colorChooserNode.setContent(colorChooser);

Alert dialog = new Alert(Alert.AlertType.NONE);
// Guarantees dialog will be above (and will block input to) mainStage.
dialog.initOwner(mainStage);
dialog.setTitle("Select a color");

dialog.getDialogPane().setContent(colorChooserNode);

dialog.getDialogPane().getButtonTypes().setAll(
    ButtonType.OK, ButtonType.CANCEL);

Optional<ButtonType> response = dialog.showAndWait();
if (response.filter(r -> r == ButtonType.OK).isPresent()) {
    int rgb = colorChooser.getColor().getRGB();
    String hex = String.format("#%06x", rgb & 0xffffff);

    Text.setText(hex);
    ShortcutButton.setBackground(new Background(
        new BackgroundFill(Color.valueOf(hex), null, null)));
} else {
    System.out.println("User canceled");
}

Of course, you're probably better off using ColorPicker in your main window, so you don't have to create an explicit dialog at all:

final ColorPicker colorPicker = new ColorPicker(Color.CYAN);
colorPicker.setOnAction(e -> {
    Color color = colorPicker.getValue();
    String hex = String.format("#%02x02x02x",
        (int) (color.getRed() * 255),
        (int) (color.getGreen() * 255),
        (int) (color.getBlue() * 255));

    Text.setText(hex);
    ShortcutButton.setBackground(
        new Background(new BackgroundFill(color, null, null)));
});

myLayoutPane.getChildren().add(colorPicker);

As an aside, Java variable names should always start with a lowercase letter, to make them easy to distinguish from class names. Consider changing Text to text, and ShortcutButton to shortcutButton.