What is the procedure to alter the color of XYChart in JavaFx?

How can I change the color of a bar chart?

Does anyone have any tips on:

  • How to adjust the color of line charts?
  • How to assign a CSS class to series?
public class CustomBarChart extends Application {

@Override public void start(Stage stage) throws Exception{

        stage.setTitle("CUSTOM HISTOGRAM");

        final CategoryAxis xAxis = new CategoryAxis();

        final NumberAxis yAxis = new NumberAxis(0,50,10);

        final BarChart<String,Number> bc = 
            new BarChart<String,Number>(xAxis,yAxis);

        bc.setTitle("CUSTOM HISTOGRAM");

        final VBox verticalbox = new VBox();

        final HBox horizontalbox = new HBox();

        final Button draw = new Button("DRAW");

        CheckBox red = new CheckBox("RED");

        red.setSelected(true);

        CheckBox blue = new CheckBox("BLUE");

        final TextField textfield = new TextField();

        horizontalbox.setAlignment(Pos.BOTTOM_RIGHT);

        horizontalbox.setSpacing(46);

        String filename = textfield.getText();


        XYChart.Series series1 = new XYChart.Series();

        bc.setPrefSize(800, 600);

        horizontalbox.getChildren().addAll(draw, red, blue,textfield);

        verticalbox.getChildren().addAll(bc, horizontalbox);

        horizontalbox.setPadding(new Insets(10, 10, 10, 50));



        Scene scene  = new Scene(new Group());

        ((Group)scene.getRoot()).getChildren().add(verticalbox);

        stage.setScene(scene);

        stage.show();

                //Setting the button on action if its clicked
        draw.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {         
                try {
                CustomBarChartUtil.occur(textfield.getText(), series1); 
                bc.getData().add(series1);
                bc.setLegendVisible(false);
                } catch (FileNotFoundException e) {
                    System.out.println("Error : No such file"); 
                }
            }
        });


        // Customize the color.

    /**  if (red.isSelected()) 
       bc.setStyle("-fx-bar-fill: #000080;"); // red box checked

      else if (blue.isSelected()) 
         bc.setStyle("-fx-bar-fill: #b22222;");// The Blue check box checked*/

    }

    public static void main(String[] args) {
        launch(args);
    }
}

Answer โ„–1

datad.nodeProperty().addListener(new ChangeListener<Node>() {
            @Override
            public void changed(ObservableValue<? extends Node> ov, Node oldNode, Node newNode) {
                newNode.setStyle("-fx-bar-fill: blue;");
            }
        });

Answer โ„–2

Out of all the methods I attempted, it was Mevlana Ayas' solution using the "setStyle" method that proved to be effective.

If we assume that "color" is a string representing the desired color, it can be defined like this:

String color = "hsb(0,0,0)";
String opaqueColor = "hsb(0,0,0,0.2)";

To apply this solution to ScatterChart, LineChart, and AreaChart, you need to add the following listener to each Data object in the series:

data.nodeProperty().addListener(new ChangeListener<Node>() {
            @Override
            public void changed(ObservableValue<? extends Node> ov, Node oldNode, final Node node) {
                if (node != null ) {                   
                    node.setStyle(String.format("-fx-background-color: %s;", color));
                }
            }
}

For LineChart:

serie.nodeProperty().addListener((ObservableValue<? extends Node> o, Node old, Node node) -> {
                if (node != null) {
                    if (node instanceof Path) {
                        node.setStyle(String.format("-fx-stroke: %s;", chartSerie.color));
                    } 
            });

For AreaChart:

serie.nodeProperty().addListener((ObservableValue<? extends Node> o, Node old, Node node) -> {
                if (node != null) {
                     {
                        if (node instanceof Group) {
                            // AreaChart, assuming FILL is FIRST child and LINE is SECOND child
                            Group group = (Group) node;
                            Path fill = (Path) group.getChildren().get(0);
                            fill.setStyle(String.format("-fx-fill: %s;", chartSerie.opaqueColor));
                            Path line = (Path) group.getChildren().get(1);
                            line.setStyle(String.format("-fx-stroke: %s;", chartSerie.color));
                        }
                    }
                }
            });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sometimes, CSS unicode characters may not render correctly and appear as jumbled symbols like "âโ€“¾"

https://i.sstatic.net/eGvzJ.jpg Every now and then, about 1 in every 100 page refreshes, the unicode characters on my page turn into jumbled nonsense (you might need to zoom in to see it clearly). Specifically, the unicode characters are displayed as รข ...

Tips for minimizing the dimensions of images in a slideshow within a gallery

Check out this website: The slideshow images on there are too tall. Can someone assist me in lowering the height of the images? I want both images to be displayed at the same height. Thank you in advance. ...

AngularJS Material Design sticky header MD table container

I am looking to create a table container to display records with a unique requirement - when the table reaches the top of the screen, its header should stick in place. Can you provide guidance on how to implement this feature? For reference, please check ...

Implementing JavaScript validation to alter the background image

I encountered a small issue while working on my project. I was designing a form in HTML using JavaScript, and for the input fields, I decided to use a background image with padding on the left to enhance its appearance. Everything seemed fine until I ran i ...

Managing collapsible content in Bootstrap 4: A comprehensive guide

How can I customize collapsible content in Bootstrap 4? For instance, take a look at this navbar: https://i.sstatic.net/UYbMQ.png https://i.sstatic.net/OuVdw.png https://i.sstatic.net/lXvYt.png I'm looking to modify the behavior of this example. ...

Ensure that the link's color remains constant and remove any styling of text-decoration

Attempting to create a customized header. My goal is to change the color and remove text decoration in the navbar. Below is my code snippet: ReactJS: import React from 'react'; import './Header.css'; function Header() { return ( ...

Align images at the center of a division using the Bootstrap framework

I'm facing an issue with centering social network icons under a div in my login form while keeping it responsive. Can someone please assist me with this problem? Please help me!!. .row { background: #f8f9fa; margin-top: 20px; } .col { bor ...

The clash of interests between jQuery and Bootstrap

I'm facing a problem with conflicting jQuery and Bootstrap files in my header.php code. Whenever I include the jQuery file before the bootstrap.js file, it causes issues with the tabs on my website where clicking on them does not navigate me to the co ...

Sending a File to Google App Engine with the help of gwt-upload

Is there a way to successfully upload files using the gwt-upload feature found on http://code.google.com/p/gwtupload/ with Google Application Engine? ...

Extracting various types of content such as images and text from a PDF document

I'm currently working on a project that involves transforming pdf files into JSON in order to display the content as HTML, including both images and text. So far, I've experimented with various modules but have encountered an issue; while I can s ...

Creating distinct identifiers for CSS JQ models within a PHP loop

Can anyone assist me in assigning unique identifiers to each model created by the loop? I am currently looping through a custom post type to generate content based on existing posts. I would like to display full content in pop-up modals when "read more" i ...

Ways to Monitor Internet Connectivity in intervals of 10-15 seconds without interruption

Currently, I am working on creating an application that needs to meet the following requirements: The app must consistently check for internet connectivity in the background. Once a connection is established, it should automatically send an email. If no c ...

CodeIgniter functionality for generating auto-incrementing IDs that are accessible in both the view and within JavaScript's Window.Print() method

While working on creating an invoice, I encountered a few issues. First, I want the Invoice No: to be displayed in my view (receipt.php) as 0001 and use it as the primary key in my tbl_payment table. However, I'm unsure how to have an auto-incremented ...

The CSS Accordion seems to be the culprit behind the missing margin or border at the top of my page

Although everything on the page is functioning as desired, there seems to be a missing margin or border that is not causing much trouble. If there is a simple solution or an easy way to identify why this is happening, it would be greatly appreciated. Take ...

center the form vertically, similar to how you would with text

I am struggling to vertically align my form on my website. Can someone assist me with this issue? I want my form to be vertically aligned in the same way as my text on the website. How can I achieve this? Here is the code snippet I am currently using: ht ...

Halt the execution of a function upon clicking a div element

I'm currently working on a function that needs to be stopped when a div with the class "ego" is clicked. This function toggles the visibility of the header based on the scroll position and should only run by default. Below is the code snippet: $("#e ...

Tips for Removing Numerous Selenium Logs

My experience using Selenium 3.0.1 with Firefox 48 has been challenging. Despite trying the following code: java.util.logging.Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(Level.OFF); java.util.logging.Logger.getLogger("org.apache.common ...

Unsure of the datatype for a particular field in a JSON object? No problem - here's how to

Working with a JSON response, I am using Jackson to parse it. However, the type of one field is unknown. For example: {"name" : "Catalina"} OR {"name" : {"First" : "Catalina", "Last" : "Kyle"}} How can I deserialize this object into a POJO? class Nam ...

What is the process of adding an array element to a hashmap?

I've been grappling with this issue for some time now. The problem I'm facing is figuring out how to insert an array object into my hashmap. Below is an example of the hashmap code I found online for a dropdown menu: private Map<String,Map&l ...

Android - CircleButton Issue

While trying to use the library provided in CircleButton.java, I encountered an issue The error message reads: "Should pass resolved color instead of resource id here" This problem occurs at line 57: circlePaint.setColor(pressed ? pressedColor : defa ...