Search code examples
javaappletawt

Java Actionlistener & getSource()


I'm trying to make an applet that will count how many times you have clicked a button, but it seems ActionListener isn't working properly. This code looks like it would work, but for some reason when I click the button in the applet, nothing is printed in the console or updated on the interface as it should.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class Test extends Applet implements ActionListener
{
    Button Clicker;
    Button Upgrade;
    int currentClicks = 0;

    public void init()
    {
        this.setSize(600,400);

        Button Clicker = new Button("Click");
        add(Clicker);
        Clicker.addActionListener(this);

        Button Upgrade = new Button("Autoclick Upgrade");
        add(Upgrade);
        Upgrade.addActionListener(this);
    }
    public void paint (Graphics g)
    {
        g.drawString("Test",300,50);
        g.drawString(String.valueOf(currentClicks), 300, 100);
    }
    public void actionPerformed(ActionEvent ae) 
    {
        String sString = ae.getActionCommand();
        if (sString.equals(Clicker))
        {
            System.out.println("Clicker was pressed");
            currentClicks++;
            System.out.println("Total Clicks: "+currentClicks);
            repaint();
        }
        else if (sString.equals(Upgrade))
        {
            System.out.println("Upgrade was pressed");
            if (currentClicks >= 25)
            {
                System.out.println("Upgrade was successfully purchased!");
                currentClicks = currentClicks - 25;
                repaint();
            }
            else
            {
                System.out.println("Upgrade was not successfully purchased!");
                repaint();
            }
        }
    }
}

Solution

  • Set an action command to the Button :

    Button Clicker = new Button("Click");
    Clicker.setActionCommand("Click");
    

    Then use that to determine what was clicked :

    if (sString.equals("Click"))
    

    OR

    Compare the source button :

    if(ae.getSource() == Clicker)