0

I'm developing a javaswing calculator. But I have some difficulties. I have constraints that I cannot resolve.

When you press "=" twice, the result should go to "0". I have difficulties to do that.

And finally I am french so you will find french words! THANKS for your help! Current result:

Here the code for the equal.


import java.awt.BorderLayout;
import java.awt.Color;  
import java.awt.Dimension;  
import java.awt.Font;   
import java.awt.event.ActionEvent;  
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel; // affichage
import javax.swing.JPanel;


public class Calculatrice extends JFrame {

        private JPanel container = new JPanel(); 

        String[] tab_string = {"1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "0", "=", "C", "+", "-", "*", "/"};
        JButton[] tab_button = new JButton[tab_string.length]; // long tab-1

        private JLabel ecran = new JLabel(); 
        private Dimension dim = new Dimension(50, 40);
        private Dimension dim2 = new Dimension(50, 31); 
        private double chiffre1;
        private boolean clicOperateur = false, update = false;
        private String operateur = "";

        public Calculatrice(){

                this.setSize(350, 300); //(Largeur, Hauteur)
                this.setTitle("Calculatrice"); //Nom programme
                this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                this.setLocationRelativeTo(null);
                this.setResizable(false);
                initComposant();

                this.setContentPane(container);
                this.setVisible(true);
        }

        private void initComposant(){

                Font police = new Font("Calibri", Font.BOLD, 15);
                ecran = new JLabel("0");
                ecran.setFont(police);
                ecran.setHorizontalAlignment(JLabel.CENTER);
                ecran.setPreferredSize(new Dimension(220, 20));

                JPanel operateur = new JPanel();        
                operateur.setPreferredSize(new Dimension(55, 225));
                JPanel chiffre = new JPanel();
                chiffre.setPreferredSize(new Dimension(165, 225));
                JPanel panEcran = new JPanel();
                panEcran.setPreferredSize(new Dimension(220, 30)); 


                for(int i = 0; i < tab_string.length; i++)
                {
                    tab_button[i] = new JButton(tab_string[i]);     // création des boutons
                    tab_button[i].setPreferredSize(dim);

                    switch(i){

                        case 11 :
                            tab_button[i].setForeground(Color.red);
                            tab_button[i].addActionListener(new EgalListener());
                            chiffre.add(tab_button[i]); // égale
                            break;

                        case 12 :
                            tab_button[i].setForeground(Color.blue);
                            tab_button[i].addActionListener(new ResetListener());
                            tab_button[i].setPreferredSize(dim2);
                            operateur.add(tab_button[i]); // opérande
                            break;

                        case 13 :
                            tab_button[i].setForeground(Color.black);
                            tab_button[i].addActionListener(new PlusListener());
                            tab_button[i].setPreferredSize(dim2);
                            operateur.add(tab_button[i]);
                            break;

                        case 14 :
                            tab_button[i].setForeground(Color.black);
                            tab_button[i].addActionListener(new MoinsListener());
                            tab_button[i].setPreferredSize(dim2);
                            operateur.add(tab_button[i]);
                            break;  

                        case 15 :   
                            tab_button[i].setForeground(Color.black);
                            tab_button[i].addActionListener(new MultiListener());
                            tab_button[i].setPreferredSize(dim2);
                            operateur.add(tab_button[i]);
                            break;

                        case 16 :
                            tab_button[i].setForeground(Color.black);
                            tab_button[i].addActionListener(new DivListener());
                            tab_button[i].setPreferredSize(dim2);
                            operateur.add(tab_button[i]);
                            break;

                        case 17 :
                            tab_button[i].setForeground(Color.black);
                            tab_button[i].addActionListener(new DivListener());
                            tab_button[i].setPreferredSize(dim2);
                            operateur.add(tab_button[i]);
                            break;  

                        default :
                            tab_button[i].addActionListener(new ChiffreListener());
                            chiffre.add(tab_button[i]); // chiffre
                            break;
                    }
                }

                panEcran.add(ecran);
                panEcran.setBorder(BorderFactory.createLineBorder(Color.black)); // bordure affichage

                container.add(panEcran, BorderLayout.NORTH); // affichage
                container.add(chiffre, BorderLayout.CENTER); // corps
                container.add(operateur, BorderLayout.EAST); // opérande
        }


        private void calcul(){
                if(operateur.equals("+"))
                {
                        chiffre1 = chiffre1 + Double.valueOf(ecran.getText()).doubleValue();
                        ecran.setText(String.valueOf(chiffre1));
                }

                if(operateur.equals("-"))
                {
                        chiffre1 = chiffre1 - Double.valueOf(ecran.getText()).doubleValue();
                        ecran.setText(String.valueOf(chiffre1));
                }               

                if(operateur.equals("*"))
                {
                        chiffre1 = chiffre1 * Double.valueOf(ecran.getText()).doubleValue();
                        ecran.setText(String.valueOf(chiffre1));
                }       

                if(operateur.equals("/"))
                {
                        try{
                                chiffre1 = chiffre1 / Double.valueOf(ecran.getText()).doubleValue();
                                ecran.setText(String.valueOf(chiffre1));
                        } catch (ArithmeticException e){
                                ecran.setText("0");
                        }
                }
        }

        class ChiffreListener implements ActionListener{
                public void actionPerformed(ActionEvent e) {
                        //On affiche le chiffre en plus dans le label
                        String str = ((JButton)e.getSource()).getText();

                        if(update)
                        {
                                update = false;
                        }
                        else
                        {
                                if(!ecran.getText().equals("0")) // si écran = 0
                                        str = ecran.getText() + str;
                        }

                        ecran.setText(str);
                }
        }


        class EgalListener implements ActionListener{
                public void actionPerformed(ActionEvent arg0) {
                        calcul();
                        update = true;
                        clicOperateur = false;
                }    
        }


        class PlusListener implements ActionListener{
                public void actionPerformed(ActionEvent arg0) {

                        if(clicOperateur)
                        {
                                calcul();
                                ecran.setText(String.valueOf(chiffre1));
                        }
                        else
                        {
                                chiffre1 = Double.valueOf(ecran.getText()).doubleValue();
                                clicOperateur = true;
                        }
                        operateur = "+";
                        update = true;
                }
        }

        class MoinsListener implements ActionListener{
                public void actionPerformed(ActionEvent arg0) {
                        if(clicOperateur)
                        {
                                calcul();
                                ecran.setText(String.valueOf(chiffre1));
                        }
                        else
                        {
                                chiffre1 = Double.valueOf(ecran.getText()).doubleValue();
                                clicOperateur = true;
                        }
                        operateur = "-";
                        update = true;
                }
        }

        class MultiListener implements ActionListener{
                public void actionPerformed(ActionEvent arg0) {
                        if(clicOperateur)
                        {
                                calcul();
                                ecran.setText(String.valueOf(chiffre1));
                        }
                        else
                        {
                                chiffre1 = Double.valueOf(ecran.getText()).doubleValue();
                                clicOperateur = true;
                        }
                        operateur = "*";
                        update = true;
                }
        }

        class DivListener implements ActionListener{
                public void actionPerformed(ActionEvent arg0) {
                        if(clicOperateur)
                        {
                                calcul();
                                ecran.setText(String.valueOf(chiffre1));
                        }
                        else
                        {
                                chiffre1 = Double.valueOf(ecran.getText()).doubleValue();
                                clicOperateur = true;
                        }
                        operateur = "/";
                        update = true;
                }
        }

        class ResetListener implements ActionListener{
                public void actionPerformed(ActionEvent arg0) {
                        clicOperateur = false;
                        update = true;
                        chiffre1 = 0;
                        operateur = "";
                        ecran.setText("0"); 
                }
        }

}
c0der
  • 18,467
  • 6
  • 33
  • 65
umanis
  • 11
  • 3
  • Can you add a minimal example of reproducibility? your code is a generic action listener. – vincenzopalazzo Apr 17 '20 at 17:12
  • @vincenzopalazzo I don't understand you want the full code or an image ? – umanis Apr 17 '20 at 17:13
  • the function calc, isn't a swing method, should be upload all your personal function – vincenzopalazzo Apr 17 '20 at 17:17
  • I edit is that what you want ? @vincenzopalazzo – umanis Apr 17 '20 at 17:22
  • I can not build an answer because I don't know your code structure and so, I don't know how you have built your action. But I can say, that with your code, you should be stored your last operator clicked and if you have two clicks with the same operator you can set the 0 value. – vincenzopalazzo Apr 17 '20 at 18:03
  • See also this [calculator example](http://stackoverflow.com/a/7441804/418556). It uses `ScriptEngine` to evaluate the expression in the text field. – Andrew Thompson Apr 18 '20 at 03:44
  • @AndrewThompson Ive tried but i don't really understand – umanis Apr 18 '20 at 08:55
  • I think [this](https://stackoverflow.com/questions/21497120/clicking-a-jbutton-twice-in-a-row) has an answer to your question. – c0der Apr 19 '20 at 06:12
  • @umanis - I hope the solution worked for you. Do not forget to accept the answer so that future visitors can also use the solution confidently. Check https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work to learn how to do it. Feel free to comment in case of any doubt/issue. – Arvind Kumar Avinash May 16 '20 at 22:53

1 Answers1

1

I tried to understand your program but could not understand because it's not in English. So, I am writing an approach to solve the problem:

  1. Create a variable, say int equalCounter = 0.
  2. Reset the value of equalCounter to 0 on click of every button except =.
  3. On click of = button, check
if(equalCounter == 0) {
    //perform the action you are already doing
    //set equalCounter to 1
} else {
    //set result to 0
    //set equalCounter to 0
}

If you wish, instead of an int equalCounter, you can create a boolean isEqaulAlreadyUsed and set its value to false and true instead of 0 and 1 respectively.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110