Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do Mouse Tracing in Jfreechart?

Can anyone tell me how to implement Mouse Tracing on Graph in jfreechart?

like image 529
sushant kumar Avatar asked Sep 16 '11 07:09

sushant kumar


1 Answers

You may attach a ChartMouseListener to a ChartPanel, on which the charts and plots are rendered. Here is an example:

public class JFreeChartTest extends JFrame {

    private static JFreeChart createPieChart(){
        // Some dataset to display
        DefaultPieDataset data = new DefaultPieDataset();
        data.setValue("Java", new Double(45.0));
        data.setValue("C++", new Double(20.0));
        data.setValue("Visual Basic", new Double(0.0));
        // Chart creation
        return ChartFactory.createPieChart("Pie Chart", // title
                data, // data
                true, // include legend
                true, false);
    }

    public JFreeChartTest(){
        initialize();
    }

    private void initialize(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        JPanel contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(10, 10, 10, 10));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);
        {
            final ChartPanel chartPanel = new ChartPanel((JFreeChart)null);
            contentPane.add(chartPanel, BorderLayout.CENTER);
            final JFreeChart pieChart = createPieChart();
            chartPanel.setChart(pieChart);
            chartPanel.addChartMouseListener(new ChartMouseListener() {

                @Override
                public void chartMouseClicked(final ChartMouseEvent event){
                    System.out.println("chartMouseClicked");
                }

                @Override
                public void chartMouseMoved(final ChartMouseEvent event){
                    int newX = event.getTrigger().getX();
                    int newY = event.getTrigger().getY();
                    System.out.println("chartMouseMoved to " + newX + " " + newY);
                }
            });
        }
    }

    public static void main(String[] args){
        JFreeChartTest frame = new JFreeChartTest();
        frame.setVisible(true);
    }
}    
like image 191
Alex Abdugafarov Avatar answered Sep 18 '22 07:09

Alex Abdugafarov