【问题标题】:Updating the sum of jTextFields automatically everytime they change (Java)每次更改时自动更新 jTextFields 的总和(Java)
【发布时间】:2012-09-11 02:33:29
【问题描述】:

作为我学习 Java 的一部分,我使用 netbeans 制作了一个 jForm,其中包含三个 jTextField 供用户输入一些数字,然后这些数字的总和显示在另一个 jTextField 中。当然,这非常简单,但我希望能够在没有任何按钮的情况下做到这一点。每次修改 3 个文本字段中的任何一个时,我都不知道如何“更新”总和。谁能帮我?

这是我的代码(表单是在设计模式下使用 netbeans 完成的):

package sumfields;

public class Frame extends javax.swing.JFrame {


    public Frame() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        n1 = new javax.swing.JTextField();
        n2 = new javax.swing.JTextField();
        n3 = new javax.swing.JTextField();
        sum = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("n1");

        jLabel2.setText("n2");

        jLabel3.setText("n3");

        jLabel5.setText("result");

        jButton1.setText("Opperate");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(15, 15, 15)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel5)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(sum, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(30, 30, 30)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(n1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(n2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(n3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(n1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1))
                        .addGap(10, 10, 10)
                        .addComponent(n2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel2))
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(n3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(sum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1)
                    .addComponent(jLabel5))
                .addContainerGap(38, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        int r=Integer.parseInt(n1.getText())+Integer.parseInt(n2.getText())+Integer.parseInt(n3.getText());
        sum.setText(""+r);

    }

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Frame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JTextField n1;
    private javax.swing.JTextField n2;
    private javax.swing.JTextField n3;
    private javax.swing.JTextField sum;
    // End of variables declaration
}

【问题讨论】:

    标签: java swing jtextcomponent documentlistener


    【解决方案1】:

    您正在寻找的是DocumentListener

    向您的每个JTextFields n1n2n3 注册一个侦听器并调用您的方法jButton1ActionPerformed 以更新结果字段。

    【讨论】:

      【解决方案2】:

      正如@Reimeus 建议的那样,您需要将文档侦听器添加到每个文本字段。由于您在 jButton1ActionPerformed() 方法中执行添加,因此每当您的文本字段发生更改时,我都会通知侦听器调用此方法。

      注意基于 cmets,我更新了我的代码以仅包含一个 DocumentListener 并添加了一个 DocumentFilter 以仅接受数字输入。我还删除了原始代码中存在的按钮以执行求和

      这是您的更新代码:

      import javax.swing.event.DocumentEvent;
      import javax.swing.event.DocumentListener;
      import javax.swing.text.AbstractDocument;
      import javax.swing.text.AttributeSet;
      import javax.swing.text.BadLocationException;
      import javax.swing.text.DocumentFilter;
      
      public class Frame extends javax.swing.JFrame {
      
      
          public Frame() {
              initComponents();
          }
      
      
          @SuppressWarnings("unchecked")
          // <editor-fold defaultstate="collapsed" desc="Generated Code">
          private void initComponents() {
      
              n1 = new javax.swing.JTextField();
              n2 = new javax.swing.JTextField();
              n3 = new javax.swing.JTextField();
              sum = new javax.swing.JTextField();
              jLabel1 = new javax.swing.JLabel();
              jLabel2 = new javax.swing.JLabel();
              jLabel3 = new javax.swing.JLabel();
              jLabel5 = new javax.swing.JLabel();
      
              DocumentListener documentListener = new DocumentListener() {
      
                  @Override
                  public void removeUpdate(DocumentEvent e) {
                      performSummation(null);
                  }
      
                  @Override
                  public void insertUpdate(DocumentEvent e) {
                      performSummation(null);
                  }
      
                  @Override
                  public void changedUpdate(DocumentEvent e) {
                  }
              };
      
              DocumentFilter numericFilter = new DocumentFilter(){
      
                  @Override
                  public void insertString(FilterBypass fb, int offset,
                          String string, AttributeSet attr)
                          throws BadLocationException {
                      fb.insertString(offset, string.replaceAll("[^\\d]", ""), attr);
                  }
      
                  @Override
                  public void replace(FilterBypass fb, int offset, int length,
                          String text, AttributeSet attrs)
                          throws BadLocationException {
      
                      fb.replace(offset, length, text.replaceAll("[^\\d]", ""), attrs);
                  }
              };
      
              ((AbstractDocument) n1.getDocument()).setDocumentFilter(numericFilter);
              ((AbstractDocument) n2.getDocument()).setDocumentFilter(numericFilter);
              ((AbstractDocument) n3.getDocument()).setDocumentFilter(numericFilter);
      
              n1.getDocument().addDocumentListener(documentListener);
              n2.getDocument().addDocumentListener(documentListener);
              n3.getDocument().addDocumentListener(documentListener);
      
      
              setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
      
              jLabel1.setText("n1");
              jLabel2.setText("n2");
              jLabel3.setText("n3");
              jLabel5.setText("result");
      
      
              javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
              getContentPane().setLayout(layout);
              layout.setHorizontalGroup(
                  layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                  .addGroup(layout.createSequentialGroup()
                      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                          .addGroup(layout.createSequentialGroup()
                              .addGap(15, 15, 15)
                              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                  .addComponent(jLabel1)
                                  .addComponent(jLabel2)
                                  .addComponent(jLabel3)))
                          .addGroup(layout.createSequentialGroup()
                              .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                              .addComponent(jLabel5)))
                      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                          .addGroup(layout.createSequentialGroup()
                              .addComponent(sum, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                              .addGap(30, 30, 30)
                              .addContainerGap())
                          .addGroup(layout.createSequentialGroup()
                              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                  .addComponent(n1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                                  .addComponent(n2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                                  .addComponent(n3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
                              .addGap(0, 0, Short.MAX_VALUE))))
              );
              layout.setVerticalGroup(
                  layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                  .addGroup(layout.createSequentialGroup()
                      .addGap(32, 32, 32)
                      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                          .addGroup(layout.createSequentialGroup()
                              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                  .addComponent(n1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                  .addComponent(jLabel1))
                              .addGap(10, 10, 10)
                              .addComponent(n2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                          .addComponent(jLabel2))
                      .addGap(20, 20, 20)
                      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                          .addComponent(n3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                          .addComponent(jLabel3))
                      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                          .addComponent(sum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                          .addComponent(jLabel5))
                      .addContainerGap(38, Short.MAX_VALUE))
              );
      
              pack();
          }// </editor-fold>
      
          private void performSummation(java.awt.event.ActionEvent evt) {
              int total = 0;
              if(n1.getText().trim().length() > 0){
                  try{
                      total += Integer.parseInt(n1.getText());
                  }catch(NumberFormatException nbx){
                  }
              }
      
              if(n2.getText().trim().length() > 0){
                  try{
                      total += Integer.parseInt(n2.getText());
                  }catch(NumberFormatException nbx){
                  }
              }
      
              if(n3.getText().trim().length() > 0){
                  try{
                      total += Integer.parseInt(n3.getText());
                  }catch(NumberFormatException nbx){
                  }
              }
      
              sum.setText(""+total);
      
          }
      
          public static void main(String args[]) {
              /* Set the Nimbus look and feel */
              //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
              /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
               * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
               */
              try {
                  for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                      if ("Nimbus".equals(info.getName())) {
                          javax.swing.UIManager.setLookAndFeel(info.getClassName());
                          break;
                      }
                  }
              } catch (ClassNotFoundException ex) {
                  java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
              } catch (InstantiationException ex) {
                  java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
              } catch (IllegalAccessException ex) {
                  java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
              } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                  java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
              }
              //</editor-fold>
      
              /* Create and display the form */
              java.awt.EventQueue.invokeLater(new Runnable() {
                  public void run() {
                      new Frame().setVisible(true);
                  }
              });
          }
          // Variables declaration - do not modify
          private javax.swing.JLabel jLabel1;
          private javax.swing.JLabel jLabel2;
          private javax.swing.JLabel jLabel3;
          private javax.swing.JLabel jLabel5;
          private javax.swing.JTextField n1;
          private javax.swing.JTextField n2;
          private javax.swing.JTextField n3;
          private javax.swing.JTextField sum;
          // End of variables declaration
      }
      

      几点建议:

      • 永远不要相信来自用户的输入。用户可能会输入错误的值(说一些不是整数的东西)。因此,验证您的输入并检查是否可以实际解析输入始终是一个好主意。记住这一点,我已经更新了你的 jButton1ActionPerformed() 方法

      • 另一种选择是使用Formatted Text Fields

      【讨论】:

      • DocumentFilter 也很有用。这会在用户键入时进行验证,您可以禁止以这种方式进行编辑。有关示例,请参见 this forum post
      • @Sujay 嘿,非常感谢,你太棒了。我只是有一个疑问,如果我想摆脱计算按钮,我应该在哪里放置新代码?再次,非常感谢。
      • @AlexTerreaux:jButton1ActionPerformed() 只是一种方法。您可以将方法重命名为您喜欢的任何名称。删除按钮将不得不影响您的代码:)
      • 由于您对每个字段执行相同的操作,您可以只使用一个DocumentListener。更少的代码,更多的重用;)
      • 我同意@MadProgrammer 的观点,是的,我应该只用一个DocumentListener 修改代码...啊,懒惰! :(
      【解决方案3】:

      此替代approach 使用PropertyChangeListenerFocusListenerupdate() 使用JFormattedTextField 的值的总和。

      【讨论】:

        【解决方案4】:

        您可以使用焦点侦听器,也可以对输入 JTextField 使用动作侦听器

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-11-25
          • 1970-01-01
          • 2010-11-30
          • 1970-01-01
          • 2019-04-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多