Create a graph from the values of a calculation

1

I have the following question, how can I make my chart dynamic? I have a graph, which is formed by two values, I want that according to result any calculation, it change / change its composition.

As, for example, I made a simple calculation by adding 2 values. As an example, add only 10 + 10, as the other half of the graph is already set to 80, thus completing the 100%.

However, it does not change according to this result, it should be divided into a 20% part (calculation result) and 80% already defined. I want to know how I can pass this value correctly to the chart.

What I did:

package jfreechart;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.util.Rotation;

public class GraficoTeste extends JFrame {

    private static final long serialVersionUID = 1L;
    private PieDataset dataset;
    private JFreeChart grafico;
    private final MeuTxt entrada1 = new MeuTxt();
    private final MeuTxt entrada2 = new MeuTxt();
    private final JButton calcular = new JButton("Calcular");

    class MeuTxt extends JTextField {

        public void setValor(Object valor) {
            setText("" + valor);
        }

        public Object getValor() {
            return "" + getText();
        }
    }

    public GraficoTeste() {
        setSize(500, 400);
        JPanel contentPane = new JPanel();
        setContentPane(contentPane);
        contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
        add(colocaCampos());
        add(colocaGrafico());
        acao();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private void acao() {
        calcular.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                calculo();
            }
        });
    }

    private int total;

    public void calculo() {
        int valor1 = Integer.parseInt(entrada1.getText());
        int valor2 = Integer.parseInt(entrada2.getText());
        total = (valor1 + valor2);
        System.out.println(total);//ver se ele esta calculando.                
    }

    public JComponent colocaCampos() {
        JPanel painelCampo = new JPanel();

        JLabel labelAltura = new JLabel("Altura:");
        painelCampo.add(labelAltura);
        painelCampo.add(entrada1);
        entrada1.setPreferredSize(new Dimension(100, 25));
        JLabel labelPeso = new JLabel("Peso:");
        painelCampo.add(labelPeso);
        painelCampo.add(entrada2);
        entrada2.setPreferredSize(new Dimension(100, 25));
        painelCampo.add(calcular);
        calcular.setPreferredSize(new Dimension(100, 23));
        return painelCampo;
    }

    public JComponent colocaGrafico() {
        JPanel painelG = new JPanel();

        //cria o dataset
        dataset = criaDataset();
        //baseando no dataset criamos o gráfico
        grafico = criaGrafico(dataset, "");
        //insere o painel no gráfico
        ChartPanel painelGrafico = new ChartPanel(grafico);
        //tamanho padrão
        painelGrafico.setPreferredSize(new Dimension(400, 200));
        painelG.add(painelGrafico);        
        return painelG;
    }

    //cria um simples dataset
    private DefaultPieDataset criaDataset() {
        DefaultPieDataset resultado = new DefaultPieDataset();
        resultado.setValue("Vermelho", total);
        resultado.setValue("Azul", 80);//valor para teste
        return resultado;
    }

    //cria o gráfico
    private JFreeChart criaGrafico(PieDataset dataset, String titulo) {
        JFreeChart graf = ChartFactory.createPieChart3D(
                titulo, dataset, true, true, false);
        PiePlot3D enredo = (PiePlot3D) graf.getPlot();
        enredo.setStartAngle(290);
        enredo.setDirection(Rotation.CLOCKWISE);
        enredo.setForegroundAlpha(0.5f);
        return graf;
    }

    public static void main(String[] args) {
        GraficoTeste t = new GraficoTeste();
        t.setVisible(true);
    }
}
    
asked by anonymous 12.05.2017 / 02:55

1 answer

2

For you to change what exists inside a JPanel, you need to use the command .revalidate , This will inform the AWT that you have changed the component tree.

You will need to restructure your code to make it more dynamic.

I made some changes see below:

public class GraficoTeste extends JFrame {

    private JTextField entrada1;
    private JTextField entrada2;
    private JPanel painelGrafico;
    private ChartPanel pltCache;

    public GraficoTeste() {
        setSize(500, 400);
        JPanel contentPane = new JPanel();
        setContentPane(contentPane);
        contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
        configuraCampos();
        configuraGraficos();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private void configuraGraficos() {
        painelGrafico = new JPanel();
        add(painelGrafico);
        plotarGrafico(0, 0);
    }

    private void configuraCampos() {
        JPanel painelCampo = new JPanel();

        entrada1 = new JTextField();
        entrada1.setPreferredSize(new Dimension(100, 25));
        painelCampo.add(new JLabel("Altura:"));
        painelCampo.add(entrada1);

        entrada2 = new JTextField();
        entrada2.setPreferredSize(new Dimension(100, 25));
        painelCampo.add(new JLabel("Peso:"));
        painelCampo.add(entrada2);

        JButton submit = new JButton("Calcular");
        submit.addActionListener(calculoListener());
        submit.setPreferredSize(new Dimension(100, 23));
        painelCampo.add(submit);

        add(painelCampo);
    }

    public ActionListener calculoListener() {
        return new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    double valor1 = Float.valueOf(entrada1.getText());
                    double valor2 = Float.valueOf(entrada2.getText());
                    calculo(valor1, valor2);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(null, ex.getMessage());
                }
            }
        };
    }

    public void calculo(double valor1, double valor2) {
        // Define a função f(x) que você vai utilizar
        double total = valor1 + valor2;
        valor1 = (valor1 / total) * 100;
        valor2 = (valor2 / total) * 100;

        plotarGrafico(valor1, valor2);
    }

    private void plotarGrafico(double valor1, double valor2) {

        DefaultPieDataset dataset = getDataSet("Vermelho", valor1, "Azul", valor2);
        JFreeChart graf = getChart("", dataset);

        ChartPanel chart = new ChartPanel(graf);
        chart.setPreferredSize(new Dimension(400, 200));

        atualizarPanelGrafico(chart);
    }

    public void atualizarPanelGrafico(ChartPanel chart) {
        if (Objects.nonNull(pltCache)) {
            painelGrafico.remove(pltCache);
        }

        pltCache = chart;
        painelGrafico.add(pltCache);

        painelGrafico.revalidate();
    }

    public JFreeChart getChart(String title, DefaultPieDataset dataset) {
        JFreeChart graf = ChartFactory.createPieChart3D("", dataset, true, true, false);
        PiePlot3D plot = (PiePlot3D) graf.getPlot();
        plot.setStartAngle(290);
        plot.setDirection(Rotation.CLOCKWISE);
        plot.setForegroundAlpha(0.5f);
        return graf;
    }

    public DefaultPieDataset getDataSet(String label1, double value1, String label2, double value2) {
        DefaultPieDataset dataset = new DefaultPieDataset();
        dataset.setValue(label1, value1);
        dataset.setValue(label2, value2);
        return dataset;
    }

    public static void main(String[] args) {
        GraficoTeste t = new GraficoTeste();
        t.setVisible(true);
    }

}

Just remembering that you need to have a predefined function to give meaning to the plot, since there was nothing implicit in your code, I put the percentage on top of each value (1, 2)

    
12.05.2017 / 18:40