【问题标题】:Accessing variable from method class to use in GUI class从方法类访问变量以在 GUI 类中使用
【发布时间】:2020-09-02 14:24:16
【问题描述】:

我正在编写代码以从两个文本字段中添加 2 个数字,并将总和显示在第三个文本字段中。但是,当我将第三个文本字段设置为显示值 Z(即总和)时,我收到错误“找不到符号”。我做错了什么?

import javax.swing.*;  
import java.awt.event.*;  
public class A implements ActionListener{     
    JTextField tf1,tf2,tf3;  
    JButton b1;   
    A(){  
        JFrame f= new JFrame(); 
        JLabel myLabel= new JLabel("Enter First Value");
        myLabel.setBounds(50,50,150,20); 
        tf1=new JTextField();  
        tf1.setBounds(50,75,250,20);
        JLabel mysecondLabel= new JLabel("Enter Second Value");
        mysecondLabel.setBounds(50,125,150,20);  
        tf2=new JTextField();  
        tf2.setBounds(50,150,250,20);  
        tf3=new JTextField();  
        tf3.setBounds(160,225,140,20);  
        tf3.setEditable(false);   
        b1=new JButton("Sum");  
        b1.setBounds(50,225,95,20);
        b1.addActionListener(this); 

        f.add(tf1);f.add(myLabel);f.add(tf2);f.add(mysecondLabel);f.add(tf3);f.add(b1);  
        f.setSize(300,300);  
        f.setLayout(null);  
        f.setVisible(true);  
    }         

        public void actionPerformed(ActionEvent e) {  
        String s1=tf1.getText();  
        String s2=tf2.getText();
    if(e.getSource()!=b1){  
        return;  
    }
    
    int x = Integer.parseInt(s1);
    int y = Integer.parseInt(s2);
            
    String result = B.Z;

    tf3.setText(result); 
}  public static void main(String[] args) {  
    new A(); 
}
}
import javax.swing.*;  
import java.awt.event.*;
public class B {
    public static int myMethod(int x, int y) {
      int Z;
      Z = x + y;
      return Z;
      }
}

【问题讨论】:

    标签: java addition


    【解决方案1】:

    您的B 类没有名为Z 的静态字段,您可以通过调用B.Z 访问该字段。你没有打电话给myMethod(x, y);。试试String result = String.valueOf(B.myMethod(x, y)); 看看是否可行。

    【讨论】:

    • 您好,感谢您的回复。我试过了,但是现在我收到错误“不兼容的类型:int 无法转换为 String”。
    • 嗯,是的。您的 myMethod() 方法返回一个 int。您需要先将其转换为字符串,然后才能将其分配给result。给我一点时间来编辑我的答案以解决这个问题。
    • 优秀。在这种情况下,请将我的答案标记为已接受,以便遇到您问题的其他人可以看到如何解决它。谢谢。
    猜你喜欢
    • 2011-09-05
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    • 2019-09-20
    • 2012-07-04
    • 2017-12-20
    • 2012-06-03
    • 2013-09-08
    相关资源
    最近更新 更多