create images clickable on jpanel

2019-07-18 03:49发布

问题:

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.

回答1:

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();
   }
});


回答2:

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.