Emily V
02/17/2022, 6:23 AMvar chartFrame: ChartPanel? = null
@Composable
private fun TheChart() {
Card(elevation = 5.dp, shape = RoundedCornerShape(0.dp), modifier = Modifier.fillMaxSize()) {
if (chartFrame == null) {
val series = XYSeries("Sensors Reading")
series.add(0, 3)
series.add(1, 4)
series.add(2, 5)
series.add(3, 6)
series.add(4, 7)
series.add(5, 3)
val dataset = XYSeriesCollection(series)
val chart: JFreeChart = ChartFactory.createXYLineChart("Test", "Time (seconds)", "Sensors value", dataset)
val frame = ChartPanel(chart)
frame.isVisible = true
chartFrame = frame
}
Box {
SwingPanel(
factory = {
JPanel().apply {
layout = BoxLayout(this, BoxLayout.Y_AXIS)
add(chartFrame)
}
})
}
}
}
This renders great and looks as it should. Now, when I want to push in new data, I basically need to update the dataset, and I do that by adding x,y values to the series object. Now obviously this needs to be hoisted out of the Composable and get pushed into the function as a parameter. But I am not entirely sure on how to architect that properly in Compose. I also added a check for null to make sure not to recreate the chart object on each recomposition and I think this is not ideal here. Can any one assist?David W
02/17/2022, 4:00 PMval series = remember { ... } // note the `=` instead of `by`
// update the series
series.value = newSeriesValue
and then
private fun TheChart(series: State<XYSeries>) {
...
val dataset = XYSeriesCollection(series.value)
...
David W
02/17/2022, 4:01 PMDavid W
02/17/2022, 4:02 PMState
directly will be of useEmily V
02/17/2022, 4:04 PMEmily V
02/17/2022, 4:06 PMEmily V
02/17/2022, 4:06 PMDavid W
02/17/2022, 4:13 PMDavid W
02/17/2022, 4:13 PMEmily V
02/17/2022, 4:14 PM