Can I add an action listener to a JLabel?

后端 未结 4 1408
小鲜肉
小鲜肉 2021-02-05 09:59

I want to replace a JButton by a JLabel and I want my code to perform some action when the JLabel is clicked.

When I had the JButton I used action listener to handle cli

4条回答
  •  南旧
    南旧 (楼主)
    2021-02-05 10:47

    Sure. JLabels have a method which allow you to attach a MouseListener object. The MouseListener object requires a MouseAdapter() object. MouseAdapter is an abstract class which ideally serves as an Adapter for for creating on the fly listeners to do things.

    JLabel lb = new JLabel(An image icon, if you'd like.);
    
    //now lets attach a listener to your JLabel
    lb.addMouseListener(new MouseAdapter() 
    {
        @Override
        public void mouseClicked(MouseEvent e) 
        {
            //THIS CODE WILL RUN WHEN THE EVENT OF CLICKING IS RECEIVED.
            //example of something you could do below.
            new Random().ints().limit(60).forEach(System.out::println);
        }
    });
    

提交回复
热议问题