3

I am trying to built a Java application using JFrame with Swing, and I have 5 JTextField instances in there. One of these is for Sum.

I need JTextField to change automatically as soon as I type some number in text fields.

How is that possible?

What I wrote is here.

private void displaytotalActionPerformed(java.awt.event.ActionEvent evt) {
// display total:
Float num1,num2,num3,num4,num5,num6,result;
num1 = display1b.getText().equals("") ? 0 : Float.parseFloat(display1b.getText());
num2 = display2b.getText().equals("") ? 0 : Float.parseFloat(display2b.getText());
num3 = display3b.getText().equals("") ? 0 : Float.parseFloat(display3b.getText());
num4 = display4b.getText().equals("") ? 0 : Float.parseFloat(display4b.getText());
num5 = display5b.getText().equals("") ? 0 : Float.parseFloat(display5b.getText());
num6 = display6b.getText().equals("") ? 0 : Float.parseFloat(display6b.getText());

result = num1+num2+num3+num4+num5+num6;

System.out.println(result);
}

I tried to get the sum and display it in this textfield using button and it worked. But i want it to be done automatically. But the code above doesnt display anything on textfield.

I am quite new to this and I appreciate if you kindly guide.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
user1971804
  • 111
  • 1
  • 3
  • 11
  • What have you tried? Stackoverflow isn't going to write your crappy code for you. – sjr Jan 12 '13 at 06:10
  • Which part of it are you having a problem with - detecting data entry, parsing the text to a number, adding the numbers? For better help sooner, post an [SSCCE](http://sscce.org/) of current code (but note it only needs 3 text fields - 2 for entry and one for result). BTW - are the numbers integers? – Andrew Thompson Jan 12 '13 at 06:11
  • *"I appreciate if you kindly guide"* That is an odd thing to write, given you have ignored my advice to post an SSCCE. A good way to express appreciation is to listen carefully and follow advice. Note that if an `ActionListener` is aded to the input text fields, and the user presses `Enter` when one of those text fields is in focus, the listener will be activated. You might also look into [`DocumentListener`](http://docs.oracle.com/javase/7/docs/api/javax/swing/event/DocumentListener.html). – Andrew Thompson Jan 12 '13 at 06:39

2 Answers2

7

I think you're looking for

An alternative to this is to use a JFormattedTextField and using listeners.

A couple of recommendations.

  • Develop intuition, usually properties to java classes are changed by (get|set)Property. Use an IDE like Netbeans and it will help you finding stuff.
  • Automatization is usually achieved by using a Listener, just learn when to use which (this is also part of intuition).
  • When you find yourself writing repeated code, consider using a function. i.e.

Instead of having 6 times:

display1b.getText().equals("") ? 0 : Float.parseFloat(display1b.getText());

Consider having your fields in an ArrayList and write a function that iterates them and have a single line of the above to set all the values.

  • Follow the JavaTutorials before additional efforts of hard-coding, or asking here. Will be more productive to you. Because you will learn how to learn for yourself and dig into documentation.
Roger
  • 2,912
  • 2
  • 31
  • 39
  • You are right, but it's not what the OP is looking for - *"I need JTextField to change automatically as soon as I type some number in text fields"* would be the part of the question I'd be focusing on. If you have some ideas about how to achieve this, then please update your answer :D – MadProgrammer Jan 12 '13 at 06:51
  • @MadProgrammer What for? instead of guide, you provided a full coded answer. – Roger Jan 12 '13 at 06:59
  • Because you might have a better idea, or solution (and I really don't want to see your answer draw any down votes) – MadProgrammer Jan 12 '13 at 07:10
  • See +1 nice use of JFormattedTextField! – MadProgrammer Jan 12 '13 at 07:14
6

You need to use a DocumentListener attached to each of the number fields. This will alert you when the fields have changed.

From there you need to call some sort of sum method to automatically update the tally.

Something like...

public class AutoSum {

    public static void main(String[] args) {
        new AutoSum();
    }

    public AutoSum() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new AutoSumPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class AutoSumPane extends JPanel {

        private JTextField[] fields;
        private JTextField tally;

        public AutoSumPane() {

            fields = new JTextField[5];

            DocumentListener docHandler = new DocumentListener() {
                @Override
                public void insertUpdate(DocumentEvent e) {
                    autoSum();
                }

                @Override
                public void removeUpdate(DocumentEvent e) {
                    autoSum();
                }

                @Override
                public void changedUpdate(DocumentEvent e) {
                    autoSum();
                }
            };

            setLayout(new GridLayout(6, 1));
            for (int index = 0; index < 5; index++) {
                fields[index] = new JTextField(3);
                fields[index].getDocument().addDocumentListener(docHandler);
                fields[index].setHorizontalAlignment(JTextField.RIGHT);
                add(fields[index]);
            }

            tally = new JTextField(3);
            tally.setHorizontalAlignment(JTextField.RIGHT);
            tally.setEditable(false);

            add(tally);

        }

        protected float getValue(JTextField field) {
            float value = 0;
            String text = field.getText();
            if (text != null && text.trim().length() > 0) {
                try {
                    value = Float.parseFloat(text.trim());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return value;
        }

        protected void autoSum() {
            float sum = 0;
            for (JTextField field : fields) {
                sum += getValue(field);
            }
            tally.setText(NumberFormat.getNumberInstance().format(sum));
        }
    }
}

for example.

Take a look at How to Write a DocumentListener for more information.

While you're at it, you might find Implementing a DocumentFilter of interest (and this for some examples)

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Thanks alot MadProgrammer. Now I know DocumentListener is the thing i need to learn . – user1971804 Jan 12 '13 at 07:03
  • 1
    +1 nice mad. also see this [example](http://stackoverflow.com/questions/12677638/simultaneously-update-text-area-while-typing-in-text-field/12678020#12678020) and this [here](http://stackoverflow.com/questions/14174776/how-to-auto-calculate-input-numeric-values-of-text-field-in-java/14174868#14174868) (the last examples shows how to use document filter to calculate sums on the fly and setText accordingly of JTextField) – David Kroukamp Jan 12 '13 at 07:14
  • @david you just like me up voting your answers ;) – MadProgrammer Jan 12 '13 at 07:15
  • @MadProgrammer hahaha it has its perks :). but more so you have answered the question so posting a duplicate solution is useless (and un-moral), where as now OP can see the way to go and some other examples too – David Kroukamp Jan 12 '13 at 07:17
  • @MadProgrammer : Seems to me, instead of providing external links, you could have provided the links to your own answers, which in my opinion are way too good. I do remember some of your previous answers related to DocumentListener, if I am not mistaken. – nIcE cOw Jan 12 '13 at 08:23
  • @GagandeepBali that's a good point, but this demonstrates a possible solution using the OPs question – MadProgrammer Jan 12 '13 at 08:29
  • @MadProgrammer : As to why I said that, I totally liked this approach, far better than what I could have thought :-). Though it is missing, just one thingy, which is to check for the Integer input for the `JTextField`, so that the OP too can understand the benefits of the same. – nIcE cOw Jan 12 '13 at 08:38
  • 1
    @GagandeepBali Fair point - I was encouraging the OP to read the docs on `DocumentFilter` and the `Float.parseFloat` is wrapped in an exception handler to short circuit possible issues - but a fair point – MadProgrammer Jan 12 '13 at 09:00