-1

I just made a calculator application, and I do not know why the buttons with the following names:: "7", "8", "9", "0", ".". they are not taken into account when I click (the number is not written in the JLabel)

The set of buttons are stored in a table that I implemented in a panel I hope someone will find out where the problem comes from

thank you My code:

Public class Fenetre1 extends JFrame {
JPanel panel = new JPanel();
JPanel panel1 = new JPanel();
JLabel resultat = new JLabel("");
String[] tab_nombres = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ".", "=" };
String[] tab_operateur = { "C", "+", "-", "*", "/" };

JButton[] tab_buttons = new JButton[tab_nombres.length];
JButton[] tab_buttonsOperateur = new JButton[tab_operateur.length];

boolean operateur = false;  //test the operator 
boolean effacer = true; // test if JLabel is wipe off
double calcul = 0;
String signe; // stock the operator
String chaineNombre = ""; // stock first number
String chaineNombre2 = "";// stock second number

public Fenetre1() {

    this.setTitle("Calculatrice");
    this.setSize(400, 200);
    this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);
    resultat.setBackground(Color.BLACK);
    panel.setLayout(new GridLayout(4, 3, 5, 5));
    panel1.setLayout(new GridLayout(5, 1, 5, 5));
    // je donne des border a mon Jlabel
    resultat.setPreferredSize(new Dimension(250, 30));// dimension
    Font police = new Font("Tahoma", Font.BOLD, 16); // Apparence
    resultat.setBorder(BorderFactory.createLineBorder(Color.BLACK, 5));// bordure
    resultat.setFont(police);

    // boucle pour remplir les deux panels
    for (int i = 0; i < tab_buttons.length; i++) {
        tab_buttons[i] = new JButton(tab_nombres[i]);
        tab_buttons[i].addActionListener(new Affichage());
        panel.add(tab_buttons[i]);

    }

    for (int i = 0; i < tab_operateur.length; i++) {
        tab_buttonsOperateur[i] = new JButton(tab_operateur[i]);
        tab_buttonsOperateur[i].addActionListener(new Affichage());
        panel1.add(tab_buttonsOperateur[i]);

        // Grisé ces buttons tant qu'aucun nombre n'est saisie
        tab_buttonsOperateur[i].setEnabled(false);

    }

    this.getContentPane().add(resultat, BorderLayout.NORTH);

    this.getContentPane().add(panel, BorderLayout.CENTER);
    this.getContentPane().add(panel1, BorderLayout.EAST);

    resultat.setBorder(new EmptyBorder(5, 5, 5, 5));
    panel.setBorder(new EmptyBorder(5, 5, 5, 5));
    panel1.setBorder(new EmptyBorder(5, 5, 5, 5));
    this.pack();
    this.setVisible(true);

private class Affichage implements ActionListener {

    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub

        Object source = e.getSource();
        for (int i = 0; i < tab_buttons.length && i < tab_buttonsOperateur.length; i++) {
            if (source == tab_buttons[11] && calcul == 0 && chaineNombre2 == "" && chaineNombre == "") {

                resultat.setText("");
                resultat.repaint();
                break;
            }

            // Premier saisi d'un nombre
            if (effacer == true) {

                chaineNombre = ((JButton) source).getText();
                resultat.setText(chaineNombre);
                resultat.validate();
                calcul = Double.valueOf(chaineNombre);
                effacer = false;

                for (int j = 0; j < tab_buttonsOperateur.length; j++) {
                    tab_buttonsOperateur[j].setEnabled(true);
                }
                break;
            }

            else if (((JButton) source) == tab_buttons[i] && ((JButton) source) != tab_buttonsOperateur[i]) {
                // Pour concatiné les premiers nombres
                if (operateur == false) {
                    chaineNombre = chaineNombre.concat(((JButton) source).getText());
                    resultat.setText(chaineNombre);
                    resultat.validate();
                    calcul = Double.valueOf(chaineNombre);

                    // Pour concatiné les deuxièmes nombres
                } else if (operateur == true) {

                    chaineNombre2 = chaineNombre2.concat(((JButton) source).getText());
                    resultat.setText(chaineNombre2);

                    resultat.validate();
                }

            }

            else if (((JButton) source) == tab_buttonsOperateur[i] && ((JButton) source) != tab_buttons[i]) {
                // Pour vider le JLabel si on clique sur C
                if (((JButton) source) == tab_buttonsOperateur[0]) {
                    resultat.setText("");
                    resultat.repaint();
                    chaineNombre = "";
                    chaineNombre2 = "";
                    effacer = true;

                    for (int j = 0; j < tab_buttonsOperateur.length; j++) {
                        tab_buttonsOperateur[j].setEnabled(false);
                    }
                    break;
                } else {
                    // Stock operation choisis
                    operateur = true;
                    signe = tab_buttonsOperateur[i].getText();

                    break;
                }

                // Effectuer calcul selon l'operateur
            } else if (operateur == true && ((JButton) source) == tab_buttons[11]) {

                switch (signe) {

                case "+":
                    calcul = calcul + Double.valueOf(chaineNombre2);
                    resultat.setText(String.valueOf(calcul));
                    resultat.validate();
                    operateur = false;
                    break;
                case "-":
                    calcul = calcul - Double.valueOf(chaineNombre2);
                    resultat.setText(String.valueOf(calcul));
                    resultat.validate();
                    operateur = false;
                    break;
                case "*":
                    calcul = calcul * Double.valueOf(chaineNombre2);
                    resultat.setText(String.valueOf(calcul));
                    resultat.validate();
                    operateur = false;
                    break;

                case "/":
                    if ((((JButton) source).getText()) == "0") {
                        resultat.setText("dévision par 0 est impossible");
                        resultat.validate();
                    } else {
                        calcul = calcul / Double.valueOf(chaineNombre2);
                        resultat.setText(String.valueOf(calcul));
                        resultat.validate();
                        operateur = false;

                    }
                    break;

                default:
                    resultat.setText("choisir une opération");
                    break;

                }
                chaineNombre2 = "";
            }

        }

    }

}

}

DataMan
  • 27
  • 6
  • 1
    Rather than sending all events to a single method, and trying to sort out who's telling it what, create different actions for different types of buttons, that have appropriate properties. For example, a number button action would have a digit value, and when activated, add that value to the display. An operator button would have an operator, and chain with the operand from the display. – erickson Apr 18 '19 at 00:17
  • no, the comparison is done correctly, since the other buttons work – DataMan Apr 18 '19 at 00:33
  • erickson, if I understand correctly, you're asking me to use a numeric type for numbers? I have to concatinate the buttons click this is only possible with a String – DataMan Apr 18 '19 at 00:37
  • 1
    You can replace `operateur == true` with just `operateur` since it's a boolean type. – Benjamin Urquhart Apr 18 '19 at 01:23
  • 1
    Also, never say `if (var == true)`; just say `if (var)` (or `if (!var)`). – chrylis -cautiouslyoptimistic- Apr 18 '19 at 01:23
  • thank you for the advice I made the changes but I still have the same problem for these buttons – DataMan Apr 18 '19 at 01:31
  • 1
    As suggested by @Erickson, your logic is way too complicated to understand what you are really doing. For example check out: https://stackoverflow.com/questions/33739623/how-to-add-a-shortcut-key-for-a-jbutton-in-java/33739732#33739732 for a simple example that shows how you can share a single Action to enter the number. Then all you need to provide is separate Actions for the add, subtract... events. If you provide separate Actions there is no need for looping code, nested if/else statements. – camickr Apr 18 '19 at 02:18
  • 1) See also this [calculator example](http://stackoverflow.com/a/7441804/418556). It uses `ScriptEngine` to evaluate the expression in the text field. 2) For better help sooner, [edit] to add a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 3) See [Detection/fix for the hanging close bracket of a code block](http://meta.stackexchange.com/q/251795/155831) for a problem I could no longer be bothered fixing. Please [edit] the question to indent the closing `}` (at the end of the code) by 4 characters. 4) Tip: Add @erickson (or whoever, the `@` is important) .. – Andrew Thompson Apr 18 '19 at 10:38
  • .. to *notify* the person of a new comment. – Andrew Thompson Apr 18 '19 at 10:39

2 Answers2

0

Around line 27, change

    JButton[] tab_buttonsOperateur = new JButton[tab_operateur.length];

to

    JButton[] tab_buttonsOperateur = new JButton[tab_nombres.length];
  • effectively he had a problem of table length my loop stop at 5 I had to use a table to rectify the problem – DataMan Apr 18 '19 at 15:46
0

The outermost loop in the actionPerformed() method of Affichage is limited by the length of the array of operator buttons, which is 5:

i < numberButtons.length && i < opButtons.length

Because of that limit on i, the number buttons for "6" and up are never processed.

This all stems from trying the complexity of trying to do everything in one giant method. Instead, you should have different listeners to perform specific tasks, and add those to the correct UI controls.

erickson
  • 265,237
  • 58
  • 395
  • 493