Hello. I am trying to make a calculator using Java GUI. I've managed to make an ActionListener and add it to a button, but I've made an error in my code that I'm unsure of how to solve. Because of how I've written the code, only one number can be placed in the text field. For example, the an ActionListener for the three button on the calculator was added to the button, but no matter how many times the user presses the button, only one 3 will appear in the text field. The code is below:
import javax.swing.*;//import the packages needed for gui import java.awt.*; import java.awt.event.*; public class Calculator { public static void main(String[] args) { JFrame window = new JFrame("Window");//makes a JFrame window.setSize(300,350); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel (new FlowLayout());//makes the panel, textfield and buttons final JTextField textField = new JTextField(20); JButton openbracket = new JButton("("); JButton closebracket = new JButton(")"); JButton clearbutton = new JButton("C"); JButton arcsin = new JButton("arcsin"); JButton arccos = new JButton("arccos"); JButton arctan = new JButton("arctan"); JButton sin = new JButton("sin"); JButton cos = new JButton("cos"); JButton tan = new JButton("tan"); JButton log = new JButton("log"); JButton seven = new JButton("7"); JButton eight = new JButton("8"); JButton nine = new JButton("9"); JButton four = new JButton("4"); JButton five = new JButton("5"); JButton six = new JButton("6"); JButton one = new JButton("1"); JButton two = new JButton("2"); JButton three = new JButton("3"); JButton zero = new JButton("0"); JButton radixpoint = new JButton("."); JButton equal = new JButton("="); final String values = " "; class Listener implements ActionListener { public void actionPerformed(ActionEvent e) { String output = values + "3"; textField.setText(output); } } Listener listener = new Listener(); panel.add(textField);//adding all the things window.add(panel); panel.add(openbracket); panel.add(closebracket); panel.add(clearbutton); panel.add(arcsin); panel.add(arccos); panel.add(arctan); panel.add(sin); panel.add(cos); panel.add(tan); panel.add(log); panel.add(nine); panel.add(eight); panel.add(seven); panel.add(six); panel.add(five); panel.add(four); three.addActionListener(listener); panel.add(three); panel.add(two); panel.add(one); panel.add(zero); panel.add(radixpoint); panel.add(equal); window.setVisible(true); } }
As you can see, because the compiler forces the String variable to be final, so when the user presses the button, the code simply shows how a space character and three character would look like, because the String variable can't change. How do I write my code so that every time the user presses the button, a character is added to the text field?