I have been trying to make this app that will produce a line chart after I click on the "Add New Data Item" button. Now, after I click on the button,nothing happens (gui freezes) and after I maximize the frame the graph appears inside of the frame, which menas that my programm worked,but I don't know why does my gui freeze. I have seen similiar questions and people responded that a new thread has to be introduced to handle different taks,and I have tried that too,but it still did't work,just made it worse.Does anyone know what mistake I am making here? Here is my code:
import java.awt.BorderLayout;
import java.util.HashSet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.DefaultXYDataset;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.RefineryUtilities;
public class ChartApp implements ActionListener {
static final JFrame frame = new JFrame("Chart");
public ChartApp(){
final JButton button = new JButton("Add New Data Item");
button.addActionListener(this);
frame.setSize(600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(button,BorderLayout.NORTH);
frame.setVisible(true);
}
public static void main(String[] args){
ChartApp app=new ChartApp();
}
public void actionPerformed(final ActionEvent e)
{
DefaultXYDataset dataSet = new DefaultXYDataset();
double[][] data = { {1,5,9}, {1, 5, 4} };
dataSet= createDataset(dataSet,data);
final JFreeChart chart = ChartFactory.createXYLineChart("Test Chart",
"x", "y", dataSet, PlotOrientation.VERTICAL, true, true,
false);
ChartPanel cp = new ChartPanel(chart);
frame.getContentPane().add(cp);
}
private static DefaultXYDataset createDataset( DefaultXYDataset dataSet,double[][]data) {
dataSet.addSeries("series1", data);
return dataSet;
}
}
Thank you!
I don't think your GUI is freezing, it's just not been told to change. Have you tried calling repaint()
on the frame after the ChartPanel
is added?
As regards threads, if the code inside actionPerformed
is less than instant, you should probably do it in a separate thread.