0

I worked on a simple project on my own, which was to develop a calculator using Java, but I am getting the wrong output:

  • When I press button 1--> 1
  • When I press button 2-->2
  • When I press button 1-->11 (This is wrong) It should display 121 not 11
  • When I press button 2-->22

    I asked everyone, I looked over my code and I could not find the solution. Most people say my code's logic is code.

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JTextField;
    
    public class ButtonListener implements ActionListener {
       JTextField text;
       String display = "";
       String button[];
       JButton buttons[];
    
       public ButtonListener(JTextField text, String[] button, JButton[] buttons) {
          this.text = text;
          this.button = button;
          this.buttons = buttons;
       }
    
       public void Display(String button) {
          display = display + button;
          // return display;
       }
    
       public void actionPerformed(ActionEvent Buttonpress) {
          /******************** Constants ********************/
          // Planks Constant
          if (Buttonpress.getSource() == buttons[0]) {
             // display+=button[0];
             Display(button[0]);
          }
          // Elementary Charge
          if (Buttonpress.getSource() == buttons[8]) {
             // display+=Buttonpress.getSource();
             Display(button[8]);
          }
          text.setText(display);
       }
    }
    
  • Hovercraft Full Of Eels
    • 283,665
    • 25
    • 256
    • 373
    • @HovercraftFullOfEels: How do I edit my code on StackOverflow? Thank you for your assistance. – Fisan mala Apr 01 '15 at 21:09
    • 2
      Consider providing a [runnable example](https://stackoverflow.com/help/mcve) which demonstrates your problem. This is not a code dump, but an example of what you are doing which highlights the problem you are having. This will result in less confusion and better responses – MadProgrammer Apr 01 '15 at 21:09
    • 2
      You edit it in your code editor *before* posting it here. – Hovercraft Full Of Eels Apr 01 '15 at 21:10

    1 Answers1

    2

    First of all method names should NOT start with an upper case character. "Display" should be "display".

    Don't keep arrays of buttons and strings to determine which button was clicked and which text should be appended.

    You can get all the information you need to update your display text field from the ActionEvent itself.

    Here is an example for you to look at:

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    
    public class CalculatorPanel extends JPanel
    {
        private JTextField display;
    
        public CalculatorPanel()
        {
            Action numberAction = new AbstractAction()
            {
                @Override
                public void actionPerformed(ActionEvent e)
                {
    //              display.setCaretPosition( display.getDocument().getLength() );
                    display.replaceSelection(e.getActionCommand());
                }
            };
    
            setLayout( new BorderLayout() );
    
            display = new JTextField();
            display.setEditable( false );
            display.setHorizontalAlignment(JTextField.RIGHT);
            add(display, BorderLayout.NORTH);
    
            JPanel buttonPanel = new JPanel();
            buttonPanel.setLayout( new GridLayout(0, 5) );
            add(buttonPanel, BorderLayout.CENTER);
    
            for (int i = 0; i < 10; i++)
            {
                String text = String.valueOf(i);
                JButton button = new JButton( text );
                button.addActionListener( numberAction );
                button.setBorder( new LineBorder(Color.BLACK) );
                button.setPreferredSize( new Dimension(50, 50) );
                buttonPanel.add( button );
    
                InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
                inputMap.put(KeyStroke.getKeyStroke(text), text);
                inputMap.put(KeyStroke.getKeyStroke("NUMPAD" + text), text);
                button.getActionMap().put(text, numberAction);
            }
        }
    
        private static void createAndShowUI()
        {
    //      UIManager.put("Button.margin", new Insets(10, 10, 10, 10) );
    
            JFrame frame = new JFrame("Calculator Panel");
            frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            frame.add( new CalculatorPanel() );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
        }
    
        public static void main(String[] args)
        {
            EventQueue.invokeLater(new Runnable()
            {
                public void run()
                {
                    createAndShowUI();
                }
            });
        }
    }
    
    camickr
    • 321,443
    • 19
    • 166
    • 288
    • You could also pass that information to the `Action` (display text and value), further decoupling it... – MadProgrammer Apr 01 '15 at 21:11
    • @MadProgrammer, Not sure what you mean, I'm using a single Action to be shared by all the buttons. – camickr Apr 01 '15 at 21:14
    • @MadProgrammer: I don't understand, can you elaborate please. Thank you again. – Fisan mala Apr 01 '15 at 21:17
    • Yes, but you could pass the text to be used by the button and the value the button would update to the screen, then you could just use `new JButton(new NumberAction("1", 1));` instead (replacing each value as required, such as you loop), then the `Action` becomes much more flexible and usable across different contexts, such as in a `JMenuItem` and your keybindings, which I demonstrated in [this similar question](http://stackoverflow.com/questions/29384469/jbuttons-and-a-jtextfield-that-has-an-action-listener/29384513?noredirect=1#comment46957285_29384513) – MadProgrammer Apr 01 '15 at 21:18
    • This, of course would require to configure the `Action` object appropriately ;) – MadProgrammer Apr 01 '15 at 21:19
    • @camickr: What is function of setCarePosition and replaceSelection? I do not know what you did, but after using replaceSelection method my code is working. I work on these 3 days and you figured it out. How did you do it so quickly, I really want to know. The Only problem with my code is I set the display with 0, so the output is like this: when [I press button 1->01, I press button 1-011, I press 2, I get 0112] I know the problem is the way I set my textfield: {private JTextField text=new JTextField("0",63); } – Fisan mala Apr 01 '15 at 21:42
    • @MadProgrammer, ...back from dinner. I see what you mean. Yes, of course you can make a more complex Action. The main point of code was to try to encourage the writing of generic code by using information found in the event object. – camickr Apr 02 '15 at 00:52
    • No issue on my part ;) – MadProgrammer Apr 02 '15 at 00:54