【问题标题】:How to Auto Calculate input numeric values of Text Field in JAVA如何在JAVA中自动计算文本字段的输入数值
【发布时间】:2012-12-19 22:22:45
【问题描述】:

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

我的问题是我是否会在文本字段中输入数值,即(入场费、月费、交通费等)以进行自动添加,然后在文本字段中输入数值,即(会费)以从上述自动添加中自动减去在单击提交按钮以在数据库中插入总值之前,我将如何在单击提交按钮之前在文本字段(总计)中获取这些数值的结果。

请检查快照:

我的源代码:

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

【问题讨论】:

  • “自动计算”是什么意思?你能更详细地解释一下吗?
  • 附注通常,您不应将计算数据存储在数据库中。大多数 DBMS 都包含根据要求进行此类计算的功能。这是首选,因为无需更改“计算”数据即可轻松修改原始数据。
  • 感谢@Code-Guru 的回复 .... 我想自动计算所有文本字段数值的总和,然后在文本字段名称总计中显示总和值...如果我缴纳会费,我也想要自动从文本字段名称 Total 中的所有值的总和中减去的值......请检查我的快照图像以更好地理解我的问题......
  • 再次,“自动计算”是什么意思?再次使用这个词并不能解释它的含义。
  • 我了解您想要获取数值并进行某种计算。但是,我不清楚您是要在用户输入数据时还是在用户单击提交时进行此计算。也许我只是对你的措辞感到厌烦。 “自动计算”在我的词汇表中没有任何意义。

标签: java swing jtextfield


【解决方案1】:

我建议使用DocumentFilter,这样我们可以用 1 块石头杀死 2 只鸟。

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

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

这是我使用DocumentFilter 制作的示例,您将看到,每次在JTextField(s) 中输入/添加新数字时,Total 字段都会更新(它也不允许字母字符等只有数字):

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 先生的回复,实际上我是 JAVA 的初学者,我不熟悉 DocumentFilter、InputVerifier 和 DocumentListener ....我对如何使用我的源代码感到困惑,所以请你能帮我一点源代码怎么做吗?
  • 感谢@David Kroukamp 先生的回复 .... 是的,先生,我正在查看您的更新,我将尝试使用我的源代码...如果我会再次失败,那么我会与您联系,但请不要介意打扰......非常感谢您的帮助。
  • 亲爱的先生@David Kroukamp .... 非常感谢您的大力帮助和它对我的良好工作....
  • 亲爱的先生@David Kroukamp 我需要更多关于您的自动计算源代码的帮助。我将如何设置限制,以便用户不会在所有发票 TextFileds.thanks 中输入超过 99999 的值
  • @SilentHeart 见this 答案。我建议您使用 DocumentFilter,因为您已经在使用它,并且只需对代码进行最少的更改即可完成
【解决方案2】:

如果您不需要为每次击键进行更新,则此 alternate approach 使用 FocusListenerPropertyChangeListenerupdate() 的总和作为更改累积。

【讨论】:

  • +1 表示FocusListener。我打算建议它并举个例子,但虽然每个按键都更好
  • @DavidKroukamp:谢谢;使用JFormattedTextField 进行数字输入稍微简单一些,但您的DocumentFilter 可能更灵活。
  • 我最初建议和InputVerifier(出于与FocusListener 相同的原因放弃验证器)和JFormattedTextField 实际上似乎不适合可变长度掩码,即我放置了一个掩码以接受6 位数字,如果我只输入 2 位数字并单击下一步 JFormattedTextfield 输入将消失,因为它不匹配掩码(6 位数字)我看到你可以创建一个可变长度掩码,但更多的工作:P..
  • @David Kroukamp 永远不要混淆用户 i.e I put a mask to accept 6 digits, if I only enter 2 digits and click next,然后改用 JSpinner
  • @David Kroukamp 请让我回滚关于 JSpinner 的愚蠢评论,这是通往地狱和使用 JFormattedTextField 的同一条道路,JSpinner with SpinnerNumberModel required DocumentFilter too,否则也可以输入非数字字符,抱歉获胜者是带有 DocumentListener 和 DocumentFilter 的普通 JTextField
【解决方案3】:

enter image description here您可以使用 MouseEntered 事件在 jtextfield 中自动显示计算值,如代码所示

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 2023-03-04
    • 2018-06-03
    • 1970-01-01
    • 2013-10-09
    相关资源
    最近更新 更多