如何自动计算JAVA中文本字段的输入数值 [英] How to Auto Calculate input numeric values of Text Field in JAVA

查看:104
本文介绍了如何自动计算JAVA中文本字段的输入数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Netbeans 7.2的JAVA中的文本字段自动计算有问题

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.

请检查快照:

图片http://s14.postimage.org/95zxgp575/image.jpg

我的源代码:

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);
        }


推荐答案

我建议使用 DocumentFilter 这将允许我们用1石头杀死2只鸟。

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

1)我们需要过滤输入的内容 JTextField s以确保我们的计算不会出错

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

2)我们需要动态更新总数即添加/删除更多数字。

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

以下是我使用 DocumentFilter 制作的示例,您将看到每次输入新数字/添加到 JTextField (s)时,总计字段将更新(也不会允许字母字符等仅数字):

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):

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);
    }
}

这篇关于如何自动计算JAVA中文本字段的输入数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆