0

I'm still learning java so bear with me. I am trying to write a program where you click a button named "Yes" and it increases a variable Y by 1, and same with a button "No" on variable X. I'm using eclipse and WindowBuilder Pro and it gives me an error "Cannot refer to a variable inside an inner class"

Here's my code:

    import javax.swing.JApplet;
    import javax.swing.JButton;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFormattedTextField;


    public class qa extends JApplet {

        /**
         * Create the applet.
         */
        public qa() {
            getContentPane().setLayout(null);

            int y=0;
            int x=0;
            String s1 = String.valueOf(y);


            JButton btnYes = new JButton("YES");
            btnYes.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent arg0) {
                    ++y;
                }
            });
            btnYes.setBounds(135, 220, 85, 42);
            getContentPane().add(btnYes);

            JButton btnNo = new JButton("NO");
            btnNo.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    ++x;
                }
            });
            btnNo.setBounds(230, 220, 85, 42);
            getContentPane().add(btnNo);

            JFormattedTextField frmtdtxtfldVarible = new JFormattedTextField();
            frmtdtxtfldVarible.setText(s1);
            frmtdtxtfldVarible.setBounds(147, 130, 157, 20);
            getContentPane().add(frmtdtxtfldVarible);


        }
    }

Thanks for any help!

mKorbel
  • 109,525
  • 20
  • 134
  • 319
GiantDwarf
  • 111
  • 5
  • Try looking at http://stackoverflow.com/questions/1299837/cannot-refer-to-a-non-final-variable-inside-an-inner-class-defined-in-a-differen In short, you should look into encapsulation. – JavaChipMocha May 13 '13 at 18:00

1 Answers1

3

Declare x and y as instance variables so that you don't need to declare them as final local variables:

public class qa extends JApplet
{
    private int x = 0;
    private int y = 0;

    // ...
}
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417