如何计算 Java 中按钮的点击次数 [英] How to count the clicks on a button in Java

查看:80
本文介绍了如何计算 Java 中按钮的点击次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我正在学习的 Java 类编写了一个带有两个按钮的程序.我现在需要计算并显示每个按钮获得的点击次数.然而,在课堂上甚至没有提到如何做到这一点.请帮我完成这个.我有一些计算点击次数的代码,但我很确定这是错误的.

I have written a program with two buttons for a Java class that I am taking. I now need to count and display the number of clicks each button gets. However, how to do this was not even touched on in the class. Please help me accomplish this. I have some code for counting clicks but am fairly certain that it is wrong.

任何帮助将不胜感激.非常感谢!

Any help would be very greatly appreciated. Thank You So Much!

非常感谢大家的帮助.我已经取得了更大的成就,但我仍然遇到编译错误.其中最新的是预期标识符".我不知道如何解决这个问题,因为这个程序所针对的课程真的一点也不好.再次感谢您的帮助!

Thank you all so much for your help. I have managed to get a little more accomplished, but I am still getting compiling errors. The most recent of which being "identifier expected". I don't know how to fix this, as the class that this program is for really is not good at all. Again, thank you for your help!

这是我更新的代码:

import java.awt.*;
import java.awt.event.*;
public class FinalProj1 extends Frame implements ActionListener,WindowListener
{
FinalProj1()
{
    setTitle("Click Counter");
    setSize(400,400);
    show();
}
public static void main(String args[])
{
    Frame objFrame;
    Button objButton1;
    Button objButton2;
    TextField count = new TextField(20);
    TextField count2 = new TextField(20);
    Label objLabel;
    Label objLabel2;

    objFrame= new FinalProj1();
    objButton1= new Button("Agree");
    objButton2= new Button("Dissagree");
    objLabel= new Label();
    objLabel2= new Label();
    objLabel2.setText("Mexican Food Is Better Than Chineese Food");

    objButton1.setBounds(110,175,75,75);
    objButton2.setBounds(190,175,75,75);
    objLabel2.setBounds(80,95, 250,25);

    objFrame.add(objButton2);
    objFrame.add(objButton1);
    objFrame.add(objLabel2);
    objFrame.add(objLabel);
}
private int numClicks = 0;
    private int numClicks2 = 0;
    objButton1.addActionListener(this)
    objButton2.addActionListener(this)
    public void actionPerformed(ActionEvent e)
    {
        numClicks++;
        numClicks2++;
        count.setText("There are " + numClicks + " who agree");
        count2.setText("There are " + numClicks2 + " who dissagree");
    }
}

推荐答案

只需添加鼠标监听器

button.addMouseListener(new MouseAdapter() {
  public void mouseClicked(MouseEvent evtent) {

    // use evtent.getClickCount()
  }
});

这篇关于如何计算 Java 中按钮的点击次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆