Java guessing game - java

I am trying to write a program in Java that takes a random number from 1-1000 and then as the guess it the background color changes to blue(cold) or red(warm) if they are in the number. I am new to java GUI, but I think the rest of the logic is right, not sure. It compiles, but the guess button doesn't work. Any guidance will be appreciated.
package guessGame;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.color.*;
import java.util.Random;
import java.util.Random;
import java.util.logging.FileHandler;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class GuessGame extends JFrame
{
private JFrame mainFrame;
private JButton GuessButton;
private JButton QuitButton;
private JLabel prompt1, prompt2;
private JTextField userInput;
private JLabel comment = new JLabel("What is your destiny?");
private JLabel comment2 = new JLabel (" ");
//private int number, guessCount;
//private int lastGuess;
private int randomNumber;
private Color background;
public GuessGame()
{
mainFrame = new JFrame ("Guessing Game!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Creates components
GuessButton = new JButton("Guess");
QuitButton = new JButton("Quit");
prompt1 = new JLabel("I have a number between 1 and 1000.");
prompt2 = new JLabel("Can you guess my number? Enter your Guess:");
comment = new JLabel ("What is your destiny?");
comment2 = new JLabel (" ");
userInput = new JTextField(5);
//userInput.addActionListener(new GuessHandler());
//content pane
Container c = mainFrame.getContentPane();
c.setLayout(new FlowLayout());
//adding component to the pane
c.add(prompt1);
c.add(prompt2);
c.add(userInput);
c.add(comment2);
c.add(GuessButton);
c.add(QuitButton);
c.add(comment);
GuessButton.setMnemonic('G');
QuitButton.setMnemonic('Q');
mainFrame.setSize(300,200);
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
mainFrame.setResizable(false);
// define and register window event handler
// mainFrame.addWindowListener(new WindowAdapter() {
// public void windowClosing(WindowEvent e)
// { System.exit(0); }
// });
//creating the handler
GuessButtonHandler ghandler = new GuessButtonHandler(); //instantiate new object
GuessButton.addActionListener(ghandler); // add event listener
QuitButtonHandler qhandler = new QuitButtonHandler();
QuitButton.addActionListener(qhandler);
}
public void paint (Graphics g)
{
super.paint(g);
setBackground(background);
}
class QuitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
class GuessButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
int getUserInput=0;
int diff;
int Difference;
randomNumber = new Random().nextInt(1001);
try {
getUserInput = Integer.parseInt(
userInput.getText().trim());
} catch (NumberFormatException ex){
comment.setText("Enter a VALID number!");
return;
}
if (getUserInput == randomNumber){
JOptionPane.showMessageDialog(null, "CONGRATULATIONS! You got it!!",
"Random Number: " + randomNumber,
JOptionPane.INFORMATION_MESSAGE);
randomNumber = new Random().nextInt(1000) + 1;
return;
}
if (getUserInput > randomNumber){
comment.setText( "Too High. Try a lower number." );
diff=getUserInput - randomNumber;
Difference=Math.abs(diff);
} else {
comment.setText( "Too Low. Try a higher number." );
diff=randomNumber - getUserInput;
Difference=Math.abs(diff);
}
if(Difference<=25){
comment2.setText("Cold");
setBackgroundColor(Color.blue);
}
if(Difference<=10){
comment2.setText("Warm");
setBackgroundColor(Color.red);
}
else {
}
}
private void setBackgroundColor(Color color) {
setBackgroundColor(color);
}
}
public static void main(String args[]) {
//instantiate gueesgame object
GuessGame app = new GuessGame();
}
}

The colors aren't changing because your setBackgroundColor always uses Color.black. Change it to:
private void setBackgroundColor(Color color) {
setBackground(color);
}
As for the number always being zero. You do not instantiate the randomNumber field. Add this to your constructor:
randomNumber = new Random().nextInt(1001);
Another problem I noticed was you added a window listener to ensure the program exits when you close the window. This is implemented in JFrame. In the constructor add:
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Instead of using the deprecated method:
mainFrame.show();
use the not deprecated:
mainFrame.setVisible(true);
Furthermore you have a field, which is never queried:
private Color background;
It's best to do the logic before connecting it to the gui. It's a lot easier to test and find the worst bugs.
Refactored code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class GuessGame extends JFrame {
private JTextField userInput;
private JLabel comment = new JLabel("What is your destiny?");
private JLabel comment2 = new JLabel(" ");
private int randomNumber;
public GuessGame() {
super("Guessing Game!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Creates components
JButton guessButton = new JButton("Guess");
JButton quitButton = new JButton("Quit");
JLabel prompt1 = new JLabel("I have a number between 1 and 1000.");
JLabel prompt2 = new JLabel("Can you guess my number? Enter your Guess:");
comment = new JLabel("What is your destiny?");
comment2 = new JLabel(" ");
userInput = new JTextField(5);
//content pane
Container c = getContentPane();
setLayout(new FlowLayout());
//adding component to the pane
c.add(prompt1);
c.add(prompt2);
c.add(userInput);
c.add(comment2);
c.add(guessButton);
c.add(quitButton);
c.add(comment);
guessButton.setMnemonic('G');
quitButton.setMnemonic('Q');
setSize(300, 200);
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
initializeNumber();
//creating the handler
GuessButtonHandler ghandler = new GuessButtonHandler(); //instantiate new object
guessButton.addActionListener(ghandler); // add event listener
QuitButtonHandler qhandler = new QuitButtonHandler();
quitButton.addActionListener(qhandler);
}
private void initializeNumber() {
randomNumber = new Random().nextInt(1000) + 1;
}
class QuitButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
class GuessButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
int getUserInput;
int diff;
int Difference;
try {
getUserInput = Integer.parseInt(userInput.getText().trim());
if (getUserInput == randomNumber) {
JOptionPane.showMessageDialog(null, "CONGRATULATIONS! You got it!!",
"Random Number: " + randomNumber,
JOptionPane.INFORMATION_MESSAGE);
initializeNumber();
return;
}
if (getUserInput > randomNumber) {
comment.setText("Too High. Try a lower number.");
diff = getUserInput - randomNumber;
Difference = Math.abs(diff);
} else {
comment.setText("Too Low. Try a higher number.");
diff = randomNumber - getUserInput;
Difference = Math.abs(diff);
}
if (Difference <= 25) {
comment2.setText("Cold");
GuessGame.this.setBackgroundColor(Color.blue);
}
if (Difference <= 10) {
comment2.setText("Warm");
GuessGame.this.setBackgroundColor(Color.red);
}
} catch (NumberFormatException ex) {
comment.setText("Enter a VALID number!");
}
}
}
private void setBackgroundColor(Color color) {
getContentPane().setBackground(color);
}
public static void main(String args[]) {
//instantiate gueesgame object
GuessGame app = new GuessGame();
}
}

You have more Swing components than you need, and you seem to be adding one set to the frame while manipulating another set. For example, you have two JTextFields, fieldBox and userInput. You add userInput to the frame, but check fieldBox for input in the Guess button handler. Since fieldBox is always empty, the NumberFormatException is caught by your exception handler (which should really just catch NumberFormatException, not Exception), and comment is updated with "Enter a VALID number!". However, just like with the double text area, comment isn't actually added to the frame, prompt1 and prompt2 are, so you can't see the change

I would write your logic without a UI first and test it until it was 100% correct. Just use a command line, text UI at first. Once that's done, put a GUI in front of it. It'll help to isolate your problems: once the text-driven logic is right, you'll know that future problems are due to UI.
It makes your MVC separation cleaner as well.

Related

Color for JFrame not working even though getcontentpane is already added

I am pretty new to Java. This is my class homework. I finished everything except the JFrame color doesn't show. I looked at all the other similar questions. Most of them said to use getContentPane(). The problem is I added that already but it is not showing. Below is my code. I separated it into two parts. The second part has all those JFrame.getContentPane().setBackground(color.**) code. Thank you.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class NumberGame extends JFrame {
private JPanel Content;
private JFrame DisplayFrame;
private JTextField Input;
private JLabel DisplayText, Message;
private int Guess;
private JButton button;
private JButton NewGame;
private int Number;
private int Lowest = 0;
private int Highest = 0;
public void NumberGame () {
Content = new JPanel ();
DisplayFrame = new JFrame ("Welcome");
DisplayFrame.setSize(700, 400);
DisplayFrame.setLayout (new BorderLayout());
DisplayText = new JLabel ("I have a number between 1 and 1000. Can you guess my number?
Enter your first guess.");
Input = new JTextField (20);
Content.add(Input);
Message = new JLabel ("");
button = new JButton ("Submit");
button.addActionListener (new GuessHandler());
NewGame = new JButton ("New Game");
NewGame.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent ae) {
Input.setText("");
Message.setText("");
repaint();
}
} );
DisplayFrame.add(Content);
Content.add(DisplayText);
Content.add(Input);
Content.add(button);
Content.add(NewGame);
Content.add(Message);
theGame();
DisplayFrame.setVisible(true);
}
public void theGame () {
Number = (int) (Math.random() * 1000 +1);
}
public static void main(String[] args) {
NumberGame a = new NumberGame ();
a.NumberGame();
}
Here is the rest of the code that I have problem with.
class GuessHandler implements ActionListener {
#Override
public void actionPerformed (ActionEvent ae) {
Guess = Integer.parseInt(Input.getText());
if(Guess>Number) {
Message.setText("Too high!");
if (Guess < Lowest) {
Lowest = Guess;
DisplayFrame.getContentPane().setBackground(Color.red);
}
else
DisplayFrame.getContentPane().setBackground(Color.blue);
}
else if (Guess < Number) {
Message.setText("Too Low!");
if (Guess > Highest) {
Highest = Guess;
DisplayFrame.getContentPane().setBackground(Color.red);
}
else
DisplayFrame.getContentPane().setBackground(Color.blue);
}
else {
Message.setText("Correct!");
Input.setEditable(false);
Lowest = 0;
Highest = 1000;
}
repaint ();
}
}
}
Content is a JPanel, because JFrame uses a BorderLayout, the panel Content will occupy the entire available space, covering the frames own content pane (don't confuse the two, the are different).
Try changing
DisplayFrame.add(Content);
to
DisplayFrame.setContentPane(Content);
You might like to have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others

Program doesn't change color

I'm trying to write a program where you guess a random generated number (from 1-1000) and the program will tell you if you're getting close or not. The problem I'm having is that I have to have the background change color according to how close you are to the answer. Red is closer, blue is further away. I have the code but I can't figure out why the background isn't working. Is it something to do with the container? Thank you!
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.Random;;
public class GuessGame extends JFrame
{
private JButton newGameButton;
private JButton enterButton;
private JButton exitButton;
private JTextField guessBox;
private JLabel initialTextLabel;
private JLabel enterLabel;
private JLabel userMessageLabel;
private int randomNumber;
private int userGuess;
private int counter = 0;
private int lastGuess = 0;
private Color background;
Container container;
public GuessGame()
{
super("Guessing Game");
newGameButton = new JButton("New Game");
exitButton = new JButton("Exit Game");
enterButton = new JButton("Enter");
guessBox = new JTextField(4);
initialTextLabel = new JLabel("I have a number between 1 and 1000 can you guess my number?");
enterLabel = new JLabel("Please enter your first guess.");
userMessageLabel = new JLabel("");
randomNumber = new Random().nextInt(1000) + 1;
container=getContentPane();
container.setLayout(new FlowLayout());
container.add(initialTextLabel);
container.add(enterLabel);
container.add(guessBox);
container.add(newGameButton);
container.add(enterButton);
container.add(exitButton);
container.add(userMessageLabel);
setSize(400, 150);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
newGameButtonHandler nghandler = new newGameButtonHandler();
newGameButton.addActionListener(nghandler);
ExitButtonHandler exithandler = new ExitButtonHandler();
exitButton.addActionListener(exithandler);
enterButtonHandler enterhandler = new enterButtonHandler();
enterButton.addActionListener(enterhandler);
}
class newGameButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
getContentPane();
background=Color.lightGray;
userMessageLabel.setText("");
randomNumber = new Random().nextInt(1000) + 1;
}
}
class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
class enterButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
userGuess = Integer.parseInt(guessBox.getText());
compareGuess(userGuess, randomNumber);
}
}
public void paint(Graphics g)
{
super.paint(g);
container.setBackground(background);
}
public void compareGuess(int userGuess, int randomNumber)
{
counter++;
if (userGuess == randomNumber)
{
userMessageLabel.setText("You are correct, it took you: " + counter + " tries");
getContentPane();
background=Color.green;
}
else if (userGuess > randomNumber)
{
userMessageLabel.setText("Too high");
}
else if (userGuess < randomNumber)
{
userMessageLabel.setText("Too Low");
}
if (counter > 1)
{
if ((randomNumber - userGuess) > (randomNumber - lastGuess))
{
getContentPane();
background=Color.red;
}
else if ((randomNumber - userGuess) < (randomNumber - lastGuess))
{
getContentPane();
background=Color.blue;
}
else
{
getContentPane();
background=Color.gray;
}
}
lastGuess = userGuess;
}
public static void main(String[] args)
{
GuessGame myGuessGame = new GuessGame();
myGuessGame.setVisible(true);
}
}
You are trying to override paint(Graphics g) function of JFrame. We should not override paint function of Top level component like JFrame.
Use a custom component extending JPanel and override its paintComponent(Graphics g) function and don't forget to call super.paintComponent(g) inside this function.
When any update should be made to the painting of a component, invoke component.repaint() on that component to reflect the changes on the GUI.
Please have a tour to the Official tutorial page: Lesson: Performing Custom Painting
I addition to Sage's comments, you are calling setBackground from within the paint, which is simply going to make another request to paint...again and again and again...
The other problem is, you are changing the background of the frame, not it's content pane.
Instead, get rid of your paint method, you're not doing anything with it...
Instead, when you want to change the color, simply call getContentPane().setBackground(...), for example...
class newGameButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
getContentPane().setBackground(Color.lightGray);
userMessageLabel.setText("");
randomNumber = new Random().nextInt(1000) + 1;
}
}
If that doesn't work, you may need to call getContentPane().repaint()

Nullpointerexception when adding an array of JButtons to a JFrame

I am making a clone of minesweeper with (slightly modified) JButtons. Because there are so many game tiles in minesweeper, I am storing them as an array. When I try and add the buttons to the Frame using a for loop, I get a nullpointerexception on the buttons. The class ButtonObject is extended from the JButton class with just two extra variables and getter/setter methods. What is going wrong?
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class Minesweeper extends JFrame implements ActionListener{
JLabel starttitle;
ButtonObject[] minefield;
JFrame frame;
Random r = new Random();
int rand;
JPanel startscreen;
JPanel gamescreen;
int gamesize;
JButton ten;
JButton tfive;
JButton fifty;
GridLayout layout;
public Minesweeper()
{
frame = new JFrame("Minesweeper");
frame.setSize(500,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);;
startscreen = new JPanel();
startScreen();
}
public void startScreen()
{
ten = new JButton("10 x 10");
tfive = new JButton("25 x 25");
fifty = new JButton("50 x 50");
starttitle = new JLabel("Welcome to minesweeper. Click a game size to begin.");
frame.add(startscreen);
startscreen.add(starttitle);
startscreen.add(ten);
startscreen.add(tfive);
startscreen.add(fifty);
ten.addActionListener(this);
tfive.addActionListener(this);
fifty.addActionListener(this);
}
public void initializeGame()
{
minefield = new ButtonObject[gamesize];
for(int i = 0;i<gamesize;i++)
{
minefield[i]=new ButtonObject();
rand = r.nextInt(5);
if(rand==5)
{
minefield[i].setButtonType(true);//this tile is a mine
}
}
}
public void gameScreen()
{
frame.getContentPane().removeAll();
frame.repaint();
initializeGame();
for(int i = 0;i<minefield.length;i++)
{
gamescreen.add(this.minefield[i]);//EXCEPTION HERE
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==ten)
{
gamesize = 99;
gameScreen();
}
else if(e.getSource()==tfive)
{
gamesize = 624;
gameScreen();
}
else if(e.getSource()==fifty)
{
gamesize = 2499;
gameScreen();
}
else
{
System.out.println("Fatal error");
}
}
public static void main(String[] args)
{
new Minesweeper();
}
}
Well, you never initialize your gamescreen variable, so that's totally normal you get a NullPointerException at this line.

Java displayField refuses to clear

I'm working on a calculator application (which I have simplified downed to make it easier to debug). When the user hits '=' the IMPORTANTINT will change to 1. When the users clicks another button the field is supposed to clear with the if then statement in CalculatorEngine:
if(IMPORTANTINT == 1){
System.out.println("Ran the block of code");
parent.setDisplayValue("");
IMPORTANTINT = 0;
System.out.println(IMPORTANTINT);
}
This is done so the user can view the result and then start a new calculation. The textField doesn't want to clear. Does anyone know why this is? Thanks!
CalculatorEngine.java
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
import javax.swing.JButton;
public class CalculatorEngine implements ActionListener{
Calculator parent;
double firstNum, secondNum;
String symbol;
int IMPORTANTINT = 0;
CalculatorEngine(Calculator parent){
this.parent = parent;
}
public void actionPerformed(ActionEvent e){
JButton clickedButton = (JButton) e.getSource();
String clickedButtonLabel = clickedButton.getText();
String dispFieldText = parent.getDisplayValue();
if(IMPORTANTINT == 1){
System.out.println("Ran the block of code");
parent.setDisplayValue("");
IMPORTANTINT = 0;
System.out.println(IMPORTANTINT);
}
if(clickedButtonLabel == "+"){
firstNum = (Double.parseDouble(parent.getDisplayValue()));
parent.setDisplayValue("");
symbol = clickedButtonLabel;
} else if(clickedButtonLabel == "="){
IMPORTANTINT = 1;
secondNum = Double.parseDouble(parent.getDisplayValue());
double answer = firstNum + secondNum;
parent.setDisplayValue(Double.toString(answer));
} else{
parent.setDisplayValue(dispFieldText + clickedButtonLabel);
}
}
Calculator.java
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.BorderLayout;
public class Calculator {
private JPanel windowContent;
private JPanel p1;
private JPanel sideBar;
private JTextField displayField;
private JButton button8;
private JButton button9;
private JButton buttonEqual;
private JButton buttonPlus;
Calculator(){
windowContent= new JPanel();
BorderLayout bl = new BorderLayout();
windowContent.setLayout(bl);
displayField = new JTextField(30);
windowContent.add("North",displayField);
button8=new JButton("8");
button9=new JButton("9");
buttonEqual=new JButton("=");
buttonPlus = new JButton("+");
p1 = new JPanel();
GridLayout gl =new GridLayout(4,3);
p1.setLayout(gl);
sideBar = new JPanel();
GridLayout gl2 = new GridLayout(5,1);
sideBar.setLayout(gl2);
p1.add(button8);
p1.add(button9);
p1.add(buttonEqual);
sideBar.add(buttonPlus);
windowContent.add("Center", p1);
windowContent.add("East", sideBar);
JFrame frame = new JFrame("Calculator");
frame.setContentPane(windowContent);
frame.pack();
frame.setVisible(true);
CalculatorEngine calcEngine = new CalculatorEngine(this);
button8.addActionListener(calcEngine);
button9.addActionListener(calcEngine);
buttonEqual.addActionListener(calcEngine);
buttonPlus.addActionListener(calcEngine);
}
public void setDisplayValue(String val){
displayField.setText(val);
}
public String getDisplayValue(){
return displayField.getText();
}
public static void main(String[] args)
{
Calculator calc = new Calculator();
}
}
public void setDisplayValue(String val){
SwingUtilities.invokeLater(new Runnable{
#Override
public void run()
{
displayField.setText(val);
}
});
}
You are effectively caching the dispFieldText before entering the IMPORTANTINT if statement block. Therefore the JTextField is being cleared but subsequently then to the cached value in the else block.
if (IMPORTANTINT == 1) {
dispFieldText = ""; // add this
...
}
if (clickedButtonLabel.equals("+")) {
...
} else if (clickedButtonLabel.equals("=")) {
...
} else {
// Field being reset here vvvv
parent.setDisplayValue(dispFieldText + clickedButtonLabel);
}
Make sure to clear the variable. Use String#equals to check String content. The == operator checks Object references.
Aside: Use Java naming conventions, IMPORTANTINT is a modifiable variable so should be importantInt (A boolean typically handles a true/false scenario)

GUI - Changing the color of the JFrame

I'm new in Java and I need your help in implementing a GUI. Below is a Guessing Game code. It works.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class GuessGame extends JFrame {
private JTextField guessTextField;
private JLabel introLabel, guessLabel, clueLabel;
private JButton enterB, playAgainB;
private int randomNumber;
public GuessGame() {
super("Guessing Game!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Creates components
enterB = new JButton("Guess");
playAgainB = new JButton("Quit");
introLabel = new JLabel("I have a number between 1 and 1000.");
guessLabel = new JLabel("Can you guess my number? Please enter your guess:");
clueLabel = new JLabel("");
// comment2 = new JLabel(" ");
guessTextField = new JTextField(5);
//content pane
Container c = getContentPane();
setLayout(new FlowLayout());
//adding component to the pane
c.add(introLabel);
c.add(guessLabel);
c.add(guessTextField);
//c.add(comment2);
c.add(enterB);
c.add(playAgainB);
c.add(clueLabel);
//enterB.setMnemonic('G');
//playAgainB.setMnemonic('Q');
setSize(350, 200);
setLocationRelativeTo(null);
setVisible(true);
//setResizable(false);
initializeNumber();
//creating the handler
GuessButtonHandler ghandler = new GuessButtonHandler(); //instantiate new object
enterB.addActionListener(ghandler); // add event listener
QuitButtonHandler qhandler = new QuitButtonHandler();
playAgainB.addActionListener(qhandler);
}
private void initializeNumber() {
randomNumber = new Random().nextInt(1000) + 1;
System.out.println(randomNumber);
}
class QuitButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
class GuessButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
int getUserInput;
int diff;
int Difference;
try {
getUserInput = Integer.parseInt(guessTextField.getText().trim());
if (getUserInput == randomNumber) {
clueLabel.setText(" Correct!");
}
if (getUserInput > randomNumber) {
clueLabel.setText(" Too High");
} else {
clueLabel.setText(" Too Low");
}
}
catch (NumberFormatException e1) {
clueLabel.setText("Enter a VALID number!");
}
}
}
public static void main(String args[]) {
//instantiate gueesgame object
GuessGame app = new GuessGame();
}
}
However, the color of the window should change into red or blue. Please help me with this code. I'm new in Java and it's syntax. I'd really appreciate your help. Thank you!
You could use:
current = Integer.parseInt(guessTextField.getText().trim());
if (!firstTime) {
if (getUserInput > previous) {
getContentPane().setBackground(Color.red);
} else {
getContentPane().setBackground(Color.blue);
}
}
where firstTime and previous are class member variables.
Don't forget to assign previous if the getUserInput == randomNumber is not met.
Update:
You are setting the background blue twice:
if (getUserInput < randomNumber) {
clueLabel.setText("Too Low");
getContentPane().setBackground(Color.blue); <------ remove this extra call
previous = getUserInput;
}
A code is better than thousand words.....
if (current_Input > previous) {
c.setBackground(Color.red);
} else {
c.setBackground(Color.blue);
}

Categories