Java MouseListener

前端 未结 5 1677
隐瞒了意图╮
隐瞒了意图╮ 2020-12-05 19:41

I have a bunch of JLabels and i would like to trap mouse click events. at the moment i am having to use:

public void mouseClicked(MouseEvent arg0) {

}

publ         


        
5条回答
  •  臣服心动
    2020-12-05 20:22

    One could use a MouseAdapter class, which implements the MouseListener interface, so one does not need to implement all the methods.

    However, by overriding the methods of interest, one can get the desired behavior. For example, if one overrides the mouseClicked method, then one can define some behavior for the mouse click event.

    For example (untested code):

    JLabel label = new JLabel("Hello");
    
    label.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            System.out.println("Clicked!");
        }
    });
    

    In the code above, the JLabel will print "Clicked!" to the console upon being clicked on.

提交回复
热议问题