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