2012-10-29 105 views
0

我想從txt字段val1和val2中獲取值並將其存儲在變量n1和n2中。那麼n1和n2將被解析以獲得計算器的值。這裏是代碼:如何將文本字段中的文本轉換爲變量?

public class CalcUI extends javax.swing.JFrame { 
    String n1 = val1.getText(); 
    String n2 = val2.getText(); 
    double num1 = Double.parseDouble(n1); 
    double num2 = Double.parseDouble(n2); 

/** 
* Creates new form CalcUI 
*/ 
public CalcUI() { 

    initComponents(); 
} 

/** 
* This method is called from within the constructor to initialize the form. 
* WARNING: Do NOT modify this code. The content of this method is always 
* regenerated by the Form Editor. 
*/ 
@SuppressWarnings("unchecked") 
// <editor-fold defaultstate="collapsed" desc="Generated Code"> 
private void initComponents() { 

    val1 = new javax.swing.JTextField(); 
    val2 = new javax.swing.JTextField(); 
    plus = new javax.swing.JButton(); 
    multiply = new javax.swing.JButton(); 
    clr = new javax.swing.JButton(); 
    exit = new javax.swing.JButton(); 
    minus = new javax.swing.JButton(); 
    divide = new javax.swing.JButton(); 
    ans = new javax.swing.JLabel(); 

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 

    plus.setText("+"); 
    plus.setMaximumSize(new java.awt.Dimension(41, 41)); 
    plus.setMinimumSize(new java.awt.Dimension(41, 41)); 
    plus.setPreferredSize(new java.awt.Dimension(41, 41)); 
    plus.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      plusActionPerformed(evt); 
     } 
    }); 

    multiply.setText("*"); 
    multiply.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      multiplyActionPerformed(evt); 
     } 
    }); 

    clr.setText("Clear"); 
    clr.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      clrActionPerformed(evt); 
     } 
    }); 

    exit.setText("Exit"); 
    exit.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      exitActionPerformed(evt); 
     } 
    }); 

    minus.setText("-"); 
    minus.setMaximumSize(new java.awt.Dimension(41, 41)); 
    minus.setMinimumSize(new java.awt.Dimension(41, 41)); 
    minus.setPreferredSize(new java.awt.Dimension(41, 41)); 
    minus.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      minusActionPerformed(evt); 
     } 
    }); 

    divide.setText("/"); 
    divide.setMaximumSize(new java.awt.Dimension(41, 41)); 
    divide.setMinimumSize(new java.awt.Dimension(41, 41)); 
    divide.setPreferredSize(new java.awt.Dimension(41, 41)); 
    divide.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      divideActionPerformed(evt); 
     } 
    }); 

    ans.setBorder(javax.swing.BorderFactory.createEtchedBorder()); 

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); 
    getContentPane().setLayout(layout); 
    layout.setHorizontalGroup(
     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGroup(layout.createSequentialGroup() 
      .addContainerGap() 
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
       .addComponent(val1) 
       .addComponent(val2) 
       .addGroup(layout.createSequentialGroup() 
        .addComponent(clr) 
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) 
        .addComponent(exit))) 
      .addContainerGap()) 
     .addGroup(layout.createSequentialGroup() 
      .addGap(134, 134, 134) 
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) 
       .addComponent(multiply, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) 
       .addComponent(plus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) 
      .addGap(77, 77, 77) 
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
       .addComponent(minus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) 
       .addComponent(divide, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) 
      .addGap(143, 143, 143)) 
     .addGroup(layout.createSequentialGroup() 
      .addContainerGap() 
      .addComponent(ans, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) 
      .addContainerGap()) 
    ); 
    layout.setVerticalGroup(
     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGroup(layout.createSequentialGroup() 
      .addGap(46, 46, 46) 
      .addComponent(val1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
      .addGap(18, 18, 18) 
      .addComponent(val2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) 
      .addComponent(ans, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) 
      .addGap(26, 26, 26) 
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) 
       .addComponent(plus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
       .addComponent(minus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) 
      .addGap(34, 34, 34) 
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) 
       .addComponent(multiply, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) 
       .addComponent(divide, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) 
      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE) 
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) 
       .addComponent(clr) 
       .addComponent(exit)) 
      .addContainerGap()) 
    ); 

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

private void plusActionPerformed(java.awt.event.ActionEvent evt) {          
    double add = num1 + num2; 
    ans.setText(Double.toString(add)); 
     // TODO add your handling code here: 
}          

private void minusActionPerformed(java.awt.event.ActionEvent evt) {          
    double min = num1 - num2; 
    ans.setText(Double.toString(min));          
    // TODO add your handling code here: 
}          

private void divideActionPerformed(java.awt.event.ActionEvent evt) {          
    double div = num1/num2; 
    ans.setText(Double.toString(div)); 
     // TODO add your handling code here: 
}          

private void exitActionPerformed(java.awt.event.ActionEvent evt) {          
    System.exit(0); 
     // TODO add your handling code here: 
}          

private void clrActionPerformed(java.awt.event.ActionEvent evt) {          
     val1.setText(""); 
     val2.setText(""); 
      ans.setText(""); 
     // TODO add your handling code here: 
}         

private void multiplyActionPerformed(java.awt.event.ActionEvent evt) {           
    double mult = num1 * num2; 
    ans.setText(Double.toString(mult)); 
     // TODO add your handling code here: 
}           

/** 
* @param args the command line arguments 
*/ 
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(CalcUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (InstantiationException ex) { 
     java.util.logging.Logger.getLogger(CalcUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (IllegalAccessException ex) { 
     java.util.logging.Logger.getLogger(CalcUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
     java.util.logging.Logger.getLogger(CalcUI.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 CalcUI().setVisible(true); 
     } 
    }); 
} 
// Variables declaration - do not modify 
private javax.swing.JLabel ans; 
private javax.swing.JButton clr; 
private javax.swing.JButton divide; 
private javax.swing.JButton exit; 
private javax.swing.JButton minus; 
private javax.swing.JButton multiply; 
private javax.swing.JButton plus; 
private javax.swing.JTextField val1; 
private javax.swing.JTextField val2; 
// End of variables declaration 

}

的問題是,在申報

String n1 = val1.getText(); 
String n2 = val2.getText(); 

我得到whioch說,非法向前引用錯誤。我該如何解決?

這是固定的。

現在,當我使用下面的代碼:

public class CalcUI extends javax.swing.JFrame { 

雙NUM1; Double num2;

/** 
* Creates new form CalcUI 
*/ 

public CalcUI(){ 
    val1 = new javax.swing.JTextField(); 
    val2 = new javax.swing.JTextField(); 

    num1 = Double.parseDouble(val1.getText()); 
    num2 = Double.parseDouble(val2.getText()); 

    initComponents(); 
} 

我得到它說生成錯誤:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String 
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1011) 
at java.lang.Double.parseDouble(Double.java:540) 
at CalcUI.<init>(CalcUI.java:24) 
at CalcUI$7.run(CalcUI.java:227) 
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251) 
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:701) 
at java.awt.EventQueue.access$000(EventQueue.java:102) 
at java.awt.EventQueue$3.run(EventQueue.java:662) 
at java.awt.EventQueue$3.run(EventQueue.java:660) 
at java.security.AccessController.doPrivileged(Native Method) 
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) 
at java.awt.EventQueue.dispatchEvent(EventQueue.java:671) 
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244) 
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163) 
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151) 
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147) 
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139) 
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97) 

我該如何解決這一問題?代碼有什麼問題?

+0

提示:哪裏是 「等於」 按鈕? – ignis

回答

3

我想,你的JTextField組件將不會被你所呼叫的時間初始化:

String n1 = val1.getText(); 
String n2 = val2.getText(); 
0

你缺少「等於」按鈕,將做計算。向該按鈕添加一個偵聽器,並在偵聽器的actionPerformed()中添加getText(),然後計算計算結果。另外,我想沒有必要將n1和n2作爲類級變量。

+0

我的計算器不能像那樣工作。兩個字段中的兩個值按加號,然後標籤顯示答案 – LightMikeE

+1

@ user1781783:仍然需要一個處理程序,getText在語句執行時讀取該字段的值。如果您在初始化期間執行它,則這些字段將爲空,因爲沒有用戶可以快速輸入。當你需要閱讀字段值時,你需要閱讀這些字段值,天氣是一個標有「=」或「+」或「什麼」的按鈕並不重要。 – ted

1

如果您使用此代碼,您將看到您的輸入是什麼。

private void yourActionButtonActionPerformed(java.awt.event.ActionEvent evt) {  

JOptionPane.showMessageDialog(null,yourTextField.getText()); 

} 

所以,這應該將數據存儲到N1。

private void yourActionButtonActionPerformed(java.awt.event.ActionEvent evt) { 

String n1;         
n1 = yourTextField.getText(); 

} 
相關問題