Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to call mouseClicked() of JButton without clicking it?

 
Marek Krokosinski
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello.


I'm making simple gallery, and i have small problem. I have for List of 20 JButtons (which icon is my Image). I don't want to add MouseListeners to each JButton. And i tried to add Action Listener in a loop. I tried something like this:


and it doesn't work, because button wasn't pressed. licznik (my counter variable) counts from 1 to 20,"while" loop sets action listener for every JButton, but when I click on my JButton it always display last image on the list (number 20).

I think i would have to click the JButton on each iteration. I tried also with something like this:



And it also doesn't work. It makes "clicks", but when I click on any button in my gallery it always displays last image.

Is it possible to add action/mouse listeners in a loop to the List of Components?
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
> miniaturyObrazkow.get(licznik).addMouseListener(new MouseListener() {

any time you code like this, look to using the Adapter classes - it would be like this:
miniaturyObrazkow.get(licznik).addMouseListener(new MouseAdapter() {

then you only need to override the event you want, instead of having to handle them all

> public void mouseClicked(MouseEvent e) {

mouseClicked() is a poor choice, it doesn't always fire - mousePressed() is better

if I'm reading your problem correctly, here's a simple demo
click any button and its index will show as its text (0-based indexes)
(would be the same for images)

 
Marek Krokosinski
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Michael Dunn wrote:> miniaturyObrazkow.get(licznik).addMouseListener(new MouseListener() {

any time you code like this, look to using the Adapter classes - it would be like this:
miniaturyObrazkow.get(licznik).addMouseListener(new MouseAdapter() {

then you only need to override the event you want, instead of having to handle them all

> public void mouseClicked(MouseEvent e) {

mouseClicked() is a poor choice, it doesn't always fire - mousePressed() is better



Thank you for your advice, I will try to remember that :)

and cool, everything is working perfectly :) Thanks !
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic