1

While trying to read data from JTextField it says:

cannot refer to non final variable declared in inner class in another method

CODE:

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

public class Soloswing {

    Soloswing() {
        JFrame jf = new JFrame("soloworld");
        jf.setLayout(new FlowLayout(5, 25, 10));
        JLabel l1 = new JLabel("VALUE1");
        JTextField t1 = new JTextField(20);
        JLabel l2 = new JLabel("VALUE2");
        JTextField t2 = new JTextField(20);
        JLabel l3 = new JLabel("RESULT");
        JTextField t3 = new JTextField(20);

        JButton b1 = new JButton("+");
        JButton b2 = new JButton("-");
        JButton b3 = new JButton("*");
        JButton b4 = new JButton("/");
        JButton b5 = new JButton("%");
        JButton bequals = new JButton("=");
        JButton bclear = new JButton("CE");
        //int i = Integer.parseInt(t1.getText());
        //int j = Integer.parseInt(t2.getText());

        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setSize(300, 500);
        jf.add(l1);
        jf.add(t1);
        jf.add(l2);
        jf.add(t2);
        jf.add(l3);
        jf.add(t3);
        jf.add(b1);
        jf.add(b2);
        jf.add(b3);
        jf.add(b4);
        jf.add(b5);
        jf.add(bequals);
        jf.add(bclear);

        jf.setVisible(true);
        b1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int j = Integer.parseInt(t2.getText());
                int k = i + j;
                t3.setText(k);
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Soloswing();
            }
        });
    }
}

So, what I expect is, when JButton is clicked it should read inputs from two JTextFields and add them together and show the result in the third textField

b1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        int j = Integer.parseInt(t2.getText());
        int k = i + j;
        t3.setText(k);
    }
});

But, it shows the error:

canot refer to non final variable declared in inner class in another  method
mKorbel
  • 109,525
  • 20
  • 134
  • 319

0 Answers0