JFreechart with Dynamic values

0

I've been struggling to create an online graph that is dynamic, I've got some "progress" but now it gives me an error: Exception in thread "main" org.jfree.data.UnknownKeyException: Unrecognised columnKey: 10/17 . The idea of the chart is, it takes all the values in a list and adds them by separating them by month in the MM/yy format. From what I read about JFreechar already performs this sum and separation in the graphical style I'm putting together, however I may be wrong.

Minimum verifiable example

import java.awt.Color;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.LineBorder;
import javax.swing.table.AbstractTableModel;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;

public class ExemploMinimo
{
    public class Request implements Serializable
    {
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
        private Date registrationDate;
        private String noteTotal;

        public Date getRegistrationDate()
        {
            return registrationDate;
        }

        public void setRegistrationDate(Date registrationDate)
        {
            this.registrationDate = registrationDate;
        }

        public String getNoteTotal()
        {
            return noteTotal;
        }

        public void setNoteTotal(String noteTotal)
        {
            this.noteTotal = noteTotal;
        }
    }

    // ----------------------------------------------------------------------------------------
    public interface Dao<R>
    {
        public List<R> searchAll() throws Exception;
    }

    // ----------------------------------------------------------------------------------------
    public class ModelTableRequestRoute extends AbstractTableModel
    {
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
        private List<Request> request = new ArrayList<>();
        private SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

        public ModelTableRequestRoute(List<Request> list)
        {
            request = list;
        }

        @Override
        public String getColumnName(int column)
        {
            switch (column)
            {
                case 0:
                    return "data";
                case 1:
                    return "valor";
            }
            return super.getColumnName(column);
        }

        @Override
        public int getColumnCount()
        {
            return 2;
        }

        @Override
        public int getRowCount()
        {
            return request.size();
        }

        @Override
        public Object getValueAt(int row, int column)
        {
            Request r = request.get(row);
            switch (column)
            {
                case 0:
                    return dateFormat.format(r.getRegistrationDate());
                case 1:
                    return r.getNoteTotal();
                default:
                    return null;
            }
        }

    }

    // ----------------------------------------------------------------------------------------

    public class FrameMinimo extends JFrame
    {
        /**
         * 
         */
        private static final long serialVersionUID = 4320341978109746731L;

        private List<Request> requestList = new ArrayList<>();

        private JPanel tablePanel;
        private JPanel graphicPanel;

        private Date currentDate = new Date();

        private JTable table;
        private JScrollPane scroll;

        public FrameMinimo()
        {
            inicializarComponentes();
            inicializarEventos();

            Request r = new Request();
            r.registrationDate = currentDate;
            r.noteTotal = "3000.00";
            requestList.add(r);

            ContruirTabela();
            construirGraficos();
        }

        private void inicializarComponentes()
        {
            setTitle("Exemplo Minimo");
            setSize(1150, 637);
            setLocationRelativeTo(null);
            setResizable(false);
            setLayout(null);
            setDefaultCloseOperation(EXIT_ON_CLOSE);

            // Table panel
            tablePanel = new JPanel();
            tablePanel.setSize(400, 402);
            tablePanel.setLocation(3, 3);
            tablePanel.setLayout(null);
            tablePanel.setBackground(Color.WHITE);
            tablePanel.setBorder(new LineBorder(Color.BLACK));
            add(tablePanel);

            // Table
            table = new JTable();
            scroll = new JScrollPane(table);
            scroll.setFont(getFont());
            scroll.setBorder(new LineBorder(Color.BLACK));
            scroll.setLocation(3, 3);
            scroll.setSize(394, 395);
            scroll.getViewport().setBackground(Color.WHITE);
            tablePanel.add(scroll);

            // Graphic panel
            graphicPanel = new JPanel();
            graphicPanel.setSize(737, 603);
            graphicPanel.setLocation(tablePanel.getX() + tablePanel.getWidth() + 1, 3);
            graphicPanel.setLayout(null);
            graphicPanel.setBackground(Color.WHITE);
            graphicPanel.setBorder(new LineBorder(Color.BLACK));
            add(graphicPanel);
        }

        private void ContruirTabela()
        {
            ModelTableRequestRoute modelTableRequestRoute = new ModelTableRequestRoute(requestList);
            table.setModel(modelTableRequestRoute);
        }

        private void construirGraficos()
        {
            // FIXME Create data set with list values
            DefaultCategoryDataset ds = new DefaultCategoryDataset();
            for (Request request : requestList)
            {
                ds.getValue(new Double(request.getNoteTotal().replace(".", "").replace(",", ".")),
                        new SimpleDateFormat("MM/yy").format(request.getRegistrationDate()));
            }

            // Create chart
            JFreeChart chart = ChartFactory.createLineChart("Vendas por Rota", "Mês", "Valor", ds, PlotOrientation.VERTICAL, true, true,
                    false);

            // Chart properties
            CategoryPlot plot = chart.getCategoryPlot();
            plot.setBackgroundPaint(Color.WHITE);
            plot.setRangeGridlinePaint(Color.GRAY);

            ChartPanel cp = new ChartPanel(chart);
            cp.setSize(730, 550);
            cp.setLocation(3, 3);
            cp.setVisible(true);
            graphicPanel.add(cp);
            graphicPanel.repaint();
        }

        private void inicializarEventos()
        {

        }
    }

    public static void main(String[] args)
    {
        ExemploMinimo e = new ExemploMinimo();
        FrameMinimo fm = e.new FrameMinimo();
        fm.setVisible(true);
    }
}
    
asked by anonymous 09.10.2017 / 19:40

1 answer

0

After much searching I found the right solution for my problem. I'm still studying the code more, but for the time being it was what gave me the expected result.

 DefaultCategoryDataset ds = new DefaultCategoryDataset();
            Map<String, Double> map = new HashMap<>();

            for (Request request : requestListForClient)
            {
                Double total = new Double(request.getNoteTotal().replaceAll(",", "."));
                String month = new SimpleDateFormat("MM/yy").format(request.getRegistrationDate());

                if (map.containsKey(month))
                {
                    Double totalMonth = map.get(month);
                    map.put(month, (totalMonth + total));
                }
                else
                {
                    map.put(month, total);
                }
            }

            for (Map.Entry<String, Double> entry : map.entrySet())
            {
                String month = entry.getKey();
                Double total = entry.getValue();

                ds.addValue(total, "Valor do Mês/Ano", month);
            }

            // Create chart
            JFreeChart chart = ChartFactory.createLineChart("Vendas por Cliente", "Mês/Ano", "Valor (R$)", ds, PlotOrientation.VERTICAL,
                    true, true, false);

            // Chart properties
            CategoryPlot plot = chart.getCategoryPlot();
            plot.setBackgroundPaint(Color.WHITE);
            plot.setRangeGridlinePaint(Color.GRAY);

            LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
            renderer.setBaseShapesVisible(true);
            renderer.setSeriesPaint(0, Color.RED);

            ChartPanel cp = new ChartPanel(chart);
            cp.setSize(730, 550);
            cp.setLocation(3, 3);
            cp.setVisible(true);
            chartPanel.add(cp);
            chartPanel.repaint();
    
13.10.2017 / 00:58