Hiti3
Hiti3

Reputation: 172

How to add up updating JTextfield values in java? [DocumentListener]

I have read numerous threads on how to use DocumentListener, but my code refuses to work. Basically I have made a food calculator, so when some food is inserted in the first JTextField it calculates all food values of the desired product per x grams.

At the bottom there is a JTextfield with which I want to have stored sum of the kcal value of all products you have consumed. So in short whenever you change your product and press enter it changes the kcal values, so I need the sum of all products I have hit enter button for.

Here is a simple image of how it works:

enter image description here

Please if you know, tell me as I am working on this for too much time. Simply I need to add up the JTextfield for every product I hit enter.

package Grafika;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.EventObject;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class Food_Calculator {

public static final String[] FOOD_NAME = { "Jogurt, sadni", "Jogurt 1,6%",
        "Smetana, sladka 30%", "Sir,sveži", "Sir, mozzarella",
        "Sir, ovčji", "Sir, parmezan", "Sirotka", "Brokoli", "Buče",
        "Čebula, bela", "Čebula, rdeča", "Česen", "Endivija",
        "Fižol, sveži", "Gobe, sveže", "Grah", "Jajčevec", "Krompir",
        "Kumare, sveže", "Kumarice, kisle", "Motovilec", "Paprika, rumena",
        "Paprika, zelena", "Paradižnik", "Pesa, kuhana", "Peteršilj",
        "Por", "Rabarbara", "Radič, rdeči", "Radič, zeleni",
        "Solata, zelena", "Špinača", "Zelena", "Zelje, glavnato belo",
        "Zelje, glavnato rdeče", "Zelje, kitajsko", "Ananas", "Avokado",
        "Banana", "Borovnice", "Breskev", "Brusnice", "Češnje", "Fige",
        "Grenivka", "Grozdje, belo", "Grozdje, črno", "Hruška (cela)",
        "Jabolko (celo)", "Jagode", "Kivi", "Kokos", "Lešniki, suhi",
        "Limona", "Lubenica", "Mandarina", "Mandlji", "Maline", "Marelica",
        "Nektarina", "Olive, zrele", "Orehi, suhi", "Pomaranča",
        "Ribez, črni", "Ribez, rdeči", "Robide", "Rozine", "Slive",
        "Šipek, suhi", "Višnje", "Goska, cela", "Kokoš, cela",
        "Konjsko meso", "Piščanec, cel", "Piščanec, belo meso",
        "Piščanec, temno meso", "Pršut", "Puran, cel", "Puran, belo meso",
        "Puran, temno meso", "Raca, cela", "Svinjina, nemastna",
        "Teletina, nemastna", "Vratovina, sušena", "Hobotnica", "Lignji",
        "List", "Losos", "Postrv, potočna", "Sardelice", "Tuna",
        "Tunina v olju", "Ajda", "Koruzni kosmiči", "Kruh, pšenični, črni",
        "Ovseni kosmiči", "Prepečenec, beli", "Pšenična moka, bela",
        "Pšenični otrobi", "Pšenica, suho zrnje", "Riž, neglaziran",
        "Riž, glaziran", "Riževa moka", "Rž", "Borovničev sok",
        "Breskov sok", "Cola", "Čaj, indijski", "Grozdni sok",
        "Hruškov sok", "Jabolčni sok", "Kava", "Marelični sok",
        "Pesin sok", "Pomarančni sok, sveži", "Čokolada, jedilna",
        "Čokolada, mlečna", "Čokolada, mlečna, z lešniki", "Med" };

public static final double[] FOOD_VALUES = { 99.0, 43.0, 284.9, 95.0,
        224.0, 447.0, 411.0, 25.9, 25.0, 15.0, 35.0, 23.0, 136.0, 11.0,
        143.0, 35.9, 67.0, 25.0, 87.0, 14.0, 10.0, 20.0, 22.0, 16.0, 14.0,
        32.0, 20.0, 28.0, 12.0, 12.0, 24.0, 15.1, 21.9, 12.0, 22.0, 20.0,
        12.0, 46.0, 126.0, 79.0, 56.0, 37.0, 45.7, 48.0, 41.0, 28.0, 60.0,
        54.0, 29.0, 40.0, 26.0, 40.0, 346.0, 701.0, 26.9, 21.0, 34.0,
        565.0, 25.0, 50.7, 50.0, 128.5, 648.0, 35.0, 28.0, 21.0, 29.0,
        246.0, 56.6, 169.2, 57.8, 198.0, 186.0, 110.0, 230.0, 116.0, 126.0,
        496.0, 143.0, 134.0, 186.0, 341.0, 161.0, 113.0, 450.0, 73.0, 77.0,
        83.0, 217.0, 86.0, 98.0, 225.0, 287.0, 333.7, 368.0, 222.0, 372.0,
        354.0, 350.0, 206.0, 326.0, 329.0, 349.0, 349.0, 347.5, 45.0, 48.0,
        39.0, 57.8, 65.7, 51.9, 49.7, 301.0, 56.6, 36.0, 45.0, 475.0,
        517.9, 529.8, 302.7 };

public static final double[] FOOD_VALUES_OH = { 18.6, 3.9, 1.0, 3.0, 0.0,
        0.0, 2.0, 5.1, 2.5, 3.4, 8.5, 5.2, 28.0, 1.1, 21.8, 5.8, 10.6, 5.6,
        20.8, 1.8, 2.0, 3.0, 5.0, 2.8, 2.8, 7.0, 1.0, 5.0, 2.0, 1.7, 3.2,
        2.8, 3.9, 2.0, 3.8, 3.5, 2.0, 11.6, 7.0, 19.2, 14.3, 9.1, 10.8,
        11.7, 9.5, 7.0, 15.3, 13.5, 7.6, 10.0, 6.2, 9.0, 3.7, 6.0, 8.2,
        5.3, 8.0, 4.3, 5.6, 12.8, 12.4, 2.6, 8.8, 5.8, 6.6, 4.4, 6.4, 64.4,
        14.6, 79.2, 14.3, 0.0, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
        0.0, 0.0, 0.0, 1.1, 0.8, 1.0, 0.9, 0.0, 0.0, 0.0, 0.0, 0.0, 72.9,
        85.1, 43.0, 72.8, 77.5, 80.1, 26.8, 72.0, 72.0, 78.0, 78.0, 74.0,
        11.1, 11.7, 10.0, 0.0, 16.6, 3.2, 13.8, 28.5, 14.6, 8.0, 10.4,
        46.8, 56.9, 51.3, 82.3 };

public static final double[] FOOD_VALUES_P = { 1.0, 3.3, 22.0, 14.0, 19.9,
        25.6, 40.0, 0.9, 3.0, 0.6, 0.9, 0.9, 6.0, 0.9, 10.1, 2.8, 5.8, 1.2,
        2.1, 0.7, 0.5, 2.0, 0.2, 0.9, 0.9, 1.1, 4.0, 2.0, 1.0, 1.2, 1.8,
        1.3, 2.2, 1.0, 1.9, 1.7, 1.0, 0.5, 2.0, 1.1, 0.6, 0.6, 0.4, 0.8,
        1.3, 0.0, 0.6, 0.5, 0.2, 0.0, 0.6, 1.0, 3.2, 14.0, 1.1, 0.4, 0.9,
        16.9, 0.9, 1.0, 0.9, 1.1, 15.8, 0.9, 0.9, 1.1, 1.3, 1.1, 0.7, 4.5,
        1.2, 21.8, 21.5, 20.9, 17.6, 21.8, 19.1, 18.9, 20.0, 22.0, 20.9,
        20.0, 20.0, 21.3, 20.8, 15.3, 16.0, 15.9, 22.5, 14.7, 17.4, 21.5,
        22.8, 11.7, 8.6, 8.0, 8.0, 11.6, 9.8, 14.1, 10.2, 7.0, 7.0, 7.0,
        9.3, 0.1, 0.3, 0.0, 14.1, 0.2, 0.3, 0.1, 12.5, 0.3, 1.0, 0.7, 7.9,
        7.7, 9.3, 0.3 };

public static final double[] FOOD_VALUES_M = { 1.1, 1.6, 30.0, 3.0, 16.1,
        40.0, 27.0, 0.3, 0.4, 0.0, 0.0, 0.0, 0.0, 0.3, 1.5, 0.5, 0.4, 0.2,
        0.1, 0.5, 0.2, 0.0, 0.3, 0.0, 0.0, 0.1, 0.0, 0.0, 0.0, 0.0, 0.5,
        0.2, 0.3, 0.0, 0.1, 0.1, 0.0, 0.0, 10.0, 0.3, 0.6, 0.0, 0.7, 0.1,
        0.0, 0.0, 0.0, 0.1, 0.0, 0.0, 0.0, 0.0, 36.0, 69.0, 0.3, 0.0, 0.0,
        53.5, 0.0, 0.2, 0.0, 13.8, 61.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.2, 1.5,
        0.3, 12.3, 11.0, 2.8, 17.7, 3.2, 5.5, 46.9, 7.0, 2.0, 11.2, 29.0,
        9.0, 3.1, 40.2, 0.8, 1.0, 1.7, 13.4, 3.0, 3.2, 15.5, 22.0, 2.4,
        1.6, 2.0, 7.5, 1.9, 1.2, 5.5, 2.0, 2.0, 1.0, 1.0, 1.8, 0.0, 0.0,
        0.0, 0.0, 0.0, 0.2, 0.0, 15.4, 0.1, 0.0, 0.2, 39.7, 32.3, 35.6, 0.0       };

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            JPanel plosca = new MainPanel();
            GraficnoOgrodje.ustvariOkno(
                    "Kalkulator Hranilnih Vrednosti   v1.0",   plosca, false);
        }
    });
}

private static class MainPanel extends JPanel implements ActionListener {

    private JButton enter;
    private JTextField calculations, food_field, value2, value3, value4,
            value5, grams, total1;
    private JLabel food, food_field_entered, kcal, value1, OH, P, FATT,
            blank, blank1, blank2, portion, total;

    public MainPanel() {
        setLayout(new BorderLayout());

        // First panel on Main panel
        JPanel PanelOne = new JPanel();
        this.add(PanelOne, BorderLayout.NORTH);
        PanelOne.setBackground(Color.lightGray);
        PanelOne.setLayout(new FlowLayout());

        food = new JLabel();
        food.setText("Insert food type: ");
        portion = new JLabel("            insert a portion in grams (g): ");
        grams = new JTextField(10);
        food_field = new JTextField(10);
        food_field.setEditable(true);
        enter = new JButton("Enter");

        PanelOne.add(food);
        PanelOne.add(food_field);
        PanelOne.add(portion);
        PanelOne.add(grams);
        PanelOne.add(enter);

        // Second Panel on Main panel
        JPanel PanelTwo = new JPanel();
        this.add(PanelTwo, BorderLayout.CENTER);
        Dimension two = new Dimension(500, 150);
        PanelTwo.setPreferredSize(two);
        PanelTwo.setLayout(new GridLayout(3, 8, 0, 10));

        food_field_entered = new JLabel("      Food: ");
        value1 = new JLabel();
        blank = new JLabel();
        blank1 = new JLabel();
        kcal = new JLabel("      Kcal: ");
        value2 = new JTextField(10);
        OH = new JLabel("      OH: ");
        value3 = new JTextField(10);
        P = new JLabel("      Proteins: ");
        value4 = new JTextField(10);
        FATT = new JLabel("      Fatt: ");
        value5 = new JTextField(10);

        PanelTwo.add(food_field_entered);
        PanelTwo.add(value1);
        PanelTwo.add(blank);
        PanelTwo.add(blank1);
        PanelTwo.add(kcal);
        PanelTwo.add(value2);
        PanelTwo.add(OH);
        PanelTwo.add(value3);
        PanelTwo.add(P);
        PanelTwo.add(value4);
        PanelTwo.add(FATT);
        PanelTwo.add(value5);

        // Third Panel on Main panel
        JPanel PanelThree = new JPanel();
        this.add(PanelThree, BorderLayout.SOUTH);
        PanelThree.setBackground(Color.lightGray);
        PanelThree.setLayout(new FlowLayout());
        Dimension three = new Dimension(getWidth(), 30);
        PanelThree.setPreferredSize(three);

        total = new JLabel("You consumed: ");
        total1 = new JTextField(10);
        total1.setEditable(true);

        PanelThree.add(total);
        PanelThree.add(total1);

        // Fourth Panel on Main panel
        JPanel PanelFour = new JPanel();
        this.add(PanelFour, BorderLayout.EAST);
        PanelFour.setPreferredSize(new Dimension(5, getHeight()
                - PanelThree.getHeight()));

        // Fifth Panel on Main panel
        JPanel PanelFive = new JPanel();
        this.add(PanelFive, BorderLayout.WEST);
        PanelFive.setBackground(Color.lightGray);
        PanelFive.setPreferredSize(new Dimension(0, getHeight()
                - PanelThree.getHeight()));

        // adding ActionListener to the MainPanel, for the button
        enter.addActionListener(this);
    }

    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();

        if (source == enter) {

            String foodText = food_field.getText();
            String gramsText = grams.getText();
            double grams2 = Double.parseDouble(grams.getText());

            value1.setText("[ " + foodText + " / " + gramsText
                    + " gramov ]");

            // calculations of food values for x grams...
            double kcal1 = 0.0;
            double oh = 0.0;
            double protein = 0.0;
            double fatt = 0.0;

            for (int i = 0; i < FOOD_NAME.length; i++) {

                if (foodText.equals(FOOD_NAME[i])) {
                    kcal1 = grams2 / 100 * FOOD_VALUES[i];
                    oh = grams2 / 100 * FOOD_VALUES_OH[i];
                    protein = grams2 / 100 * FOOD_VALUES_P[i];
                    fatt = grams2 / 100 * FOOD_VALUES_M[i];
                }
            }
            value2.setText(String.format(" %.1f ", kcal1));
            value3.setText(String.format(" %.1f g", oh));
            value4.setText(String.format(" %.1f g", protein));
            value5.setText(String.format(" %.1f g", fatt));

        }

        value2.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void changedUpdate(DocumentEvent e) {
                // TODO Auto-generated method stub
                warn();
            }

            @Override
            public void insertUpdate(DocumentEvent e) {
                // TODO Auto-generated method stub
                warn();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                // TODO Auto-generated method stub
                warn();
            }

            public void warn() {
                double total = 0.0;
                double kcal1 = Double.parseDouble(value2.getText());
                total = kcal1 + total;
                total1.setText(String.format(" %.1f Kcal", total));
            }
        });
    }
}

}

Upvotes: 0

Views: 507

Answers (1)

asaini007
asaini007

Reputation: 836

Add an ActionListener to your JButton enter like so:

Button enter = new JButton("Enter");
enter.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        total1.setText(Double.parseDouble(value2.getText())+
                       Double.parseDouble(value3.getText())+
                       Double.parseDouble(value4.getText())+
                       Double.parseDouble(value5.getText()))
    }
});

This simply makes it so that every time the button "enter" is pressed, the JTextField total1 will display the sum of the values in the JTextField's value2-5. The values first have to be parsed as doubles because otherwise, String addition would be used (concatenating instead of arithmetically adding).

Upvotes: 1

Related Questions