[英]How do I bring in Double values from one ActionListener method into another to perform a calculation? Java
我正在创建基本二次方计算器的JFrame程序。 我已经创建了一个动作侦听器,将三个文本字段转换为三个Double值,分别等于a,b和c,这些值在二次公式中使用。 当用户完成操作时,我不知道如何将它们放入按钮的其他ActionListener中。 按钮的目的是在用户完成操作后执行二次方程式的计算,并在新的JFrame上显示答案。 这是我的代码,有人对如何执行此操作有建议吗?
编辑:尝试执行计算时出现错误,告诉我“找不到符号”
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.math.*;
public class GUISource extends JFrame {
private JTextField textA;
private JTextField textB;
private JTextField textC;
private JLabel labA;
private JLabel labB;
private JLabel labC;
private JButton butA;
private JButton butB;
private JButton butC;
public GUISource(){
super ("Quadratic Equatic");
setLayout (new FlowLayout());
labA = new JLabel("Enter your A value:");
add(labA);
textA = new JTextField(30);
add(textA);
butA = new JButton("Enter");
//add(butA);
labB = new JLabel("Enter your B value:");
add(labB);
textB = new JTextField(30);
add(textB);
//butB = new JButton("Enter");
//add(butB);
labC = new JLabel("Enter your C value:");
add(labC);
textC = new JTextField(30);
add(textC);
//butC = new JButton("Enter");
//add(butC);
add(butA);
listenPlease handle = new listenPlease();
//labA.addActionListener(handle);
//labB.addActionListener(handle);
//labC.addActionListener(handle);
//butA.addActionListener(handle);
//butB.addActionListener(handle);
//butC.addActionListener(handle);
textA.addActionListener(handle);
textB.addActionListener(handle);
textC.addActionListener(handle);
buttonListen handler = new buttonListen();
butA.addActionListener(handler);
}
private class listenPlease implements ActionListener{
public void actionPerformed (ActionEvent e){
String transfer = "";
if (e.getSource() == textA){
transfer = String.format("field 1 : %s", e.getActionCommand());
double a = Integer.parseInt(transfer);
}
else if(e.getSource() == textB){
transfer = String.format("field 2: %s", e.getActionCommand());
double b = Integer.parseInt(transfer);
}
else if(e.getSource() == textC){
transfer = String.format("frield 3: %s", e.getActionCommand());
double c = Integer.parseInt(transfer);
}
}
}
private class buttonListen implements ActionListener{
//private double a;
//private double b;
//private double c;
public void actionPerformed (ActionEvent ButtonPress){
JFrame Answer = new JFrame("Answer");
Answer.setSize(200, 200);
double d = (Math.pow(b, 2)+(4 * a * c));
}
}
}
您可以将三个double
放入静态变量中:
public class GUISource extends JFrame {
//same as before
private JTextField textA;
private JTextField textB;
private JTextField textC;
private JLabel labA;
private JLabel labB;
private JLabel labC;
private JButton butA;
private JButton butB;
private JButton butC;
public static double a =0,b=0,c=0;
然后在您的actionListener中:
if (e.getSource() == textA){
transfer = String.format("field 1 : %s", e.getActionCommand());
double a = Integer.parseInt(transfer);
GUISource.a = a;
}
//similarly for b and c
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.