I read some of the threads on calculators, but couldn't find anything related with what I need.

We have this swing calculator project, that uses buttons and/or a textbox for input, and a different textbox for output.

I have done most of it, and is working ok. The problem I have is with using the textbox for input.
I have to hit Enter every time after I enter any digits, and any operators. For example:
"35(ENTER) +(ENTER) 25(ENTER) =(ENTER)".... and I get a correct result on my output textbox.
What I want to know is.... is there a way to make the input textbox read so I don't have to hit enter after everything(only after "=") ?

Here is what I have(still needs some cleanup):

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class CalcPanel extends JPanel implements ActionListener
{  
  public CalcPanel()
  { 
    setLayout(new BorderLayout());
    Font bigFont = new Font("Arial", Font.PLAIN, 20);
    input = new JTextField();
    input.setFont(bigFont);
    input.addActionListener(this);
    JPanel d = new JPanel();
    d.setLayout(new BorderLayout());
    display = new JTextField("0");
    display.setFont(bigFont);
    display.setEditable(false);
    add(input, "North");
    d.add(display, "North");
    add(d, "Center");
      
    JPanel p = new JPanel();
    p.setLayout(new GridLayout(0, 4));
    String buttons = "789/456*123-0.=+";
    for(int i = 0; i < buttons.length(); i++) 
        addButton(p, buttons.substring(i, i + 1));      
    add(p, "South");
  }

  private void addButton(Container c, String s)
  {  
    JButton b = new JButton(s);
    c.add(b);
    b.addActionListener(this);
  }
   
  public void actionPerformed(ActionEvent evt)
  {
    String s = evt.getActionCommand();
    if ('0' <= s.charAt(0) && s.charAt(0) <= '9' || s.equals("."))
    {  
      if (start)
        display.setText(s);
      else
        display.setText(display.getText() + s);
      start = false;
    }
    else
    {  
      if (start)
      {
        if (s.equals("-")) 
        { 
          display.setText(s);
          start = false;
        }
        else 
          op = s;
      }
      else
      {
        double x = Double.parseDouble(display.getText());
        calculate(x);
        op = s;
        start = true;
      }
    }
    input.setText("");//Clear input textbox
  }
   
  public void calculate(double n)
  {
    if (op.equals("+"))
      arg += n;
    else if (op.equals("-"))
      arg -= n;
    else if (op.equals("*"))
      arg *= n;
    else if (op.equals("/"))
      arg /= n;
    else if (op.equals("="))
      arg = n;
    display.setText("" + arg);
  }
   
  private JTextField display;
  private JTextField input;
  private double arg = 0;
  private String op = "=";
  private boolean start = true;

}//end class CalcPanel

class CalcFrame extends JFrame
{  
  public CalcFrame()
  {  
    setTitle("Calculator");
    setSize(200, 190);
    addWindowListener(new WindowAdapter()
    {  
      public void windowClosing(WindowEvent e)
      {  
        System.exit(0);
      }
    });

    Container contentPane = getContentPane();
    contentPane.add(new CalcPanel());
  }
}//end class CalcFrame

public class Calculator
{
  public static void main(String[] args)
  {
    JFrame frame = new CalcFrame();
    frame.setVisible(true);  
  }

}//end class Calculator

Recommended Answers

All 6 Replies

for input apply CaretListener

// input.addActionListener(this);
        input.addCaretListener(new CaretListener() {

            @Override
            public void caretUpdate(CaretEvent e) {
                System.out.println(e);
                // TODO
            }
        });

Can you add some comments to the code explaining its logic.
What is the user supposed to enter in the textfield?
When I enter: 4+2= and press Enter, "4+2=" is copied to a label below the text field.
How is the user supposed to enter his expression?

Yes, that is exactly my problem.
Like I said above the code:

I have to hit Enter every time after I enter any digits, and any operators. For example:
"35(ENTER) +(ENTER) 25(ENTER) =(ENTER)".... and I get a correct result on my output textbox.

That's the only way it works. If I enter the entire operation, it just gets copied to the output textbox.

Basically, only until Enter is hit, it counts as an event. I'd like it to count every keystroke inside the input textbox as an event, that way it would read when an operator is entered.

I'd like it to count every keystroke inside the input textbox as an event, that way it would read when an operator is entered.

What are you going to do then?
If 47+2=<ENTER> is entered, what is the code supposed to do at each keystroke?

That's what I am asking for help with. I don't know how to do that or what the code should do.

If I'd have to make major changes to my code, then I wouldn't do it, I'll just submit it like it is now.
But if there is some way to do it without changing much, I'd appreciate the help.

*I didn't get the CaretListener comment. Not sure where I should use that.

One approach would be to add a document listener to the text field only allow digits to be entered.
Or there may be Swing methods that would do that. Look at setInputVerifier()

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.