我想将图标更换为我的图片,我已经查阅了CSS参考指南,但似乎没有找到相关内容。是否有可能?无论是使用CSS还是从主JavaFX脚本中以声明方式实现都可以。
请查看这个音频播放器中如何渲染自定义滑块的示例代码和图像。
如果您只需要反馈而不需要交互控件,JFXtras库中有许多仪表可供选择。
以下是使用invariant答案指出的选择器的一些示例css。请注意,我需要添加一个-fx-padding规范,以便整个图像都能显示,其大小为图像尺寸的一半。
/** slider.css
place in same directory as SliderCss.java
ensure build system copies the css file to the build output path */
.slider .thumb {
-fx-background-image :url("http://icons.iconarchive.com/icons/double-j-design/diagram-free/128/piggy-bank-icon.png");
-fx-padding: 64;
}
/* Icon license: creative commons with attribution: http://www.doublejdesign.co.uk/products-page/icons/diagram */
示例应用程序:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class SliderCss extends Application {
public static void main(String[] args) { launch(args); }
@Override public void start(Stage stage) throws Exception {
VBox layout = new VBox();
layout.setStyle("-fx-background-color: cornsilk; -fx-padding: 10px;");
layout.getChildren().setAll(new Slider());
layout.getStylesheets().add(getClass().getResource("slider.css").toExternalForm());
stage.setScene(new Scene(layout));
stage.show();
}
}
示例程序输出:
使用CSS可以更改滑块的拇指
.slider .thumb{
-fx-background-image :url("your image");
...// more customization
}
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();
}
}
#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;
}
示例程序输出:
.slider .thumb {
-fx-background-image :url("sider-round-thumb-image.png");
-fx-padding: 16; /* My thumb image is 33x33 pixels,so padding is half */
-fx-pref-height: 28;
-fx-pref-width: 28;
-fx-background-color:transparent;
}