我有一个颜色选择器使用setStyle命令为按钮指定颜色。然后我必须解析颜色的值,因为它是十六进制的。我手动将该颜色分配给对象。我有两个我能想到的问题。有时我的解析是不正确的,它不会分配颜色。第二个问题是因为我使用固定字符串设置样式。我希望稍后使用颜色选择器添加更多内联样式。我的第一种思维方式是将每个硬编码的内联css分配为一个字符串,并在最后将它们连接到一个大的SetStyle调用。我想知道是否有更好的选择,比如修改外部css?
private void displayproperties()
{
AnchorPane PropertiesPane = Main.getGeneralPaneProperties();
PropertiesPane.getChildren().clear();
//backgroundColor
Text bgcolor = new Text();
bgcolor.setText("Background Color");
bgcolor.setLayoutX(0.0);
bgcolor.setLayoutY(10.0);
PropertiesPane.getChildren().add(bgcolor);
System.out.println(getStyle());
final ColorPicker colorPicker = new ColorPicker();
colorPicker.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent event) {
setStyle("-fx-background-color:"+ colorPicker.getValue().toString().substring(2));
}
});
PropertiesPane.getChildren().add(colorPicker);
String bordercolor = "-fx-border-color: #545454";
colorPicker.relocate(bgcolor.getBoundsInParent().getMaxX()+5,bgcolor.getBoundsInParent().getMinY());
}
答案 0 :(得分:4)
修复解析:不要使用toString()
:无法保证返回的String
的格式在将来的版本中是相同的。这意味着如果用户升级其JVM安装,您的代码可能会中断。
似乎没有一种好方法可以做到这一点:你只需要从颜色中获取红色,绿色和蓝色值并构建相应的字符串。一种方式是这样的:
public String getCssSpec(Color c) {
int r = (int) (c.getRed() * 256) ;
int g = (int) (c.getGreen() * 256) ;
int b = (int) (c.getBlue() * 256) ;
return String.format("rgb(%d, %d, %d)", r, g, b);
}
可替换地:
return String.format("#%02x%02x%02x", r, g, b);
然后就这样做
@Override
public void handle(ActionEvent event) {
setStyle("-fx-background-color: " + getCssSpec(colorPicker.getValue()));
}
对于需要应用多个样式的问题,最好的方法可能是将所有样式连接成一个字符串,并调用setStyle(...)。我认为我这样做的方法是为你想要设置的每个样式定义一个具有属性的类:
class ButtonStyle {
Color backgroundColor ;
Color borderColor ;
// etc
}
然后定义一个从各种属性构建整个css字符串的方法。这样,您可以使用一两个方法调用更新属性并重新生成内联样式。