statsButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e){
              
              //Return the string "stats" to gameLoop() as cmd
            }
        });
public void gameLoop(){

		Scanner lineScanner = new Scanner(System.in);
		cmd = "";

		System.out.print(getBoard().printBoard(false));
		
		while (!cmd.equals("quit")) {
			System.out.print(">");
			Scanner wordScanner = new Scanner(lineScanner.nextLine());

		if (wordScanner.hasNext()) {
			cmd = wordScanner.next();
			if (cmd.equals("board")) {
				System.out.print(getBoard().printBoard(false));
                } else if (cmd.equals("ships")) {
			System.out.print(getBoard().printBoard(true));
                } else if (cmd.equals("help")) {
                    printHelp();    
                } else if (cmd.equals("stats")) {
                    printStats();
                } else if (cmd.equals("fire")) {
			if(fire(wordScanner)) {	
			printStats();
			cmd = "quit";
					}
                } else if (cmd.equals("quit")) {	
                } else if (!cmd.equals("")) {
                    System.out.println(ILLEGAL_COMMAND);
                }
			}
			
		}
	}

What I'm trying to do is that when the user clicks the statsButton, the String cmd in the gameLoop would be changed to "stats". The statsButton and the gameLoop() are located in two different classes. Anyone can give me an idea how to do it? (I've attempted pipedreader/pipedwriter) and I just can't seem to get it right.

*I'm basically trying to make my console application into a GUI application without changing the original console application.

Edited 5 Years Ago by rlhh: n/a

Well, call gameLoop() from actionPerformed() of the button and pass the cmd as argument...

statsButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e){
              
              gameLoop("stats");
            }
        });
public void gameLoop(String cmd){

		//do stuff with cmd
	}

And since you say they are in two different classes, you can create an instance of the class that contains this gameLoop() and store it in your GUI class that contains the button and u can use that object(instance) to call gameLoop().

Or if ur game loop is in a class that need not be instantiated....or if u dont want that method... you can make gameLoop() static and u can call it directly using the ClassName.gameLoop("stats")

Edited 5 Years Ago by stevanity: n/a

Would that work? How am I going to modify the String cmd when I click a different button?

Well that was just an example....

What u can do is, u can name the button "stats", "fire", etc....

and in the actionPerformed method, u can make a call to get the button name like this:

String cmd=e.getActionCommand()

Now u can pass cmd.... This way if fire is pressed, above method will return "fire" which u can pass to gameLooop().

This article has been dead for over six months. Start a new discussion instead.