3 つの Jtextfields を持つ単純な電卓を作成しようとしています。最初の 2 つはユーザー入力を保持し、3 番目は計算結果を表示します。ユーザー入力を文字列に変換して表示できるようにしましたが、明らかにそれは間違っています。助けてください。これが私のコードです:
public class LetsDoMath extends JFrame {
JLabel instruction1;
JLabel instruction2;
JLabel instruction3;
JTextField input1;
JTextField input2;
JTextField result;
JButton plus;
JButton minus;
JButton times;
JButton divides;
/**
* Constructor of LetsDoMath
*
*/
public LetsDoMath() {
setSize(350, 100);
setTitle("Some Math Functions");
JPanel panel = new JPanel();
add(panel);
instruction1 = new JLabel("First");
panel.add(instruction1);
input1 = new JTextField(4);
panel.add(input1);
instruction2 = new JLabel("Second");
panel.add(instruction2);
input2 = new JTextField(4);
panel.add(input2);
instruction3 = new JLabel("Result");
panel.add(instruction3);
result = new JTextField(6);
panel.add(result);
result.setEditable(false);
plus = new JButton("+");
plus.addActionListener(new ButtonListener());
panel.add(plus);
minus = new JButton("-");
minus.addActionListener(new ButtonListener());
panel.add(minus);
times = new JButton("*");
times.addActionListener(new ButtonListener());
panel.add(times);
divides = new JButton("/");
divides.addActionListener(new ButtonListener());
panel.add(divides);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
String msg = event.getActionCommand();
String x;
String y;
double z;
x = input1.getText();
System.out.println("Reading " + x + " from the first text field");
System.out.println("Converted value: "+ Double.parseDouble(x));
y = input2.getText();
System.out.println("Reading " + y + " from the first text field");
System.out.println("Converted value: "+ Double.parseDouble(y));
if(event.getSource()== plus)
{
z = Double.parseDouble(x) + Double.parseDouble(y);
System.out.println("Result equals: "+z);
result = Double.toString(z).setText();
System.out.println("Ready for next input");
}
else if(event.getSource() == minus)
{
z = Double.parseDouble(x) - Double.parseDouble(y);
System.out.println("Result equals: "+z);
result = Double.toString(z).setText();
System.out.println("Ready for next input");
}
else if(event.getSource() == times)
{
z = Double.parseDouble(x) * Double.parseDouble(y);
System.out.println("Result equals: "+z);
result = Double.toString(z).setText();
System.out.println("Ready for next input");
}
else if(event.getSource() == divides)
{
z = Double.parseDouble(x) / Double.parseDouble(y);
System.out.println("Result equals: "+z);
result = Double.toString(z).setText();
System.out.println("Ready for next input");
}
}
}