0

My goal is to show some data with the JFreeChart XY scatter plot so that the plot appears when a jButton is pushed and it should also be possible to click on the data points on the plot and see some additional information about them. After a push on the jButton the data points are imported from an external data file and a scatter plot is created. The plotting works as expected, but the plot doesn't react to mouse clicks.

I tried to add a ChartMouseListener to the chart panel which contains the scatter plot but it seems that it doesn't register the mouse clicks or there is no reaction to the clicks.

This is the part of the code:


    ChartPanel chapa = new ChartPanel(scatterchart);

    chapa.addChartMouseListener(new ChartMouseListener(){

          @Override
          public void chartMouseClicked(ChartMouseEvent event){

                ChartEntity entity = event.getEntity();

                if (entity != null && entity instanceof XYItemEntity) {
                        XYItemEntity ent = (XYItemEntity) entity;

                        int serindex = ent.getSeriesIndex();
                        int itemindex = ent.getItem();

                        JOptionPane.showMessageDialog(null, serindex);
                        System.out.println(serindex);
                }
         }
         @Override
         public void chartMouseMoved(ChartMouseEvent cme) {}
    });

    jPanel2.setLayout(new java.awt.BorderLayout());
    jPanel2.add(chapa, BorderLayout.CENTER);
    jPanel2.validate();

Above that part the scatterchart is created. All that code is located inside a jButtonActionPerformed method, and surrounded by a try and catch block (for catching the BiffException, IOException and SQLException which are necessary for handling the chart data).

When clicking on a data point on the scatter plot, a message window with the index of the XY series containing that data point should appear, and that index should also be delivered by System.out.println, but actually nothing happens when clicking a data point. What is wrong in the code? Thanks for any help.

reip
  • 11
  • 4
  • Please [edit] your question to include a [mcve] that exhibits the problem; this will allow you to study the problem in isolation, for [example](https://stackoverflow.com/a/28926590/230513). – trashgod Apr 05 '19 at 21:22

1 Answers1

1

I managed to find the solution. The code is all right, there was a simpler mistake - the program contains many jButtons which generate scatter charts, but not every jButton creates a chart with a chartMouseListener. When running the program, one such jButton was pushed instead the right one, so the scatter chart didn't react to clicks because it just didn't have the chartMouseListener...

When looking for the solution and trying different options, I wrote a simpler code (there is only one jButton and one jPanel) with the same idea. It creates a simple scatter chart and prints out the x-coordinates of the clicked data points. I post it here, maybe it can serve as an example for somebody (copy and save it as "graphclick"):

import java.awt.BorderLayout;
import javax.swing.JOptionPane;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartMouseEvent;
import org.jfree.chart.ChartMouseListener;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.entity.ChartEntity;
import org.jfree.chart.entity.XYItemEntity;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

public class graphclick extends javax.swing.JFrame {

    public graphclick() {
        initComponents();
    }

    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 421, Short.MAX_VALUE)
        );

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(365, 365, 365)
                .addComponent(jButton1)
                .addContainerGap(383, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addContainerGap(59, Short.MAX_VALUE))
        );

        pack();
    }

    // HERE IS THE MAIN ACTION TAKING PLACE
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        XYSeriesCollection impser = new XYSeriesCollection();
        try {
        XYSeries series1 = new XYSeries("Series1");
        series1.add(1.0, 2.0);
        series1.add(2.0, 2.5);
        series1.add(3.0, 2.0);

        impser.addSeries(series1);
        JFreeChart scatterchart = ChartFactory.createScatterPlot("", "X", "Y", impser);

        XYPlot xyplot = scatterchart.getXYPlot();
        ValueAxis domainAxis = xyplot.getDomainAxis(); // x-axis
        ValueAxis rangeAxis = xyplot.getRangeAxis();

        domainAxis.setRange(0.0, impser.getDomainUpperBound(false) + 1.0);
        rangeAxis.setRange(0.0, impser.getRangeUpperBound(true) + 1.0);

        jPanel1.removeAll();
        ChartPanel chapa = new ChartPanel(scatterchart);

        chapa.addChartMouseListener(new ChartMouseListener(){
            @Override
            public void chartMouseClicked(ChartMouseEvent event){

                ChartEntity entity = event.getEntity();

                if (entity != null && entity instanceof XYItemEntity) {
                    XYItemEntity ent = (XYItemEntity) entity;

                    int sindex = ent.getSeriesIndex();
                    int iindex = ent.getItem();

                    XYSeries ser = impser.getSeries(sindex);

                    System.out.println(impser.getX(sindex, iindex));

                }
            }
            @Override
            public void chartMouseMoved(ChartMouseEvent cme) {}
        });

        jPanel1.setLayout(new java.awt.BorderLayout());
        jPanel1.add(chapa, BorderLayout.CENTER);
        jPanel1.validate();

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Error: " + e.getMessage());
        }
    }                                        

    public static void main(String args[]) {

        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(graphclick.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(graphclick.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(graphclick.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(graphclick.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new graphclick().setVisible(true);
            }
        });
    }

    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel1;               

}
reip
  • 11
  • 4