如何获得按钮actionListener来计算某人单击的次数?

时间:2018-10-24 15:10:56

标签: java swing jbutton

public class Button {

    public static void main(String[] args) {

        int numClicks = 0;

        JButton button1 = new JButton ();
        button1.setText("1 click = 1 dollar for animals you love");

        JFrame god = new JFrame ();

        JPanel panel = new JPanel();

        god.getContentPane().add(button1);
        god.add(button1);       
        god.setSize(new Dimension(400, 400));
        god.setVisible(true);

    }

    public void actionPerformed(ActionEvent event) {

    }

}

有人可以帮我弄清楚如何使Actionlistener计数按钮被点击的次数吗?我是一个noobie编码员(三个月),我真的坚持了这一点

1 个答案:

答案 0 :(得分:0)

您需要向按钮添加ActionListener。

button1.addActionListener(new MyActionList()); 
//MyActionList is an object which implements ActionListener

在您的情况下是同一个对象。

//---implements ActionListener---
public class Button implements ActionListener{

    private int clickCount;

    public Button() {

        clickCount = 0;

        JFrame god = new JFrame ();
        god.setSize(new Dimension(400, 400));

        //if you don't do this, your program still running, even if you click on X.
        god.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

        JPanel panel = new JPanel();

        god.add(panel);

        JButton button1 = new JButton("1 click = 1 dollar for animals you love");

        //here we add ActionListener
        button1.addActionListener(this);
        //'this' refer to the current object. In our case 'new Button()' from 'main'...
        //...which has implemented ActionListener.

        panel.add(button1);

        god.setVisible(true);

    }

    public static void main(String[] args){

        new Button();

    }

    //Override from Interface ActionListener and...
    //...here describe what happend when button was pressed.
    @Override
    public void actionPerformed(ActionEvent e) {

        clickCount++;

        System.out.println(clickCount);

    }


}