4

我在使用 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);
        }
4

3 回答 3

5

我建议使用 aDocumentFilter这可以让我们用 1 块石头杀死 2 只鸟。

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

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

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

在此处输入图像描述

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);
    }
}
于 2013-01-05T18:22:42.327 回答
2

如果您不需要为每次击键进行更新,则此替代方法会在发生更改时同时使用 aFocusListener和 aPropertyChangeListenerupdate()计算总数。

图片

于 2013-01-05T19:43:11.507 回答
0

在此处输入图像描述您可以使用 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);
}                                      
于 2019-03-02T21:19:27.967 回答