JAVAFX 2.0 How can i change the slider icon in a slider to an image?

后端 未结 4 1748
刺人心
刺人心 2021-01-02 19:04

I want to change the icon to my image, I\'ve looked through the CSS reference guide but I can\'t seem to find anything relevant. Is it even possible? Doesn\'t matter if it i

4条回答
  •  孤城傲影
    2021-01-02 19:39

    I know that this is an old question but I think I have a contribution to this solution.

    If we want to use a unique slider or we want to modify the appearance of all the sliders the previous solution is more than enough. However, if we need only modify the appearance of only one slider the we need another approach.

    What we gonna do is imagine that we have applied a based style to the main scene. But we don't want to add another css file just to modify the behavior of the slider. So the question is: How we can modify the slider style using our base css file?

    The solution is simple setId() all the controls have this attribute. Now let's check out main class:

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Slider;
    import javafx.scene.layout.VBox;
    import javafx.stage.Stage;
    
    /**
     * Created by teocci.
     *
     * @author teocci@yandex.com on 2018-Jul-06
     */
    public class CustomSliderThumb extends Application
    {
        public static void main(String[] args) { launch(args); }
    
        @Override
        public void start(Stage stage) throws Exception
        {
            Slider slider = new Slider();
            slider.setId("custom-slider");
    
            VBox layout = new VBox();
            layout.setId("base-layout");
            layout.getChildren().setAll(slider);
    
            Scene scene = new Scene(layout);
            scene.getStylesheets().add("css/style.css");
    
            stage.setScene(scene);
            stage.show();
        }
    }
    

    In this example, we created a slider and set its id as "custom-slider". Then we added this slider to a VBox layout and, finally, we added the layout to the scene that has the style.css

    Now lets check the style.css and how to use the id selector to apply a custom style. Remember specify -fx-pref-height and -fx-pref-width with the dimensions of the image or if is a square -fx-padding at half the image side dimension for displaying the whole image.

    #custom-slider .thumb {
        -fx-background-image :url("https://i.imgur.com/SwDjIg7.png");
        -fx-background-color: transparent;
    
        -fx-padding: 24;
    
        /*-fx-pref-height: 48;*/
        /*-fx-pref-width: 48;*/
    }
    
    #custom-slider .track {
        -fx-background-color: #2F2F2F;
    }
    
    #base-layout {
        -fx-background-color: lightgray;
        -fx-padding: 10px;
    }
    

    Sample program output:

    slider

提交回复
热议问题