
Java Program - GUI Number Guessing
Look at the code, notice that the actionPerformed method is not complete. It just contains code that will print to the console when buttons are pressed. Make the following modifications to the code.
- When the Higher button is pressed invoke this.guesser.higher(), and then put the new guess into the this.guessField
- When the Lower button is pressed invoke this.guesser.lower() and then put the new guess into the this.guessField
- When the Reset button is pressed, invoke this.guesser.reset() and then put the new guess into the ghis.guessField
- When the Correct button is pressed, exit the app using System.exit(0).
- Wrap the invocation of lower() and higher() in try catch blocks that catch NumberGuesserIllegalStateExceptions. Show a JOptionPane that alerts the user that you are onto their schemes.
- Change the guessing
algorithm from random-guess to binary search. You can do this by changing the object created for the guesser to a plain old NumberGuesser. It should just be a single line change.
Main.java
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
class Main extends JFrame implements ActionListener {
private JTextField guessField;
private JButton lowerButton;
private JButton higherButton;
private JButton correctButton;
private JButton resetButton;
private NumberGuesser guesser;
public Main() {
// Used to specify GUI component layout
GridBagConstraints positionConst = null;
// Set frame's title
setTitle("Number Guesser");
// Create the Number Guesser
this.guesser = new RandomNumberGuesser(1, 100);
// Create the display for the guess
JLabel guessLabel = new JLabel("Current Guess: ");
this.guessField = new JTextField(15);
this.guessField.setEditable(false);
// Create the four button objects
this.lowerButton = new JButton("Lower");
this.higherButton = new JButton("Higher");
this.correctButton = new JButton("Correct");
this.resetButton = new JButton("Reset");
// Use "this" class to handle button presses
this.lowerButton.addActionListener(this);
this.higherButton.addActionListener(this);
this.correctButton.addActionListener(this);
this.resetButton.addActionListener(this);
// Use a GridBagLayout
setLayout(new GridBagLayout());
positionConst = new GridBagConstraints();
// 10 pixels vert, 5 horizontal around components
positionConst.insets = new Insets(10, 5, 10, 5);
// Add component using the specified constraints
positionConst.gridx = 0;
positionConst.gridy = 0;
add(guessLabel, positionConst);
positionConst.gridx = 1;
positionConst.gridy = 0;
add(this.guessField, positionConst);
positionConst.gridx = 2;
positionConst.gridy = 0;
add(this.resetButton, positionConst);
positionConst.gridx = 0;
positionConst.gridy = 2;
add(this.lowerButton, positionConst);
positionConst.gridx = 1;
positionConst.gridy = 2;
add(this.higherButton, positionConst);
positionConst.gridx = 2;
positionConst.gridy = 2;
add(this.correctButton, positionConst);
}
/*
* Method is automatically called when a button is pressed
*
* It needs some work. The logic here doesn't play a guessing game. It just
* provides some examples that you can use.
*
* inside the action performed method you have access to this class's
* member fields. So you can access each of these:
* - this.lowerButton
* - this.higherButton
* - this.resetButton
* - this.cancelButton
* - this.numberGuesser
*/
@Override
public void actionPerformed(ActionEvent event) {
// A reference to the button that was pressed
Object buttonPressed = event.getSource();
// Here is how to check to see if the button is
// the "lower" button. Use can use similar if
// statements to check for the other buttons
if (buttonPressed == this.lowerButton) {
// printint to the console is just for debugging when you
// are writing a GUI. The user won't see it.
System.out.println("Lower");
}
// Here is a similar if. This one looks for the "reset"
// button. It displays a JOptionPane.
if (buttonPressed == this.resetButton) {
// This is how you can show a JOptionPane. You should use this
// to let the user know when you catch them cheating.
JOptionPane.showInternalMessageDialog(
null,
"Cheating!",
"Notice", JOptionPane.INFORMATION_MESSAGE);
}
}
public static void main(String[] args) {
Main myFrame = new Main();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.pack();
myFrame.setVisible(true);
}
}

Trending nowThis is a popular solution!
Step by stepSolved in 3 steps

- Write a toString method. The text representation of a receipt should include: the text representation of the Store the number of items the total money spent the receipt IDarrow_forwardAssume that we have a Button object named btnPrint, and a method named print(). Write a "STATEMENT" that will cause the button to trigger a call to the print method. JUST NEED THE STATMENTarrow_forwardGUI calculator in python - The user enters two integers into the text fields. - When the Add button is pressed, the sum of values in the text fields are shown after the Equals: as a label. - The Clear button clears the values in the text fields and the result of the previous calculation. The cleared values can be blank or zero. - The Quit button closes the GUI window.arrow_forward
- Look through the method header below, then, as an example, write a call to the method. an internal void ShowValue()arrow_forwardNeed help with the following: Adding comments to help explain the purpose of methods, classes, constructors, etc. to help improve understanding. Implementing enhanced for loop (for each loop) to iterate over the numbers array in the calculateProduct method. Creating a separate class for the UI and a separate class for the calculator logic. Lastly, creating a constant instead of hard coding the number "5" in multiple places. Thank you for any input/knowldge you can transfer to me, I appreciate it. Source Code: package implementingRecursion; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class RecursiveProductCalculator extends JFrame { private JTextField[] numberFields; private JButton calculateButton; private JLabel resultLabel; public RecursiveProductCalculator() { setTitle("Recursive Product Calculator"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new GridLayout(7, 1)); numberFields = new…arrow_forwardMethods with an empty parameter list and do not return a value: [Questions 1-8 required] You invoke a method by its name followed by a pair of brackets and the usual semi-colon Write a method called DisplayPersonalInfo(). This method will display your name, school, program and your favorite course. Call the DisplayPersonalInfo() method from your program Main() method Write a method called CalculateTuition(). This method will prompt the user for the number of courses that she is currently taking and then calculate and display the tuition cost. (cost = number of course * 569.99). Call the CalculateTuition() method two times from the same Main() method as in question 1. Write a method call CalculateAreaOfCircle(). This method will prompt the user for the radius of a circle and then calculate and display the area.[A = πr2].Call the CalculateAreaOfCircle() method twice from the same Main() method as in question 1. Use Math.Pi for the value of π Write a method call…arrow_forward
- java-Find the area of circle using method... Write an application that prompts the user for the radius of a circle and uses a method called circleArea to find tarea of the circle. method method should return the computed area to the caller method.arrow_forwardInstructor note: This lab is part of the assignment for this chapter. HINT: 1). The decision means how many times to flip the coin. 2). Use a random integer variable to indicate the head or tail in each toss. Java Define a method named coinFlip that takes a Random object and returns "Heads" or "Tails" according to a random value 1 or 0. Assume the value 1 represents "Heads" and 0 represents "Tails". Then, write a main program that reads the desired number of coin flips as an input, calls method coinFlip() repeatedly according to the number of coin flips, and outputs the results. Assume the input is a value greater than 0. Ex: If the random object is created with a seed value of 2 and the input is: 3 the output is: Heads Tails Heads Note: For testing purposes, a Random object is created in the main() method using a pseudo-random number generator with a fixed seed value. The program uses a seed value of 2 during development, but when submitted, a different seed value may be used…arrow_forwardWrite the following two methods: computeDiameter: This method accepts the radius (r) of a circle, and returns its diameter (2*r; radius = 7.5). Declare all variables used here & initialize radius: Show method call: Write method code here: displayData: This method accepts two arguments: radius & diameter. The output should have appropriate messages on the screen. Show method call: Write method code here:arrow_forward
- Add a toString method to your Account class. For the purposes of this assignment, please use the toString display the following: This account contains $x. You have earned $y in the last month. where x is the account balance (please don't format the decimals) and y is the monthly interest earned, obtained from the getMonthlyInterest method. Compile and test in a driver by creating and printing an Account object. Add an equals method to your Account class. Two Account objects are equal if their balance and annualInterestRates are equal. Compile and test in your driver by creating 2 Account objects to see if they are equal.arrow_forwardPythonarrow_forwardAlert dont submit AI generated answer. in Java.arrow_forward
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education





