Results 1 to 14 of 14
  1. #1
    exose is offline Member
    Join Date
    Sep 2010
    Posts
    19
    Rep Power
    0

    Default new instance of the program (all the time)

    Hi,

    I have implemented a reset button for my game but that reset button creates a new instance of the game all the time.

    I have really no clue how to solve that...

    would you be able to look at this for me please?

    Java Code:
    	public class Restart implements ActionListener
    	{
    		GUI g;
    		public void actionPerformed(ActionEvent e)
    		{
    			this.g=new GUI();
    			initGame(g);
    		}
    
    	}
    
        public static void main(String[] args)
        {
    		GUI guessingGame = new GUI();
    		guessingGame.initGame(guessingGame);
    
    
        }
        public void initGame(GUI gui)
        {
        	GUI start;
            start = gui;
            start.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            start.setVisible(true);
            start.setSize(400,170);
            start.setTitle("Random Number Guessing Game");
        }

  2. #2
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,085
    Rep Power
    20

    Default

    That's because you're creating a new instance of the game each time:
    Java Code:
    this.g=new GUI();

  3. #3
    exose is offline Member
    Join Date
    Sep 2010
    Posts
    19
    Rep Power
    0

    Default

    i know :)

    how I should correct that then? I have no clue

  4. #4
    dswastik is offline Senior Member
    Join Date
    Dec 2008
    Location
    Kolkata
    Posts
    282
    Rep Power
    6

    Default

    May be this help

    Java Code:
    public class Restart implements ActionListener
    	{
    		static GUI g=null;
    		public void actionPerformed(ActionEvent e)
    		{
    			if(g==null){
    				g=new GUI();
    			}
    			initGame(g);
    		}
    
    	}
    Swastik

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by exose View Post
    i know :)

    how I should correct that then? I have no clue
    Don't do it. Instead give your GUI a method, say called reset(), and in the code of that method reset all the gui's fields and components. Also give your Restart class a constructor that takes a GUI parameter and pass the current GUI into this method so that the current displayed GUI can be acted upon.

    e.g.,

    Java Code:
    	public class Restart implements ActionListener
    	{
    		GUI g;
    
    		public Restart(Gui g) {
    		   this.g = g;
    		}
    
    		public void actionPerformed(ActionEvent e)
    		{
    			//  this.g=new GUI();
    			initGame(g);
    		}
    
    	}
    Last edited by Fubarable; 04-08-2011 at 01:57 PM.

  6. #6
    exose is offline Member
    Join Date
    Sep 2010
    Posts
    19
    Rep Power
    0

    Default

    thanks for your help!

    I have one more issue, what I should put into when I instantiate new button? Cuz now the consructor looks:

    Java Code:
    public Restart(GUI g) {
    		   this.g = g;
    		}
    I am getting an error here:

    Java Code:
        	r = new Restart();
        	restartButton.addActionListener(r);
    cannot find symbol constructor Restart(GUI.Restart)

    I have added new variable:
    GUI g;

    and my button looks like:

    Java Code:
        	r = new Restart(g);
        	restartButton.addActionListener(r);
    However I still have new instance of the program every time :S
    Last edited by exose; 04-08-2011 at 02:11 PM.

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    You add a reference to the currently visible GUI object. I have no idea where you're calling new Reset(...). Is it in the GUI class? If so, then pass in the "this" argument ( but no quotes).

  8. #8
    exose is offline Member
    Join Date
    Sep 2010
    Posts
    19
    Rep Power
    0

    Default

    yes I call restartButton in GUI class, actually in the constructor of this class :)

    Java Code:
    r = new Restart(this.g);
        	restartButton.addActionListener(r);
    this is my full code:

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.util.Random;
    
    public class GUI extends JFrame{
    
        private int secretNumber;
        private int guess;
        Random randomGenerator;
    
        private JButton button;
        private JButton restartButton;
        private JTextField textField;
        private JLabel infoLabel;
        private JLabel promptLabel;
        private JLabel resultLabel;
        private JLabel randomLabel;
        private int count = 0;
        private int max_GUESSES = 6;
        Event e;
        Restart r;
        GUI g;
    
    
        public GUI()
        {
        	JMenuBar menuBar = new JMenuBar();
    
            JMenu menuFile = new JMenu();
            JMenu menuSystem = new JMenu();
            JMenu menuSearch = new JMenu();
    
            JMenuItem menuFileExit = new JMenuItem();
            JMenuItem menuSystemLinear = new JMenuItem();
            JMenuItem menuSystemBinary = new JMenuItem();
    
    
    		menuSystem.setText("Login");
    		menuFile.setText("File");
    		menuFileExit.setText("Exit");
    		menuSystemLinear.setText("Linear");
    		menuSystemBinary.setText("Binary");
    
        	infoLabel = new JLabel("Before you will be able to start the game you need to log in!");
        	add(infoLabel);
    
        	setLayout(new FlowLayout());
        	promptLabel = new JLabel("Enter a random number 1-100");
        	add(promptLabel);
    
        	textField = new JTextField(5);
        	add(textField);
    
        	button = new JButton("Guess!");
        	add(button);
    
        	resultLabel = new JLabel("");
        	add(resultLabel);
    
        	randomLabel = new JLabel("");
        	add(randomLabel);
    
        	restartButton = new JButton("Restart!");
        	add(restartButton);
    
        	e = new Event();
        	button.addActionListener(e);
        	button.setEnabled(false);
    
        	r = new Restart(this.g);
        	restartButton.addActionListener(r);
    
        	// Add action listener.for the menu button
            menuFileExit.addActionListener
            (
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        GUI.this.windowClosed();
                    }
                }
            );
    
            // Add action listener.for the linear search option
    		menuSystemLinear.addActionListener
    		(
    			new ActionListener()
    				{
    					public void actionPerformed(ActionEvent e)
    						{
    							UserValidation validation=null;
    							validation = new LinearUserValidation();
    							if (validation.checkPwd())
    							{
    								button.setEnabled(true);
    							}
    						}
    				}
    		);
    
    		menuSystemBinary.addActionListener
    		(
    			new ActionListener()
    				{
    					public void actionPerformed(ActionEvent e)
    						{
    							UserValidation validation=null;
    							validation = new BinaryUserValidation();
    							if (validation.checkPwd())
    							{
    								button.setEnabled(true);
    							}
    						}
    				}
    		);
    
    		menuFile.add(menuFileExit);
            menuBar.add(menuFile);
    		menuSystem.add(menuSystemLinear);
    		menuSystem.add(menuSystemBinary);
    	 	menuBar.add(menuSystem);
    	 	setJMenuBar(menuBar);
    
    	 	// Add window listener.
            this.addWindowListener
            (
                new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                        GUI.this.windowClosed();
                    }
                }
            );
            secretNumber = (int)(Math.random()*100+1);
    
        }
        protected void windowClosed()
        {
            System.exit(0);
        }
    
    
    	public class Event implements ActionListener
    	{
    
    		public void actionPerformed(ActionEvent e)
    		{
    			++count;
    			guess = (int)(Double.parseDouble(textField.getText()));
    
    				if (guess == secretNumber)
    				{
    	        		resultLabel.setText("you won the game!");
    
    	        	}
    	        	if (guess < secretNumber)
    	        	{
    	        		resultLabel.setText("your number is lower, this is your "+count+" guess");
    	        	}
    
    				if (guess > secretNumber)
    	        	{
    					resultLabel.setText("your number is higher, this is your "+count+" guess");
    	        	}
    	        	if ((count > max_GUESSES)&&(guess != secretNumber))
    				{
    				resultLabel.setText("you had too many tries, please start game again");
    				randomLabel.setText("the random number was "+ secretNumber);
    				}
    		}
    	}
    	public class Restart implements ActionListener
    	{
    		GUI g;
    
    		public Restart(GUI g) {
    		   this.g = g;
    		}
    
    		public void actionPerformed(ActionEvent e)
    		{
    			initGame();
    		}
    
    	}
    
        public static void main(String[] args)
        {
    		GUI guessingGame = new GUI();
    		guessingGame.initGame();
    
    
        }
        public void initGame()
        {
        	GUI start = new GUI();
            start.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            start.setVisible(true);
            start.setSize(400,170);
            start.setTitle("Random Number Guessing Game");
        }
    
    }

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

  10. #10
    exose is offline Member
    Join Date
    Sep 2010
    Posts
    19
    Rep Power
    0

    Default

    corrected! :)

    my resetButton looks like:

    Java Code:
    r = new Restart(this);
        	restartButton.addActionListener(r);
    but I am still getting new instances of the program...

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by exose View Post
    corrected! :)

    my resetButton looks like:

    Java Code:
    r = new Restart(this);
        	restartButton.addActionListener(r);
    but I am still getting new instances of the program...
    This is because your code is only doing what you tell it to do. What do you expect will happen when you call initGame method in the actionPerformed:

    Java Code:
       public void initGame() {
          [color="red"][b]GUI start = new GUI();[/b][/color]
          start.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          start.setVisible(true);
          start.setSize(400, 170);
          start.setTitle("Random Number Guessing Game");
       }

    To solve this problem and to learn programming, you have to walk through your code and think "what will happen when this line is executed?", because the answers are all in your code. Again, the Results class can have no lines that create a new GUI object. None. Instead your Result object now has a reference to the current GUI object, g, and you need to use this reference as was suggested above. That means in actionPerformed call method(s) off of the g variable to reset your GUI. And again, you will have to give the GUI class its own method perhaps called "reset()" that does all the necessary reset actions (initialize fields and components), and this method needs to be called in Result's actionPerformed. If this doesn't make sense please let me know what confuses you.
    Last edited by Fubarable; 04-08-2011 at 03:08 PM.

  12. #12
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    In simplest terms, something like so:

    Java Code:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    
    public class GUI {
       private JButton restart = new JButton("Restart");
       
       public GUI() {
          // TODO f
          
          restart.addActionListener(new Restart(this));
       }
       
       public void reset() {
          // initialize all of GUI's fields
          
          // reset all of GUI's components
       }
    }
    
    class Restart implements ActionListener {
       private GUI g;
       
       public Restart(GUI g) {
          this.g = g;
       }
    
    
       public void actionPerformed(ActionEvent e) {
          g.reset();
       }
    }

  13. #13
    exose is offline Member
    Join Date
    Sep 2010
    Posts
    19
    Rep Power
    0

    Default

    as far I understand in this line of code:

    Java Code:
    [COLOR="Red"]GUI start = new GUI();[/COLOR]
    a constructor of the GUI class is executed.

    I understand what you meant, I think, my assumption was wrong I thought that I can just create a new instance of my program and then program will be over-written by it.

    Instead, you suggest to create a reset method where I will reset all the variables.

    thank you for your input! I will try to do that now, and not try to bother you too much :)

  14. #14
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by exose View Post
    as far I understand in this line of code:

    Java Code:
    [COLOR="Red"]GUI start = new GUI();[/COLOR]
    a constructor of the GUI class is executed.

    I understand what you meant, I think, my assumption was wrong I thought that I can just create a new instance of my program and then program will be over-written by it.
    "new" creates a new completely new and distinct entity, completely unrelated to the currently viewed GUI. Your code's results should prove this to you. What happens when it's called? Do you see a completely new GUI? I think that you're seeing the light finally!

    Instead, you suggest to create a reset method where I will reset all the variables.
    Yes!


    thank you for your input! I will try to do that now, and not try to bother you too much :)
    Good luck!

Similar Threads

  1. Time it took to run and complete a program.
    By AcousticBruce in forum IntelliJ IDEA
    Replies: 3
    Last Post: 12-17-2010, 05:31 PM
  2. Find instance that owns instance?
    By Addez in forum New To Java
    Replies: 2
    Last Post: 04-04-2010, 03:36 PM
  3. calculating time of program runing
    By sara12345 in forum New To Java
    Replies: 3
    Last Post: 03-17-2010, 12:25 AM
  4. Can we find out program excecution Time?
    By makpandian in forum New To Java
    Replies: 1
    Last Post: 02-27-2009, 01:30 PM
  5. Payroll Program exits at wrong time
    By jsand2 in forum Java Applets
    Replies: 13
    Last Post: 01-26-2009, 03:10 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •