栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

每次更改jTextField时自动更新总和(Java)

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

每次更改jTextField时自动更新总和(Java)

@Reimeus
建议的那样,您需要将document
Listener添加到每个文本字段中。由于您要在
jButton1ActionPerformed()
方法中执行添加操作,因此,只要您的文本字段发生更改,我都会通知侦听器通知此方法。

注意
根据评论,我将代码更新为仅包含一个

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[]) {                //<editor-fold defaultstate="collapsed" desc=" Look and feel setting pre (optional) ">                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>                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}

几个指针:

  • 永远不要相信来自用户的输入。用户可能输入了错误的值( 例如,不是Integer的内容 )。因此,验证输入并检查输入是否可以真正解析总是一个好主意。记住这一点,我已经更新了您的

    jButton1ActionPerformed()
    方法

  • 另一种选择是使用格式化文本字段



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/453471.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号