Question

I'm creating a calculator and I'm wondering how do you add number or symbol to the text field. For example when you press the button labelled '2', I want '2' to appear in the textfield.

What I have so far is just the frame of the calculator where the buttons currently do nothing. If you need any more information, please do ask. Thanks

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

public class CalcFrame extends JFrame 
{

    public CalcFrame()
{
    super("Calculator");
    setLayout(new FlowLayout() );
    JTextField calcTextField = new JTextField (19);
    add (calcTextField);
    calcTextField.setEditable(false);

    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout ( new GridLayout(4,4) );

    String[] buttonNames = {"7", "8", "9", "/",
            "4", "5", "6", "*",
            "1", "2", "3", "-",
            "0", ".", "=", "+"};

    for (String buttonText : buttonNames)
    {
        JButton button = new JButton(buttonText);
        buttonPanel.add(button);
    }

    buttonPanel.setPreferredSize(new Dimension(220, 250));
    add(buttonPanel);


}

public static void main (String[]args)
    {
    CalcFrame myCalc = new CalcFrame();
    myCalc.setSize(300, 350);
    myCalc.setVisible( true );
    myCalc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}
}
Was it helpful?

Solution

Here I edited your code and added a good things, the = button is working and added C button which is the clear button.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;//added this line
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
public class CalcFrame extends JFrame implements ActionListener{

  private JTextField calcTextField;
  private ScriptEngineManager sem;
  private ScriptEngine scriptEngine;
  public CalcFrame(){

    super("Calculator");
    setLayout(new FlowLayout() );
    calcTextField = new JTextField (19);
    calcTextField.setPreferredSize(new Dimension(0,50));//added this line
    add (calcTextField);
    calcTextField.setEditable(false);

    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout ( new GridLayout(5,4,10,10) );

    String[] buttonNames = {"7", "8", "9", "/",
                            "4", "5", "6", "*",
                            "1", "2", "3", "-",
                            "0", ".", "=", "+",
                            "C", "(", ")"};

    for (String buttonText : buttonNames)
    {
        JButton button = new JButton(buttonText);
        buttonPanel.add(button);
        button.addActionListener(this);//added this line
    }

    buttonPanel.setPreferredSize(new Dimension(220, 250));
    add(buttonPanel);

    sem = new ScriptEngineManager();
    scriptEngine = sem.getEngineByName("JavaScript");

}
//added this method (it must be added because you implemented
//ActionListener above while declaring the class
@Override
public void actionPerformed(ActionEvent ev){
    JButton b = (JButton)ev.getSource();
    if(b.getText().equals("C"))
        calcTextField.setText("");
    else if(!b.getText().equals("="))
        calcTextField.setText(calcTextField.getText()+b.getText());
    else{
          try{
            String result = scriptEngine.eval(calcTextField.getText()).toString();
            calcTextField.setText(result);
        }catch(Exception ex){
            JOptionPane.showMessageDialog(null,"The Expression is wrong, maybe you miss a bracket!");
        }
    }
}
//-----
public static void main (String[]args) {
    CalcFrame myCalc = new CalcFrame();
    myCalc.setSize(300, 350);
    myCalc.setVisible( true );
    myCalc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}
}

OTHER TIPS

String[] buttonNames = {"7", "8", "9", "/",
          "4", "5", "6", "*",
          "1", "2", "3", "-",
          "0", ".", "=", "+"};

for (String buttonText : buttonNames)
{
    JButton button = new JButton(buttonText);
    buttonPanel.add(button);
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            //Set your textfield to the previous text here as well as the new button
            //which should correlate to your button name.
            calcTextField.setText(calcTextField.getText() + buttonText);
        }
    });      
}

As Salah stated, but let's not be old fashioned ;) Let's use advantage of lambdas:

import javax.swing.*;
import java.awt.*;
import java.util.Arrays;
import java.util.List;

//Avoid extending your class with JFrame. There is no need in this case.
public class CalcFrame extends JFrame {

    public CalcFrame() {
        super("Calculator");
        setLayout(new FlowLayout());
        JTextField calcTextField = new JTextField(19);
        add(calcTextField);
        calcTextField.setEditable(false);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridLayout(4, 4));

        List<String> buttonNames = Arrays.asList("7", "8", "9", "/",
                "4", "5", "6", "*",
                "1", "2", "3", "-",
                "0", ".", "=", "+");


        buttonNames.forEach(bt -> {
            JButton button = new JButton(bt);
            button.addActionListener(e -> calcTextField.setText(calcTextField.getText() +
                    ((JButton) e.getSource()).getText()));
            buttonPanel.add(button);
        });

        //buttonPanel.setPreferredSize(new Dimension(220, 250));
        add(buttonPanel);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.pack();
        this.setVisible(true);


    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(CalcFrame::new);

    }
}

First You need to add ActionListener to your buttons:

button.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // set text.

        }
    });

Then you can set the text to text field, as:

textField.setText(buttonText);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top