Search code examples
javapythonswingbuttonactionlistener

Adding a action listener in java for a counter


I am a fairly new user with programming in Java with about a week and a bit experience, as of before I have been using python for about 3 years but thought to give java a try. I have been trying to develop my skills by creating small projects and applications and am now creating a small GUI counter.

I have achieved creating the GUI with 2 buttons and a label and have tested the maths behind the application but I am struggling to work out how the ActionListener works as it feels a lot different to python when making a button have a action.

This is My Code;

package gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.*;

public class GUI{
  //This creates a frame or panel to contain things
  public static void main(String[] args) {

  //Maths To The Counter
  int Counter = 0;
  System.out.println(Counter);
  Counter =+ 1;
  System.out.println(Counter);

  //Creating The Frame
  JFrame frame = new JFrame();

  JPanel panel = new JPanel();
  panel.setBackground(Color.WHITE);
  frame.getContentPane().add(panel);

  //Creating The Label
  JLabel label3 = new JLabel("Counter: ");
  panel.add(label3); 

  //Button Which should have a funtion to add and display the number
  JButton button = new JButton("Click Here.");
  panel.add(button);

  //Button to reset the counter
  JButton buttonReset = new JButton("Reset Counter.");
  panel.add(buttonReset);

  //Set Size Of Window
  frame.setSize(new Dimension(500, 400));
  //Set Starting Position to centre
  frame.setLocationRelativeTo(null);
  //Setting a default close action
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  //Set Title
  frame.setTitle("Counter");
  //Disable Resize
  frame.setResizable(false);
  //Setting if its visible
  frame.setVisible(true);
  //Fits frame to fit everything
  frame.pack();


  }



}
    enter code here

I know that in python a action is in a function so that has been my logic to this problem however I have seen that I need to use the actionlistener instead and I am struggling to get my head around it.

If Someone could show me how this type of action should be implemented it would be great help, I have watch some youtube videos and done a bit of research but im still struggling to understand in my situation how to do it.

For any confussion im sorry, overall my question is how do I add a action to a button in my program that can implement my maths at the start.

As well any feedback on the structure of my code would be welcomed as I am just starting in java and I do know poor structure can lead to mistakes.


Solution

  • This code should work:

    Basically, in the main method I am creating an instance of the class and calling a method to create the gui.

    I also created an instance variable as the counter, otherwise you won't be able to update the variable in your action listener.

    public class Gui {
    
        private int counter;
    
        // This creates a frame or panel to contain things
        public static void main(String[] args) {
    
            Gui gui = new Gui();
            gui.create();
        }
    
        private void create() {
    
            // Creating The Frame
            JFrame frame = new JFrame();
    
            JPanel panel = new JPanel();
            panel.setBackground(Color.WHITE);
            frame.getContentPane().add(panel);
    
            // Creating The Label
            JLabel label3 = new JLabel("Counter: ");
            panel.add(label3);
    
            // Button Which should have a funtion to add and display the number
            JButton button = new JButton("Click Here.");
            panel.add(button);
    
            button.addActionListener(new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.out.println(counter++);
                }
            });
    
            // Button to reset the counter
            JButton buttonReset = new JButton("Reset Counter.");
            panel.add(buttonReset);
    
            buttonReset.addActionListener(new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent e) {
                    counter = 0;
                }
            });
    
            // Set Size Of Window
            frame.setSize(new Dimension(500, 400));
            // Set Starting Position to centre
            frame.setLocationRelativeTo(null);
            // Setting a default close action
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            // Set Title
            frame.setTitle("Counter");
            // Disable Resize
            frame.setResizable(false);
            // Setting if its visible
            frame.setVisible(true);
            // Fits frame to fit everything
          }
      }
    

    With Lambda expressions, you can simplify your action listeners as follows:

    button.addActionListener(a -> System.out.println(counter++));
    buttonReset.addActionListener(a -> counter = 0);
    

    If you want to write more than 1 statement, then you can just put your code in curly brackets:

    button.addActionListener(a -> {
            System.out.println(counter++);
            System.out.println("doing more stuff...");
    });