JavaFX How to change ProgressBar color dynamically?

匿名 (未验证) 提交于 2019-12-03 01:04:01

问题:

I was trying to solve my problem with colored progress bars in this thread. The solution was present, but then I ran into another problem: I can't change color dynamically from my code. I want to do it right from my code, not with pre-defined .css. Generally I can do it, but I run into some difficulties when I try to do it with more than one progess bar.

public class JavaFXApplication36 extends Application {      @Override     public void start(Stage primaryStage) {         AnchorPane root = new AnchorPane();         ProgressBar pbRed = new ProgressBar(0.4);         ProgressBar pbGreen = new ProgressBar(0.6);         pbRed.setLayoutY(10);         pbGreen.setLayoutY(30);          pbRed.setStyle("-fx-accent: red;");       // line (1)         pbGreen.setStyle("-fx-accent: green;");   // line (2)          root.getChildren().addAll(pbRed, pbGreen);         Scene scene = new Scene(root, 150, 50);         primaryStage.setTitle("Hello World!");         primaryStage.setScene(scene);         primaryStage.show();     } } 

I always get 2 red progressbars with it! It seems that code in line (1) changes the style of ProgressBar class, not the instance.

Another strange moment is that deleting line (1) don't result in 2 green progress bars. So I can figure that line (2) is completely useless!! WHY?! That's definitely getting odd.

Is there any way to set different colors for separate progressbars?

回答1:

See also the StackOverflow JavaFX ProgressBar Community Wiki.


There is a workaround you can use until a bug to fix the sample code in your question is filed and fixed.

The code in this answer does a node lookup on the ProgressBar contents, then dynamically modifies the bar colour of the progress bar to any value you like.

import javafx.application.Application; import javafx.beans.value.*; import javafx.geometry.Pos; import javafx.scene.*; import javafx.scene.control.*; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.stage.Stage;  public class ProgressBarDynamicColor extends Application {   public static void main(String[] args) { launch(args); }   @Override public void start(Stage stage) {     PickedColorBar aquaBar = new PickedColorBar(0.4, Color.AQUA);     PickedColorBar fireBar = new PickedColorBar(0.6, Color.FIREBRICK);      HBox layout = new HBox(20);     layout.getChildren().setAll(aquaBar, fireBar);     layout.setStyle("-fx-background-color: -fx-box-border, cornsilk; -fx-padding: 15;");      stage.setScene(new Scene(layout));     stage.show();      aquaBar.wasShown();     fireBar.wasShown();   }    class PickedColorBar extends VBox {     private final ProgressBar bar;     private final ColorPicker picker;      private boolean wasShownCalled = false;      final ChangeListener<Color> COLOR_LISTENER = new ChangeListener<Color>() {       @Override public void changed(ObservableValue<? extends Color> value, Color oldColor, Color newColor) {         setBarColor(bar, newColor);       }     };      public PickedColorBar(double progress, Color initColor) {       bar    = new ProgressBar(progress);       picker = new ColorPicker(initColor);        setSpacing(10);       setAlignment(Pos.CENTER);       getChildren().setAll(bar, picker);     }      // invoke only after the progress bar has been shown on a stage.          public void wasShown() {       if (!wasShownCalled) {         wasShownCalled = true;         setBarColor(bar, picker.getValue());         picker.valueProperty().addListener(COLOR_LISTENER);       }       }      private void setBarColor(ProgressBar bar, Color newColor) {       bar.lookup(".bar").setStyle("-fx-background-color: -fx-box-border, " + createGradientAttributeValue(newColor));     }      private String createGradientAttributeValue(Color newColor) {       String hsbAttribute = createHsbAttributeValue(newColor);       return "linear-gradient(to bottom, derive(" + hsbAttribute+ ",30%) 5%, derive(" + hsbAttribute + ",-17%))";     }      private String createHsbAttributeValue(Color newColor) {       return          "hsb(" +            (int)  newColor.getHue()               + "," +            (int) (newColor.getSaturation() * 100) + "%," +            (int) (newColor.getBrightness() * 100) + "%)";     }   } } 

The code uses inlined string processing of css attributes to manipulate Region backgrounds. Future JavaFX versions (e.g. JDK8+) will include a public Java API to manipulate background attributes, making obsolete the string processing of attributes from the Java program.

Sample program output:



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!