javaswingactionlistener

How can I increase the value in the text field with JButton?


I have a school project and I want to do an online shopping cart with Java. It has a frame, 4 different types of clothing with JLabels, one text field that displays 0 in the starting for each of them and two JButtons that have plus and minus icons for each text fields. I want to increase the number which is in the text field with plus button and decrease it with minus button. Also it needs to count how many clothes I want to buy, for calculating the money.

pa = JButton which has a plus sign and need to increase the number of Pants. pt = JTextField which shows us the number of pants.

pa.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent actionEvent) {
        pt.setText(String.valueOf(Integer.valueOf(pt.getText() + 1)));
    }
});

Output: Pants: 0 (Press + button once) Pants: 1 (Press + button once) Pants: 11

My expectation: Pants: 0 (Press + button once) Pants: 1 (Press + button once) Pants: 2

Also, decreasing similarly with - button, but I can't.

Also, I tried this one but it didn't work:

int counter = 0;
pa.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent actionEvent) {
        counter++;
        pt.setText(String.valueOf(counter));
    }
});

Error: java: local variables referenced from an inner class must be final or effectively final


Solution

  • Your first approach is not far off. There is just a little error in line pt.setText(String.valueOf(Integer.valueOf(pt.getText() + 1)));: the +1 should not be inside Integer.value(...) but right after it. Your current code gets the text, appends the character 1 to the text, and parses the modified text as number. But you need to get the text, parse the text as number, and then add 1 to the parsed number. It might help to do each step in a separate line and assign each intermediate result to a local variable instead of doing everything in one statement.

    Still, the idea from the second approach is the better one. Change your int counter from a local variable to a field of your class and it will work.