i am developing for a few months now and wanted to create a calculator which becomes Input from 3 JTextFields (first number; operator; second number) and gives output over an extra window. But i am receiving an issue now, and in 1 hour I couldn't get, where the issue is coming from. Because I don't know, what the issue is, i will post the whole program text below:
package de.programmer.main;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main {
public static void main(String[] args) {
JTextField first = new JTextField(10);
JTextField operator = new JTextField(5);
JTextField second = new JTextField(10);
JButton button = new JButton("Calculate");
JFrame frame = new JFrame();
frame.setTitle("Calculator");
frame.setSize(800, 400);
frame.setLocation(600, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.setBackground(Color.CYAN);
button.setForeground(Color.RED);
button.setFocusPainted(false);
JPanel panel = new JPanel();
panel.setBackground(Color.DARK_GRAY);
panel.add(first);
panel.add(operator);
panel.add(second);
panel.add(button);
frame.add(panel);
frame.setVisible(true);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFrame ergebnisframe = new JFrame();
ergebnisframe.setSize(400, 200);
ergebnisframe.setLocation(600, 300);
ergebnisframe.setTitle("Ergebnis");
JPanel ergebnispanel = new JPanel();
ergebnispanel.setBackground(Color.DARK_GRAY);
JLabel ergebnislabel = new JLabel("Ergebnis: ");
ergebnislabel.setForeground(Color.CYAN);
ergebnislabel.setBackground(Color.BLACK);
String firststring = first.getText();
int firstint = Integer.parseInt(firststring);
String secondstring = first.getText();
int secondint = Integer.parseInt(secondstring);
String operatorstring = operator.getText();
double ergebnis;
if (operatorstring == "+") {
ergebnis = firstint + secondint;
String ergebnisstring=Double.toString(ergebnis);
ergebnislabel.setText("Ergebnis: " + ergebnisstring);
}
ergebnispanel.add(ergebnislabel);
ergebnisframe.add(ergebnispanel);
ergebnisframe.setVisible(true);
}
});
}
}
When I excute and put the numbers "1" "+" and "2" in, I get this:
so i added an "else" after the if-testing with the command "ergebnislabel.setText("Etwas ist schief gelaufen!");" to get an answer where it is coming from and if I excute this, I am receiving this:
so the issue is in the if-testing. I've tested it again with the "-" as operator but received the same. I just don't know what to do. Can anyone help me please?