Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Number Game - Multiple ActionListener in the Same Class

I am only 6 - 7 weeks into learning Java, so I apologize in advance if my code is sloppy or terminology is off. I'm trying to create program that creates a random number and allows the user to guess until they get the correct number. It serves no real purpose other than a learning experience for me.

I have the basic program working, I just want to add other elements to improve it and gain the experience.

The program runs in a JFrame and has a JTextField for the user to enter their guess. I have ActionListener setup for the JTextField. I'd like to add a Start button that displays at the beginning of the game. When the user clicks the start button, the JTextField should become active. Also, when the user clicks guesses the correct answer, I'd like to use the start button to reset the program. I've experimented with several ways to do this with no success. I believe this will require multiple ActionListeners in the same class. I'm not even sure if this is possible?

Here is my code. Thanks in advance for any help.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

public class JMyFrame2 extends JFrame implements ActionListener {
    Random num = new Random();
    int computerGenerated = num.nextInt(1000);
    public int userSelection;
    JTextField numberField = new JTextField(10);
    JLabel label1 = new JLabel();
    Container con = getContentPane();
    int previousGuess;

    // constructor for JMyFrame
    public JMyFrame2(String title) {
        super(title);
        setSize(750, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        label1 = new JLabel(
                "I have a number between 1 and 1000 can you guess my number?" + "Please enter a number for your first guess and then hit Enter.");

        setLayout(new FlowLayout());
        add(numberField);
        add(label1);
        System.out.println(computerGenerated);

        numberField.addActionListener(this);
    }


    public void actionPerformed(ActionEvent e) {
        userSelection = Integer.parseInt(numberField.getText());
        con.setBackground(Color.red);

        if (userSelection == computerGenerated) {
            label1.setText("You are correct");
            con.setBackground(Color.GREEN);
        } else if (userSelection > computerGenerated) {
            label1.setText("You are too high");
        } else if (userSelection < computerGenerated) {
            label1.setText("You are too low");
        }
    }
}


public class JavaProgram5 {

    public static void main(String[] args) {


        JMyFrame2 frame2 = new JMyFrame2("Assignment 5 - Number Guessing Game");
        frame2.setVisible(true);
    }
}
like image 719
Brent Avatar asked Sep 26 '15 14:09

Brent


1 Answers

Sure you can have multiple action listeners. In fact, your class should not implement it.

Start by removing the actionPerformed method, and replace this line:

    numberField.addActionListener(this);

With this:

    numberField.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            userSelection = Integer.parseInt(numberField.getText());
            con.setBackground(Color.red);

            if (userSelection == computerGenerated) {
                label1.setText("You are correct");
                con.setBackground(Color.GREEN);
            } else if (userSelection > computerGenerated) {
                label1.setText("You are too high");
            } else if (userSelection < computerGenerated) {
                label1.setText("You are too low");
            }
        }
    });

You can add another action listener to the start button you plan to add, following this pattern, using an anonymous class. (It doesn't have to be an anonymous class, this was just simple to demonstrate.)

like image 101
janos Avatar answered Oct 02 '22 23:10

janos