Java Actionlistener&的getSource()

时间:2016-02-01 17:10:48

标签: java applet awt

我正在尝试制作一个小程序,它会计算你点击按钮的次数,但似乎ActionListener无法正常工作。这段代码看起来会起作用,但出于某种原因,当我单击applet中的按钮时,控制台中没有打印任何内容,也没有在界面上更新。

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();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

将动作命令设置为按钮:

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

然后使用它来确定点击的内容:

if (sString.equals("Click"))

比较源按钮:

if(ae.getSource() == Clicker)