1

我想从 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();

我收到一个错误,说非法前向引用。我该如何解决?

这是固定的。

现在当我使用以下代码时:

    public class CalcUI extends javax.swing.JFrame {

双 num1 ; 双 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)

我该如何解决?代码有什么问题?

4

3 回答 3

3

我想您的 JTextField 组件在您调用时不会被初始化:

String n1 = val1.getText();
String n2 = val2.getText();
于 2012-10-29T02:23:05.853 回答
2

如果您使用此代码,您将看到您的输入是什么。

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();

}
于 2015-07-07T05:45:35.480 回答
1

您缺少将进行计算的“等于”按钮。向该按钮添加一个侦听器,然后在侦听器的 actionPerformed() 中 getText() 然后计算计算。另外,我想没有必要将 n1 和 n2 作为类级变量。

于 2012-10-29T02:24:19.107 回答