Some time ago I wrote a little image viewer/processing program with Java, a mini-Photoshop, if you will.
I wanted there to be a drop-down menu where I could select which one of the images I have opened would be "on the table", ie. shown and methods applied to. I wanted the name of the image to be the name of the JMenuItem shown in the menu. I also wanted a new button to appear when I add a new image.
I wondered this for some time and finally produced this solution, a new class that handles the creation of the new button when an image is added. The code is as follows:
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class ImageList{
private ArrayList<JMenuItem> list;
private ImageHandler main;
private ImageLevel img;
public ImageList() {}
public void setHandler(ImageHandler hand) {
main = hand;
img = main.getImg1();
}
public void add(Buffer addi) {
final String added = addi.getName();
JMenuItem uusi = new JMenuItem(added);
main.getMenu5().add(uusi);
uusi.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
img.setBuffer(added);
main.getScr().updateUI();
}
});
}
}
This works as it should. For this site I translated the original Finnish names to English, wonder why I wrote them in Finnish originally...I suck at naming things.
Method add is supposed to be called multiple times while the program is running.
What I cannot understand really is the inner class implementation of the interface ActionListener, namely its compilation and how it works.
If I have two buttons on my interface and I want them to do different things, I need two inner classes, one for each, each having its own inner implementation of the interface ActionListener. But in my code there is one class that seems to do the work of many, one complied .class-file for it, but the final result works as if there were many.
Can someone educate me on this issue? Is this code here one class and new buttons are instances of it? Are they new classes? Should there be a new .class-file for each new button? etc...