Issue
I'm trying to work on a LineChart in JavaFX , I have two classes the Main class and the Controller class , the Main class has the Stage and the Scene , and the Controller Class has the functionality of the LineChart , after initializing the LineChart in the Contoller Class and after the running the code , the LineChart is not displaying the coordinates on the chart , why is that happeing ?
Here's the Main Class :
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Line Chart");
primaryStage.setScene(new Scene(root, 900, 500));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Controller Class :
package sample;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import java.net.URL;
import java.util.ResourceBundle;
public class Controller implements Initializable {
@FXML
private ComboBox functionChooser;
@FXML
private TextField tfWidth,tfMin,tfMax;
@FXML
private RadioButton showFunction,hideFunction;
@FXML
private Label labelWidth,labelMin,labelMax;
@FXML
private LineChart lnChart;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
final NumberAxis xAxis = new NumberAxis();
final NumberAxis yAxis = new NumberAxis();
String funcs[] = {"y(x) = sin(X)","y(x) = cos(x) - 2 * sin(x)","y(x) = sin(x*x)"};
functionChooser.getItems().setAll(funcs);
functionChooser.getSelectionModel().selectFirst();
Stage stage = new Stage();
lnChart = new LineChart<Number,Number>(xAxis,yAxis);
XYChart.Series series1 = new XYChart.Series();
series1.setName("Portfolio 1");
series1.getData().add(new XYChart.Data(0, 23));
series1.getData().add(new XYChart.Data(1, 14));
series1.getData().add(new XYChart.Data(2, 15));
series1.getData().add(new XYChart.Data(3, 24));
series1.getData().add(new XYChart.Data(4, 34));
lnChart.getData().add(series1);
}
}
Solution
Never set a member marked @FXML
to a new
value.
The FXML annotated members are created by the FXMLLoader and automatically added to the node hierarchy the loader creates.
What you are doing is creating a second line chart, putting data in it, and never adding it to the scene.
What you want to do instead, is put your data in the existing line chart that was already created by the loader.
Answered By - jewelsea