views:

25

answers:

2

hi How i can add icon (car, earth or other) image that can be clickabel by user? i want to add them on an jpanel with overrided paint method.

A: 

The easiest way is to add an Icon to a JButton, then you can use an ActionLlistener to handle the mouse click. You can also use:

button.setBorderPainted( false );

to get rid of the border so it looks like a label.

camickr
Using a button can sometimes have issues in various look and feels, especially if the image has transparent images - i.e. in rollover or armed state painting.
Keilly
How would this be different when using an Icon and text on a button the way it is normally used?. Would you not have the same problems? This sounds like a problem with the LAF although I've never seen it with Metal or Windows.
camickr
+1  A: 

Just use a JLabel with an icon. Then add a MouseListener to listen for clicks.

JLabel label = new JLabel(yourIcon); // probably an ImageIcon
label.addMouseListener(new MouseAdapter(){
   public void mouseClicked(MouseEvent e) {
     System.out.println("Click at: " + e.getPoint();
   }
});
Keilly
You should not handle mouseClicked. The standard is to handle mousePressed (or released depending on your requirement). That is another reason why a button is preferred. It collapses the pressed/released into an ActionEvent. Whereas a mouseClicked will not fire if the mouse is moved by even a pixel between the pressed and released events.
camickr