Skip to content

Creating a XYChart on button click

The purpose of the program is to display chart on click of the button with given parameters.

calcButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //some calculations ...
                XYChart chart = QuickChart.getChart("Graph", "X", "Y", "y(x)", expression.xData, expression.yData);
                new SwingWrapper(chart).displayChart();

            }
        });

However displayChart uses invokeAndWait, which cannot be executed inside ActionListener which makes sense. What is the proper way to solve this issue?

I am using swing with XChart library

Answer

You have to create the frame and its content panel by yourself, note that using multiple frames in an application is in general a bad idea, so consider a different design for your UI (e.g. tabbed pane).

Sample code, only displayChart(...) is relevant for you but I always prefer to create a runnable example:

package test;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;

import org.knowm.xchart.QuickChart;
import org.knowm.xchart.XChartPanel;
import org.knowm.xchart.XYChart;

public class TestChart {
    public static void main(String[] args) {
        double[] xData=new double[100];
        double[] yData=new double[100];
        for (int i=0;i<100;i++) {
            yData[i]=i+1;
            xData[i]=Math.log(i+1);
        }
        XYChart chart = QuickChart.getChart("Graph", "X", "Y", "y(x)", xData, yData);
        
        JFrame frame=new JFrame("Main");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        JButton clickMe=new JButton("Click me!");
        clickMe.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                displayChart(frame, chart);
            }
        });
        frame.setContentPane(clickMe);
        frame.pack();
        frame.setVisible(true);
        
    }
    
    public static void displayChart(JFrame owner, XYChart chart) {
        XChartPanel<XYChart> panel=new XChartPanel<XYChart>(chart);
        JDialog d=new JDialog(owner, "Chart");
        d.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        d.setContentPane(panel);
        d.pack();
        d.setLocationRelativeTo(owner);
        d.setVisible(true);
    }
}