【发布时间】:2020-08-31 19:08:58
【问题描述】:
我一直在实现一个使用JTextField 将两个数字相加的程序。
我已经能够让它运行,但是我想更改代码,以便将来自 JTextField 的值发送到方法文件(位于同一文件夹中)以添加在一起。添加值后,我希望将答案发送回第三个JTextField 以显示答案。我已经设置好了,当按下JButton 时,会调用该方法,但是我不知道如何编写该方法并在第三个JTextField 中获得答案。
这是我的代码,A 类是格式,B 类是方法文件:
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();
int x = Integer.parseInt(s1);
int y = Integer.parseInt(s2);
int z = 0;
if (e.getSource() == b1) {
B b = new B();
b.mymethod();
}
String result = String.valueOf(z);
tf3.setText(result);
}
public static void main(String[] args) {
new A();
}
}
import javax.swing.*;
import java.awt.event.*;
public class B {
public static void mymethod() {
int x, y;
int z = x + y;
}
}
【问题讨论】:
-
B.myMethod() 不应编译。 x、y、z 未定义。你需要参数。
-
@NomadMaker 感谢您的回复。你能详细说明一下吗?
-
类似于 ``public static int myMethod(int x, int y) { return x + y; }