Jfreechart with Dynamic values

Asked

Viewed 222 times

0

I have been facing difficulties in creating an online graphic that is dynamic, I got some "progress" but now he accuses me a mistake: Exception in thread "main" org.jfree.data.UnknownKeyException: Unrecognised columnKey: 10/17. The idea of the graph is, it takes all the values of a list and sum by separating them by month in the format MM/yy. From what I read about Jfreechar already realizes this sum and the separation in the graphic style that 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);
    }
}
  • Didn’t you already ask that question? https://answall.com/questions/244292/jfreechart-jtable

  • No, it’s different, now it’s another problem. I found a logic to assign the values inside the graph, but now it informs me an error

  • To me it seems to be the same problem.

  • No, because now is this error: Exception in thread "main" org.jfree.data.Unknownkeyexception: Unrecognised columnKey: 10/17. I thought it best to open another question, because that post was about a question of logic, this is already a concrete problem with an error

1 answer

0


After much research I found the appropriate solution to my problem. I’m still studying the code more, but for now it was what generated 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();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.