java 如何从文本字段获取文本到变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13115141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:32:48  来源:igfitidea点击:

how to get the text from a text field to a variable?

javaswingvariablestextfieldgettext

提问by LightMikeE

i want to get the value from the txt field val1 and val2 and store it in the variables n1 and n2. then n1 and n2 will be parsed to get the value for the calculator. here is the code:

我想从 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

}

}

the problem is that in the declaration

问题是在声明中

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

i get an error whioch says illegal forward reference. how do i fix this?

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

this was fixed.

这是固定的。

now when i use the following code:

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

    public class CalcUI extends javax.swing.JFrame {

Double num1 ; Double num2 ;

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

i get a build error which says:

我收到一个构建错误,它说:

    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.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
String n1 = val1.getText();
String n2 = val2.getText();
0(EventQueue.java:102) at java.awt.EventQueue.run(EventQueue.java:662) at java.awt.EventQueue.run(EventQueue.java:660) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain.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)

how do i fix this? what is wrong with the code?

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

回答by travega

I imagine your JTextField components will not have been initialised by the time you are calling:

我想您的 JTextField 组件在您调用时尚未初始化:

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

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

}

回答by Ali yasar Erdogan

If you use this code you will see what your input is.

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

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

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

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

String n1;                                   
n1 = yourTextField.getText();

}

So, this should store your data to n1.

因此,这应该将您的数据存储到 n1。

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

String n1;                                   
n1 = yourTextField.getText();

}
##代码##

回答by ignis

You're missing the "equals" button that will do the computation. Add a listener to that button, and in the listener's actionPerformed() you getText() and then compute the calculation. Also, I guess there's no need to have n1 and n2 as class-level variables.

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