Question

My calculator program only takes single digit in the textfield when a button is pressed. How can I make it take multiple digits when buttons are pressed? It replaces the original number that I pressed with the new number.

This is my code:

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

class cal  implements ActionListener
{
JFrame frame;
JPanel grid,flow;
JButton one,two,three,four,five,six,seven,eight,nine,zero,plus,sub,mul,div,equal,clear;
JTextField text;
JLabel em,em1,em2;
int b,c;

public cal()
{
frame=new JFrame("Calculator");     //frame
frame.setVisible(true);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setSize(600,600);

flow=new JPanel();          //panel
grid=new JPanel(new GridLayout(5,4));

one=new JButton("1");           //button
one.addActionListener(this);
two=new JButton("2");           //button
two.addActionListener(this);
three=new JButton("3");         //button
three.addActionListener(this);
four=new JButton("4");          //button
four.addActionListener(this);
five=new JButton("5");          //button
five.addActionListener(this);
six=new JButton("6");           //button
six.addActionListener(this);
seven=new JButton("7");         //button
seven.addActionListener(this);
eight=new JButton("8");         //button
eight.addActionListener(this);
nine=new JButton("9");          //button
nine.addActionListener(this);
zero=new JButton("0");          //button
zero.addActionListener(this);
plus=new JButton("+");          //button
plus.addActionListener(this);
sub=new JButton("-");           //button
sub.addActionListener(this);
mul=new JButton("*");           //button
mul.addActionListener(this);
div=new JButton("/");           //button
div.addActionListener(this);
equal=new JButton("=");         //button
equal.addActionListener(this);
clear=new JButton("Clear");         //button
clear.addActionListener(this);

text=new JTextField();      //textfield

em=new JLabel("");          //empty label
em1=new JLabel("");
em2=new JLabel("");

grid.add(text);
grid.add(em);
grid.add(em1);
grid.add(em2);
grid.add(one);
grid.add(two);
grid.add(three);
grid.add(plus);
grid.add(four);
grid.add(five);
grid.add(six);
grid.add(sub);
grid.add(seven);
grid.add(eight);
grid.add(nine);
grid.add(mul);
grid.add(clear);
grid.add(zero);
grid.add(equal);
grid.add(div);

flow.add(grid);
frame.add(flow);
}

public void actionPerformed(ActionEvent a)
{
if(a.getSource()==one)
text.setText("1");

if(a.getSource()==two)
text.setText("2");

if(a.getSource()==three)
text.setText("3");

if(a.getSource()==four)
text.setText("4");

if(a.getSource()==five)
text.setText("5");

if(a.getSource()==six)
text.setText("6");

if(a.getSource()==seven)
text.setText("7");

if(a.getSource()==eight)
text.setText("8");

if(a.getSource()==nine)
text.setText("9");

if(a.getSource()==zero)
text.setText("0");

if(a.getSource()==plus)
{
b=Integer.parseInt(text.getText());
c=1;
text.setText("");
}

if(a.getSource()==sub)
{
b=Integer.parseInt(text.getText());
c=2;
text.setText("");
}

if(a.getSource()==mul)
{
b=Integer.parseInt(text.getText());
c=3;
text.setText("");
}

if(a.getSource()==div)
{
b=Integer.parseInt(text.getText());
c=4;
text.setText("");
}

if(a.getSource()==equal)
{
if(c==1)
{
int x=Integer.parseInt(text.getText());
int y=b+x;
text.setText(Integer.toString(y));
}

if(c==2)
{
int x=Integer.parseInt(text.getText());
int y=b-x;
text.setText(Integer.toString(y));
}

if(c==3)
{
int x=Integer.parseInt(text.getText());
int y=b*x;
text.setText(Integer.toString(y));
}

if(c==4)
{
int x=Integer.parseInt(text.getText());
int y=b/x;
text.setText(Integer.toString(y));
}
}

if(a.getSource()==clear)
{
text.setText("");
b=0;
}
}
public static void main(String[] args)
{
cal a =new cal();
}
}

Works fine with a single digit, but not with multiple digits.

Was it helpful?

Solution 2

For multiple digits you need to append the current text with existing one. Code sample below

    String valueText=text.getText();

    if (a.getSource() == one)
        valueText=valueText.concat("1");

    if (a.getSource() == two)
        valueText=valueText.concat("2");

    if (a.getSource() == three)
        valueText=valueText.concat("3");

    if (a.getSource() == four)
        valueText=valueText.concat("4");

    if (a.getSource() == five)
        valueText=valueText.concat("5");

    if (a.getSource() == six)
        valueText=valueText.concat("6");

    if (a.getSource() == seven)
        valueText=valueText.concat("7");

    if (a.getSource() == eight)
        valueText=valueText.concat("8");

    if (a.getSource() == nine)
        valueText=valueText.concat("9");

    if (a.getSource() == zero)
        valueText=valueText.concat("0");

    text.setText(valueText);

OTHER TIPS

The setText(...) method replaces the existing text with the new text.

Here is an example that shows how you can use the replaceSelection(...) method of the JTextField.

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();
            }
        });
    }
}

The example also shows how to use a common ActionListener for all the buttons without using nested if/else statements.

if(a.getSource()==one)
    text.setText(text.getText()+"1");
if(a.getSource()==two)
    text.setText(text.getText()+"2");
......
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top