首页 > 解决方案 > 在 Java 程序的 GUI 中打印结果的小问题

问题描述

图形界面照片:

在此处输入图像描述

我正在创建一个简单的 Java 程序,其中用户输入一个数字,然后单击计算按钮,输入数字的平方根的结果出现在该字段中。但是我在制作这个小程序时遇到了麻烦。供用户输入输入数字的字段称为 inputText。我创建了一个名为 inputText 的字符串变量来接收用户以字符串格式输入的内容。然后我创建了一个名为 inputValueInteger 的整数变量来转换为整数。在计算结果的按钮中,我调用了calcButton. 在这个按钮的方法中,我调用了calculate( inputValueInInteger)方法。这个inputValueInInteger变量必须取自resultFieldActionPerformed。在calcButtonActionPerformed方法中,我调用了calculate( inputValueInInteger)方法。这种方法(inputValueInInteger) 计算作为参数传递的数字的平方的结果。但是,我无法让 GUIresultField字段打印结果。请问有人可以帮忙吗?

public class Calc extends javax.swing.JFrame {
    int inputValueInInteger;

    public Calc() {
        initComponents();
    }

 private void inputTextActionPerformed(java.awt.event.ActionEvent evt) {                                          
        String inputFieldInString = inputText.getText().toString();
        inputValueInInteger = Integer.parseInt(inputFieldInString);
    }                                         

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

        int result = calculate(inputValueInInteger);
        String resultInString = String.valueOf(result);
        resultField.setText(resultInString);
    }                                           

    private void calcButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
        calculate(inputValueInInteger);
    }                                          
    
    public int calculate(inputValueInInteger) {
        return inputValueInInteger * inputValueInInteger;
    }
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new InterfaceGrafica().setVisible(true);
                calculate(inputValueInInteger);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton calcButton;
    private javax.swing.JTextField inputText;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField resultField;
    // End of variables declaration                   
}

标签: javanetbeans

解决方案


推荐阅读