java 计算按下 JButton 的次数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5602463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:51:47  来源:igfitidea点击:

Count how many times a JButton is pressed?

javauser-interfacebuttonjbutton

提问by Philip McQuitty

In the action performed code in a JAVA GUI, how would I count how many times a button is pressed, and do something different for each press of the button?

在 JAVA GUI 中执行操作的代码中,我如何计算按钮被按下的次数,并为每次按下按钮执行不同的操作?

  private class Listener implements ActionListener
  {
     public void actionPerformed (ActionEvent e)
     {

       HOW WOULD I COUNT HOW MANY TIMES THIS BUTTON HAS BEEN PRESSED?

     }

Thanks!!!

谢谢!!!

回答by camickr

Create a class variable and then increment the variable in the method.

创建一个类变量,然后在方法中递增该变量。

private class Listener implements ActionListener   
{      
    private int clicked;

    public void actionPerformed (ActionEvent e)
    {
         clicked++
    }
}

You can then create a method to access the variable.

然后,您可以创建一个方法来访问该变量。

回答by Sadiq

You can have a field in the Listener class and increment it every time the button is pressed and then have a switch to select the action to perform depending on the value of your variable.

您可以在 Listener 类中有一个字段并在每次按下按钮时增加它,然后有一个开关来根据变量的值选择要执行的操作。

private class Listener implements ActionListener   
{      
    private int clicks;

    public void actionPerformed (ActionEvent e)
    {
        clicks++;
        switch (clicks){
            case '1':
                // Do operation 1
                break;
            case '2':
                // Do operation 2
                break;
        }
    }
}

回答by Dinesh Madhup

You have declared clicks as int, therefore, case statement needs int value not the char.

您已将 clicks 声明为 int,因此,case 语句需要 int 值而不是 char。

Corrected version:

修正版:

private class Listener implements ActionListener   
{      
    private int clicks;

    public void actionPerformed (ActionEvent e)
    {
        clicks++;
        switch (clicks){
            case 1:
                // Do operation 1
                break;
            case 2:
                // Do operation 2
                break;
        }
    }
}

回答by Jebbillbobk

Just use e.getClickCountin your MouseEvent

只需e.getClickCount在您的 MouseEvent 中使用