Search code examples
javaswingjbuttonactionlistenerjlabel

Mouse listener in button to change click count in label


How can I put MouseListener in JButton so that a JLabel changes to the no. of times the button is clicked?

I created a frame with a button and a label` using a mouse listener. The label of the frame shows the no. of times the button is clicked. I tried using the below program :

import javax.swing.*;
import java.awt.event.*;
class Bevent implements ActionListener
{
JFrame jf=new JFrame("BUTTON EVENT");
JButton jb=new JButton("CLICK !");
JLabel jl=new JLabel("CLicked 0 times");
int count=0;
Bevent()
{
jf.setSize(500,500);
jf.setLayout(null);
jf.setVisible(true);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jb.setBounds(100,100,100,30);
jf.add(jb);
jl.setBounds(100,200,200,30);
jf.add(jl);
jb.addActionListener(this);
}
public static void main(String arg[])
{
new Bevent();
}
public void actionPerformed(ActionEvent ae){
count=count+1;
jl.setText("CLicked "+count+" times");
jf.add(jl);
}
}

Is it an efficient code for the problem.


Solution

  • Here's one way of doing it.

    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    
    public class ButtonClick{
        JFrame frame;
        JLabel label;
        JButton button;
        int count = 1;
        
        public static void main(String[] args){
            ButtonClick gui = new ButtonClick();
            gui.go();
        }
    
        public void go(){
            frame = new JFrame();
    
            button = new JButton("Click me");
            button.addActionListener(new ClickListener());
    
            label = new JLabel("Clicked 0 times");
    
            frame.getContentPane().add(BorderLayout.CENTER, button);
            frame.getContentPane().add(BorderLayout.EAST, label);
    
            frame.setSize(400,300);
            frame.setVisible(true);
        }
    
        class ClickListener implements ActionListener{
            public void actionPerformed(ActionEvent event){
                label.setText("Clicked " + count + " times");
                count += 1;
            }
        }
    }
    

    In the code above, the JButton has a ClickListener which sets the JLabel's text to the number of times(instance variable count) the JButton was pressed.