Create a graph from values of a calculation

Asked

Viewed 745 times

1

I am with the following doubt, how can I make my dynamic graph ? I have a graph, which is formed by two values, I want that according to the result any calculation, it changes/alters its composition.

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

However, it does not change according to this result, it should be divided into a 20% share (result of the calculation) 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);
    }
}
  • Wouldn’t that be duplicate? https://answall.com/q/202022/28595

1 answer

2


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

You’ll 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 function previously defined to give meaning to Plot, as there was nothing implicit in your code put the percentage on top of each value (1, 2)

  • That’s right, thank you very much !

Browser other questions tagged

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