I have to create a calculator that displays the results according to their text fields. The display does not work, yet the calculation is performed. I get an error that says my JLabel is zero. How do I solve the problem?
Maybe with
JLabel Resultat = new JLabel("Résultat : ", SwingConstants.CENTER);
at the wrong place ?
The code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Exercice4 extends JFrame {
private JTextField ZoneTxt, ZoneTxt2;
private JPanel CalculPanel;
private JLabel Resultat;
private JComboBox Op;
private JButton BCalcul;
private int cbselect = 0;
private double res;
final String[] operateur = { "+", "-", "*", "/" };
public Exercice4() {
super("Exercice 4");
JFrame FrameExercice4 = new JFrame();
JPanel CalculPanel = new JPanel();
ZoneTxt = new JTextField(10);
ZoneTxt2 = new JTextField(10);
final JComboBox Op = new JComboBox(operateur);
BCalcul = new JButton("Calculer");
BCalcul.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int cbselect = Op.getSelectedIndex();
if (cbselect == 0) {
res = (((Double.parseDouble(ZoneTxt.getText()))) + ((Double
.parseDouble(ZoneTxt2.getText()))));
System.out.println(res);
Resultat.setText("Résultat : " + String.valueOf(res));
}
if (cbselect == 1) {
// System.out.println(res1 - res2);
}
if (cbselect == 2) {
// System.out.println(res1 * res2);
}
if (cbselect == 3) {
// System.out.println(res1 / res2);
}
}
});
JLabel Resultat = new JLabel("Résultat : ", SwingConstants.CENTER);
FrameExercice4.setVisible(true);
FrameExercice4.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FrameExercice4.setSize(500, 500);
FrameExercice4.add(CalculPanel);
CalculPanel.add(ZoneTxt);
CalculPanel.add(Op);
CalculPanel.add(ZoneTxt2);
CalculPanel.add(BCalcul);
CalculPanel.add(Resultat, BorderLayout.CENTER);
}
public static void main(String[] args) {
JFrame frame = new Exercice4();
}
}