我正在创建基本二次方程式计算器的JFrame程序。我创建了一个Action侦听器,将三个文本字段转换为三个Double值,等于a,b和c,它们在Quadratic Formula中使用。当用户完成时,我无法弄清楚如何将这些放入我的其他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));
}
}
}
答案 0 :(得分:2)
您可以将三个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