gpt4 book ai didi

Java Actionlistener 和 getSource()

转载 作者:行者123 更新时间:2023-12-02 03:58:45 27 4
gpt4 key购买 nike

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

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

最佳答案

为按钮设置操作命令:

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

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

if (sString.equals("Click"))

比较源按钮:

if(ae.getSource() == Clicker)

关于Java Actionlistener 和 getSource(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35136331/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com