cannot add different mouse event listeners to different panels
Introduction:
I am trying to show all files in a folder in a grid view, when clicked on
the file, I should print out that name on the command line.
I have jpanels for all the files, so I am trying to detect click on the
jpanel and assign action to that panel, in a loop.
My problem,
When using the for loop, I have variable "name", which keeps the name of
file, I am trying to add mouse listener like this,
panel[i].addMouseListener(new MouseAdapter(){
    public void mouseClicked(MouseEvent e){
        System.out.println("MOUSE_RELEASED_EVENT:for "+name);
    }
});
As you can notice, I am iterating over i, adding mouselisteners to all
panels thus, but the problem is the variable name itself is being used in
the mouselisteners.
Example
If what written above is not the way to explain it, I mean say I have two
files, A and B.
What I am looking for is, mouse listener for first is,
System.out.println("MOUSE_RELEASED_EVENT:for A"); //Since name="A" here.
For second file is,
System.out.println("MOUSE_RELEASED_EVENT:for B");  //Since name="B" here.
But it doesn't happen this way, variable name is itself attached to the
mouse listeners, and what I get always is the final value of name, in my
example "B" always. Since it was the last value of name in the loop.
How do I solve this problem?
As an extra, can someone tell if I can fix size in BorderLayout for child
panels, they get resized no matter what I use, setSize, setPreferredSize,
setMaximumSize, setMinimumSize.
Thanks for time and efforts.
 
No comments:
Post a Comment