2016-06-12 17 views

回答

1

我想在这两个文本框的值,一旦加入我进入他们 和填充结果在另一个文本框“txtTotal”不使用 按钮。

这可以通过使用JTextFieldDocumentListener来完成。

这里是覆盖在如何使用它们的基础知识教程:How to Write a Document Listener


从教程重要摘录:

文档事件发生时的文件改变任何 内容way

这将允许您监视文本字段值的变化并反应acc ordingly。对于你的情况,这将涉及检查的2个输入值和提供的都是有效的,在输出文本字段


这里显示的结果是一个快速SSCCE(Stack overflow glossary of acronyms):

public class AutoCalculationDemo { 
    public static void main(String[] args) { 
     JTextField firstInput = new JTextField(); 
     JTextField secondInput = new JTextField(); 
     JTextField output = new JTextField(); 
     output.setEditable(false); 

     DocumentListener additionListener = new DocumentListener() { 
      @Override 
      public void insertUpdate(DocumentEvent e) { 
       attemptAddition(); 
      } 

      @Override 
      public void removeUpdate(DocumentEvent e) { 
       attemptAddition(); 
      } 

      @Override 
      public void changedUpdate(DocumentEvent e) { 
       attemptAddition(); 
      } 

      public void attemptAddition(){ 
       try{ 
        double firstValue = Double.parseDouble(firstInput.getText()); 
        double secondValue = Double.parseDouble(secondInput.getText()); 
        output.setText(String.valueOf(firstValue + secondValue)); 
       }catch (NumberFormatException nfe){ 
        System.out.println("Invalid number(s) provided"); 
       } 
      } 
     }; 
     firstInput.getDocument().addDocumentListener(additionListener); 
     secondInput.getDocument().addDocumentListener(additionListener); 

     JFrame frame = new JFrame(); 
     JPanel panel = new JPanel(new GridLayout(3,2)); 
     panel.add(new JLabel("First number: ")); 
     panel.add(firstInput); 
     panel.add(new JLabel("Second number: ")); 
     panel.add(secondInput); 
     panel.add(new JLabel("Output: ")); 
     panel.add(output); 
     frame.add(panel); 
     frame.setSize(250,150); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 
} 
+0

为计算器更好(JTextField和数字)来使用DocumentFilter,那么关于Double.parse的所有代码行都是无用的... – mKorbel