4

I have problem with Text Field Auto Calculation in JAVA using Netbeans 7.2

My Question is if I will input numeric values in Text Field i-e (admission fee, monthly fee, transport fee etc) for auto addition and then input numeric values in Text Field i-e (dues) to auto subtract from the above auto addition before clicking submit Button to insert the total values in database so how i will get result of those numeric values in Text Field (Total) before clicking submit Button.

Please check snapshot:

image

My Source code:

try
         {

            String insrt = "Insert into fee (admission, monthly, transport, dues, total) values (?, ?, ?, ?, ?)";

            PreparedStatement pstmt = conn.prepareStatement(insrt);

            pstmt.setString(1, adm_fee.getText());
            pstmt.setString(2, mnth_fee.getText());
            pstmt.setString(3, trnsprt_fee.getText());
            pstmt.setString(4, dues_fee.getText());
            pstmt.setString(5, total_fee.getText());
            pstmt.executeUpdate();

            JOptionPane.showMessageDialog(null,"Record successfully inserted");
        }

        catch (Exception exp)
        {
            JOptionPane.showMessageDialog(null, exp);
        }
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Silent Heart
  • 77
  • 1
  • 2
  • 7
  • What do you mean by "auto calculate"? Can you explain this in more detail? – Code-Apprentice Jan 05 '13 at 19:26
  • p.s. Typically you shouldn't store calculated data in a database. Most DBMS's contain functionality to do these kinds of calculations upon request. This is preferred because the original data can easily be modified without changing the "calculated" data. – Code-Apprentice Jan 05 '13 at 19:27
  • Thanks for reply @Code-Guru .... i want to Auto calculate sum of all Text Field numeric values then show sum value in Text Field name Total...also i want if i put dues values which auto subtract from sum of all value in the Text Field name Total....please check my snapshot image for better understand my question... – Silent Heart Jan 05 '13 at 19:32
  • Again, what does "auto calculate" mean? Using the word again doesn't explain what it means. – Code-Apprentice Jan 05 '13 at 19:32
  • I understand that you want to get the numeric values and do some kind of calculation. However, I'm unclear if you want to do this calculation *as the user enters the data* or *when the user clicks Submit*. Perhaps I'm just getting hung up on your wording. "Auto calculate" doesn't mean anything in my vocabulary. – Code-Apprentice Jan 05 '13 at 19:35
  • @Code-Guru see my example, I think OP means as the data is entered into textfields he wants to display the results *on the fly* in another textfield i.e so a button click for *calculate* is not needed to be clicked – David Kroukamp Jan 05 '13 at 19:35
  • And is there a reason that you are storing numeric data in your database as text? This seems like a Bad Idea (TM). Similarly, storing calculated data isn't very good, either. I can imagine scenarios where the calculated data can get out of sync with the data it is calculated from. – Code-Apprentice Jan 05 '13 at 19:36
  • @Code-Guru yes "Auto calculate" doesn't mean anything but i add this word for understand my question what i want.....also thank you so much for great help using " Text " instead of integer so i will change it too....once again thanks for help. – Silent Heart Jan 05 '13 at 19:44

3 Answers3

5

I suggest use a DocumentFilter this will allow us to kill 2 birds with 1 stone.

1) we need to filter what is inputted to JTextFields to make sure our calculation wont go wrong

2) We need to update the total on the fly i.e as more digits are added/removed.

Here is an example I made which uses DocumentFilter and as you will see the Total field will be updated each time a new digit is entered/added to the JTextField(s) (also it wont allow alphabetic characters etc only digits):

enter image description here

import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.DocumentFilter.FilterBypass;

public class DocumentFilterOnTheFlyCalculation {

    public DocumentFilterOnTheFlyCalculation() {
        createAndShowGui();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new DocumentFilterOnTheFlyCalculation();
            }
        });
    }

    private void createAndShowGui() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new GridLayout(4, 2));

        JLabel label1 = new JLabel("Add:");
        final JTextField jtf1 = new JTextField();

        JLabel label2 = new JLabel("Add:");
        final JTextField jtf2 = new JTextField();

        JLabel label3 = new JLabel("Subtract:");
        final JTextField jtf3 = new JTextField();

        JLabel totalLabel = new JLabel("Total:");
        final JTextField totalField = new JTextField("0");
        totalField.setEditable(false);

        DocumentFilter df = new DocumentFilter() {
            @Override
            public void insertString(FilterBypass fb, int i, String string, AttributeSet as) throws BadLocationException {

                if (isDigit(string)) {
                    super.insertString(fb, i, string, as);
                    calcAndSetTotal();
                }
            }

            @Override
            public void remove(FilterBypass fb, int i, int i1) throws BadLocationException {
                super.remove(fb, i, i1);
                calcAndSetTotal();
            }

            @Override
            public void replace(FilterBypass fb, int i, int i1, String string, AttributeSet as) throws BadLocationException {
                if (isDigit(string)) {
                    super.replace(fb, i, i1, string, as);
                    calcAndSetTotal();

                }
            }

            private boolean isDigit(String string) {
                for (int n = 0; n < string.length(); n++) {
                    char c = string.charAt(n);//get a single character of the string
                    //System.out.println(c);
                    if (!Character.isDigit(c)) {//if its an alphabetic character or white space
                        return false;
                    }
                }
                return true;
            }

            void calcAndSetTotal() {
                int sum = 0;

                if (!jtf1.getText().isEmpty()) {
                    sum += Integer.parseInt(jtf1.getText());//we must add this
                }
                if (!jtf2.getText().isEmpty()) {
                    sum += Integer.parseInt(jtf2.getText());//we must add this
                }
                if (!jtf3.getText().isEmpty()) {
                    sum -= Integer.parseInt(jtf3.getText());//we must subtract this
                }

                totalField.setText(String.valueOf(sum));
            }
        };

        ((AbstractDocument) (jtf1.getDocument())).setDocumentFilter(df);
        ((AbstractDocument) (jtf2.getDocument())).setDocumentFilter(df);
        ((AbstractDocument) (jtf3.getDocument())).setDocumentFilter(df);

        frame.add(label1);
        frame.add(jtf1);
        frame.add(label2);
        frame.add(jtf2);
        frame.add(label3);
        frame.add(jtf3);
        frame.add(totalLabel);
        frame.add(totalField);

        frame.pack();
        frame.setVisible(true);
    }
}
David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
  • 1
    Thanks for reply sir @David Kroukamp sir actually i am beginner with JAVA and i am not familiar with DocumentFilter, InputVerifier and DocumentListener....i am confuse to how to use with my source code so please can you little help with source code how to do it ? – Silent Heart Jan 05 '13 at 19:17
  • Thanks for reply sir @David Kroukamp .... yes sir i looking your update and i am going to try it to do with my source code....if i will fail then again i will contact you but sorry don't mind for disturbance....thank you much for great help. – Silent Heart Jan 05 '13 at 19:25
  • 1
    dear sir @David Kroukamp .... thank you so much for great help and its fine working me.... – Silent Heart Jan 06 '13 at 17:55
  • dear sir @David Kroukamp i need some more help ASAP about above your source code of auto calculation. how i will put restrictions so user wont enter value more then 99999 in all invoice TextFileds.thanks – Silent Heart Feb 13 '13 at 15:41
  • @SilentHeart see [this](http://stackoverflow.com/questions/14305921/detecting-jtextfield-deselect-event/14305952#14305952) answer. I would suggest you use `DocumentFilter` as you already using it and it can be done with minimal changes to code – David Kroukamp Feb 13 '13 at 20:29
2

If you don't need an update for each keystroke, this alternate approach uses both a FocusListener and a PropertyChangeListener to update() the total as changes accrue.

image

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • +1 for `FocusListener`. I was going to suggest it and make a example but though the every key stroke better – David Kroukamp Jan 05 '13 at 20:03
  • 1
    @DavidKroukamp: Thank you; it's slightly simpler to use `JFormattedTextField` for numeric input, but your `DocumentFilter` may be more flexible. – trashgod Jan 05 '13 at 20:09
  • I intiailly suggested that and a `InputVerifier` (dropped verifier for same reason as `FocusListener`) and `JFormattedTextField` actually doesnt seem fit for variable lenght masks, i.e I put a mask to accept 6 digits, if I only enter 2 digits and click next `JFormattedTextfield` the input would disappear as it didnt match the mask (of 6 digits) I see you can create a variable length mask, but even more work :P.. – David Kroukamp Jan 05 '13 at 20:12
  • @David Kroukamp never to confuse the user [i.e I put a mask to accept 6 digits, if I only enter 2 digits and click next](http://stackoverflow.com/a/8582656/714968), then to use JSpinner instead – mKorbel Jan 05 '13 at 20:36
  • @David Kroukamp please can I rollback my idiotic comment about JSpinner, this is the same road to the hell and usage of JFormattedTextField, [JSpinner with SpinnerNumberModel required DocumentFilter too](http://stackoverflow.com/a/9779203/714968), otherwise is possible to input non_numeric chars too, sorry winner is plain JTextField with DocumentListener & DocumentFilter – mKorbel Jan 05 '13 at 20:47
0

enter image description hereYou can use MouseEntered event to auto display computed value in jtextfield as shown in the code

private void TxtnetpayMouseEntered(java.awt.event.MouseEvent evt) {                                       
  DecimalFormat numberFormat = new DecimalFormat("#.00");
  double totalgrosssalary = Double.parseDouble(Txttotalgrosspay.getText());
  double totaldeduct = Double.parseDouble(Txttotaldeduction.getText());     

    netpay = totalgrosssalary - totaldeduct; 
    String netpayy = String.valueOf(numberFormat.format(netpay));

    Txtnetpay.setText(netpayy);
}