简体   繁体   中英

Java Button Click Counter

I wanted to make a button that every time it is clicked it would increase the variable int score by 1. So far I have added the button and everytime I click it does add one but instead of replacing the old score it writes a new line for each click.

public class ButtonClicker extends JFrame implements ActionListener
{
    static int score = 0;

    public static void main (String[] args)
    {
        ButtonClicker run = new ButtonClicker();
        run.cole();
    } // main method

    public ButtonClicker () 
    {
        JFrame j = new JFrame("Window title");
        JButton click = new JButton("button");

        j.getContentPane().add(click);

        click.addActionListener(this);

        j.setSize(450,450);
        j.setVisible(true);
    }

    public void actionPerformed(ActionEvent e)
    {
        System.out.println("Score: " + score);
        score++;        
    }

    public void cole ()
    {

    }
} // ButtonClicker class

So everytime I click instead of replacing Score:0 to Score: 1 and so on, it adds a new line. Example Score:0 Score:1 Score:2 etc.

您正在终端本身中打印结果,您不能像这样清除前一行,而是使用框架本身中的文本框来显示结果。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM