简体   繁体   中英

How to access local variables in anonymous inner actionListener class and actionPerformed method?

I am working on a project for a CS class, so I cannot post any code, but I will try my best to describe what setup I have. The program is supposed to have 3 separate JPanels, each with an image and buttons to rotate and reset the image. A Driver class was provided that sets up the JFrame, creates a single Project object to pass around to other classes (this Project class contains the methods for rotating and combining the images), and has the main method.

What I've done is create a class that extends JPanel to setup a JPanel with the image, file name, and rotate/reset buttons. I have the constructor for this class taking in the number of the panel (to keep up with writing the image number in the panel), the image file to display, and the Project object that was created in the Driver class (to be able to access the methods for manipulating the images). I immediately call super(); and then set up the file name and image (as a JLabel) and buttons as (JButtons).

This is where my problem comes in though. I'm trying to set up the Rotate button, so I created an anonymous inner class action listener and actionPerformed method. What I planned on doing was using the Project object reference to call the rotate method on the image object, having it return a BufferedImage into a modifiedImage BufferedImage. Then remove the JLabel with the original image, add the modifiedImage as a JLabel, revalidate, and repaint. However, I cannot use the this reference or the reference to the Project object within the inner actionPerformed class.

How do I gain access to these references within the actionperformed inner class? or is my setup completely awful? Please bear with me- it's my first time working with any kind of GUI.

Make your reference to Project object final . It will solve the problem and does not make any harm as you are not going to assign it again.

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