Java Swing GUI

How to Count the Clicks on a Button in Java

In this tutorial, we are going to see how to count the clicks on a button in Java Swing. The following program simply creates a window and puts two buttons on it. The button updates a counter each time it is clicked. There is a label that displays the counter value.


 

Java Program to count the clicks on a button:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ClickCounter implements ActionListener 
{
  // Initialize the counter
  private int i = 0;
  
  // label to display the counter value
  private JLabel label;

  // Increment button
  private JButton plus;

  // Decrement button
  private JButton moins;
  
  public JPanel getPanel() {
    // Create the panel
    JPanel panel = new JPanel();
    
    // Add increment button to JPanel
    plus = new JButton("+");
    plus.addActionListener(this);
    panel.add(plus);
    
    // Add decrement button to JPanel
    moins = new JButton("-");
    moins.addActionListener(this);
    panel.add(moins);
    
    // Add the counter to JPanel
    label = new JLabel("" + i);
    panel.add(label);
    
    return panel;
  }
  
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == plus) {
      i++;
      label.setText("" + i);
    }
    else {
      i--;
      label.setText("" + i);
    }
  }

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setTitle("Click Counter");
    frame.setSize(new Dimension(250, 80));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    // Create the panel
    ClickCounter counter = new ClickCounter();
    JPanel counterPanel = counter.getPanel(); 
      
    // Add the panel to the center of the window
    Container content = frame.getContentPane();
    content.add(counterPanel, BorderLayout.CENTER);
    
    // Show the window
    frame.setVisible(true);
  }
}

Output:


mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *