I have a class that extends JPanel
for JFreeChart
. Inside of setMean()
, I tried updating values of dataset
or just the Function2D
, but nothing changes on the graph even with repaint()
.
public class JFreeChartPanel extends JPanel {
Function2D normal = new NormalDistributionFunction2D(0.0, 3.0);
XYDataset dataset = DatasetUtilities.sampleFunction2D(normal, -5.0, 5.0, 100, "Normal");
double mean = 0.0, std = 1.0;
public double getMean() {
return mean;
}
public void setMean(double mean) {
this.mean = mean;
normal = new NormalDistributionFunction2D(mean,std);
dataset = DatasetUtilities.sampleFunction2D(normal, -5.0, 5.0, 100, "Normal");
repaint();
}
public double getStd() {
return std;
}
public void setStd(double std) {
this.std = std;
}
public JFreeChartPanel(){
JFreeChart chart = ChartFactory.createXYLineChart(
"Normal Distribution",
"X",
"Y",
dataset,
PlotOrientation.VERTICAL,
true,
true,
false
);
final ChartPanel chartPanel = new ChartPanel(chart);
setLayout(new BorderLayout());
add(chartPanel);
}
}
And this is executed everytime I change the value in my JTextField
.
public void updateMean()
{
String meanS = mean.getText();
double mean = 0.0;
try{
mean = Double.parseDouble(meanS);
System.out.println("Mean: "+mean);
jFreeChartPanel.setMean(mean);
}catch(Exception e){
System.out.println("Mean: incorrect input");
}
}
Ordinarily, you could simply update the
XYDataset
used to create theJFreeChart
, and the listening chart would update itself in response. As @Hovercraft notes,repaint()
alone is not sufficient to tell the chart's plot that you have replaced the dataset. In the example below, I've refactored the dataset's initialization and passed it tosetDataset()
as a parameter.See the relevant source to examine the event wiring. A
ChangeListener
added to aJSpinner
may be easier to operate than aJTextField
.