-1

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.

Dipu Raj
  • 1,784
  • 4
  • 29
  • 37
  • Mixing GUI and console based apps is not a good idea, the user has an expectation for one or the other. Java does not have a native console library for generating "pretty" output, so I'd suggest you focus on updating the GUI with the new value instead – MadProgrammer Jan 16 '17 at 03:52
  • Ya I know, it is just that in school we are learning through a program called Ready To Program which is simplified java with a built in console and basic JFrame. I have been teaching myself to get further ahead and haven't reached the point of making a well rounded GUI. – Bardia Foroughi Jan 16 '17 at 03:54
  • [This](http://stackoverflow.com/questions/15843202/how-to-show-percentage-progress-of-a-downloading-file-in-java-consolewithout-ui/15846788#15846788) is not a pretty solution, but it will work, but I'd personally avoid it based on where you're starting... – MadProgrammer Jan 16 '17 at 04:00
  • Is there a way I can add a JLabel on the window instead of using the console? Because currently if I add a JLabel it removes the JButton. – Bardia Foroughi Jan 16 '17 at 04:05
  • [How to use labels](http://docs.oracle.com/javase/tutorial/uiswing/components/label.html) and [Laying Out Components Within a Container](https://docs.oracle.com/javase/tutorial/uiswing/layout/index.html) – MadProgrammer Jan 16 '17 at 04:06
  • What this cole method do? – siddhartha jain Jan 16 '17 at 04:13

1 Answers1

0

You are printing the result in the terminal itself, you cannot clear the previous line like this, instead use a text box in the frame itself that displays the result.

Vishnu
  • 1,757
  • 2
  • 11
  • 19