0

I was trying to make a counter with ActionListener. And i wanted the JLabel to display how many times i have clicked on the button. But when i run the code it just gives me You have click..., i tried to make it resizable but it gave me the same result, and the google search gave me no useful info.

This is my code btw:

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;

public class Counter implements ActionListener {
  public JFrame frame = new JFrame();
  public JLabel label = new JLabel();
  public JButton button = new JButton();
  public int count = 0;

  public Counter() {
    frame.setSize(500, 500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setBackground(Color.gray);

    label.setText("You have clicked " + this.count + " times!");
    label.setBounds(50, 50, 120, 50);

    button.setBounds(70, 100, 60, 20);
    button.addActionListener(this);

    frame.add(label);
    frame.add(button);
    frame.setLayout(null);
    frame.setVisible(true);
  }

  @Override
  public void actionPerformed(ActionEvent event) {
    count++;
    label.setText("You have clicked " + this.count + " times!");
  }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

0 Answers0