0

I'm trying to write a "ClickerGame" that the user need to click on a button as much as he can in 1 min. Can you help me to improve the functionality of this program? it's not really working.

import javax.swing.*;

import java.awt.FlowLayout;
import java.awt.event.*;
import java.awt.*;
import java.lang.*;
import java.util.Date;

public class ClickerGame extends javax.swing.JFrame {
    int i,j;
    JPanel panel;
    JFrame frame;
    JButton start;
    JButton stop;
    JButton click;
    JTextArea text;
    JLabel label;
    public static void main(String[] args){
        ClickerGame a = new ClickerGame();
        a.go();
    }

    public void go(){
         frame = new JFrame();
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

         JPanel panel = new JPanel();

         click = new JButton("Click");
         click.addActionListener(new ClickListener());

         start=new JButton("Start");
         start.addActionListener(new StartListener());

         stop=new JButton("Stop");
         stop.addActionListener(new StopListener());
         panel.add(start);
         panel.add(click);
         panel.add(label);
         frame.getContentPane().add(BorderLayout.CENTER,panel);

         frame.setSize(500,500);
         frame.setVisible(true);
    }
    class ClickListener implements ActionListener{
        public void actionPerformed(ActionEvent event){

            click.setText("Number of clicks: "+i);
            i++;
        }

        }

    Timer timer = new Timer(1000,new ActionListener(){
        public void actionPerformed(ActionEvent e){
            Date currentTime = new Date();
            label= new JLabel(currentTime.toString());


        }
    });

    class StartListener implements ActionListener{
        public void actionPerformed(ActionEvent event){
            timer.start();
        }
    }
    class StopListener implements ActionListener{
        public void actionPerformed(ActionEvent event){
            timer.stop();
        }
    }

}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Michael
  • 189
  • 1
  • 10

2 Answers2

1

Your error is caused by trying to add label to the panel, as label is never initialised (null).

Remove: panel.add(label);

I'm not convinced the functionality of your game is as intended, but that's a separate question.

d.j.brown
  • 1,822
  • 1
  • 12
  • 14
0
panel.add(label);

In this line.. label is not initialized. Please initialize it before using like this -

label = new JLabel("ABC");
Srijani Ghosh
  • 3,935
  • 7
  • 37
  • 68