How to count the clicks on a button in Java

2019-08-26 20:30发布

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!

Here is my updated code:

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

2条回答
狗以群分
2楼-- · 2019-08-26 20:47

Just add a mouse listener

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

    // use evtent.getClickCount()
  }
});
查看更多
Evening l夕情丶
3楼-- · 2019-08-26 20:48

For whichever button you want this would be appropriate:

        int buttonClicked = 0;
        objButton1.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e)
        {
           buttonClicked++;
           System.out.println(buttonClicked);
        }
    });      

You can replace objButton1 with whatever button you find appropriate. The button must be associated with the action listener and perhaps you want your result to send to console when clicked so I added the print statement inside.

查看更多
登录 后发表回答