Search code examples
javaswingchartsjfreechart

Open new frame or chart when a bar or a bar chart is clicked


I have a bar chart which gets the dataset from the mysql database, and I am stuck on using the chartMouseClicked. Currently the code prints when clicked on x or y axis bars, as I learned in a previous question, but how do I set that when I click a particular bar on x or y axis and open a new frame or chart. Also an information box would be fine.

private void lineChart() {
// *************** ADDING BAR CHART FROM DATABASE *****************************

try {
    String sql = "select Region, Male, Female from ObeseLondon limit 14";
    JDBCCategoryDataset dataset = new JDBCCategoryDataset(MySQL.Connectdb(), sql);
    JFreeChart chart = ChartFactory.createBarChart("", "Town", "No. Of Obese People", dataset, PlotOrientation.HORIZONTAL, true, true, true);
    chart.setBackgroundPaint(Color.white);
    BarRenderer render = null;
    //CategoryPlot plot = null;
    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    plot.getRenderer().setSeriesPaint(0, Color.green);
    plot.getRenderer().setSeriesPaint(1, Color.yellow);
    render = new BarRenderer();

    org.jfree.chart.ChartFrame chartframe = new org.jfree.chart.ChartFrame("Query Chart", chart);
    //chartframe.setVisible(true);
    //chartframe.setSize(200,500);
    panelBarChart.setLayout(new java.awt.BorderLayout());
    ChartPanel chartPanel = new ChartPanel(chart);
    panelBarChart.add(chartPanel);
    panelBarChart.validate();
    chartPanel.addChartMouseListener(new ChartMouseListener() {

@Override
public void chartMouseClicked(ChartMouseEvent event) {
    ChartEntity entity = event.getEntity();
    System.out.println(entity);
}

@Override
public void chartMouseMoved(ChartMouseEvent event) {
}

Solution

  • Open a JOptionPane in your handler, as shown below in a ChartMouseListener added to BarChartDemo1. The pane displays a panel of labels, as shown in this related example, but a nested ChartPanel would work as well.

    image

    @Override
    public void chartMouseClicked(ChartMouseEvent event) {
        CategoryItemEntity entity = (CategoryItemEntity) event.getEntity();
        JPanel panel = new JPanel(new GridLayout(0, 1));
        Comparable row = entity.getRowKey();
        Comparable col = entity.getColumnKey();
        panel.add(new JLabel(String.valueOf(row)));
        panel.add(new JLabel(String.valueOf(col)));
        panel.add(new JLabel(String.valueOf(entity.getDataset().getValue(row, col))));
        JOptionPane.showMessageDialog(rootPane, panel);
    }