简体   繁体   中英

Cannot refer to a variable inside an inner class

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!

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;

    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM