create images clickable on jpanel

2019-07-18 04:10发布

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.

2条回答
地球回转人心会变
2楼-- · 2019-07-18 04:40

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();
   }
});
查看更多
老娘就宠你
3楼-- · 2019-07-18 04:42

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.

查看更多
登录 后发表回答