Hello Friends, in this tutorial, we will learn how to create a Number Guessing Game in Java Swing with Source Code. In the previous tutorials, we have already learned how to create a Login form in Java Swing and a Calculator application using Java Swing. Now in this tutorial, we will create a GUI Number Guessing Game in Java step by step, and the source code of the project will be given at the end of the tutorial.
In short, What will happen in this GUI Number Guessing Game in Java Swing is the generation of a random number ranging between 0 to 100. The objective for the Player is to guess the correct number. If the Player successfully guesses the right number, a message dialog box will appear to declare their victory. However, if the Player’s guess is incorrect, a hint will be provided indicating whether the guessed number is low or high. This allows the Player to make subsequent guesses.
Additionally, there will be an option to “Give Up” the Game if the Player decides not to continue guessing and wishes to reveal the number. Furthermore, a “New game” option will be available, enabling the Player to start a fresh game.
The bottom section of the Game will feature statistics indicating the number of attempts made by the Player, the highest score achieved, and the time taken by the Player.
Prerequisite
In order to build our GUI Number Guessing Game using Java Swing, it is essential to possess a solid understanding of the basic components of Java Swing. Below, I have listed all the necessary topics that we need to create the Number Guessing Game in Java Swing.
- JFrame Java Tutorial for Beginners
- JLabel Tutorial
- JTextField Tutorial
- JButton Tutorial
- JPanel Tutorial
- Java Button Click Event
- Key Event in Java
If you have finished covering the topics mentioned earlier, we can proceed with our tutorial on building a Number Guessing Game in Java Swing, including the source code.
Number Guessing Game in Java Swing/ with GUI
Importing Packages
Step 1
- In the first step, we need to import all the essential packages in our program so that we will be able to use all the interfaces and classes that we will use in our program.
1 2 3 4 5 |
import javax.swing.*; import javax.swing.text.*; import java.awt.*; import java.awt.event.*; import java.util.Random; |
Creating a Class GuessingGame.java
Step 2
- In this step, we will create a class GuessingGame.java that will implement both ActionListner and KeyListener interface.
- We will implement the ActionListener and KeyListener interface because we will do some button click events and key-typed events in our program. For this, we have already imported the necessary package in our class, which is java.awt.event.*;.
- ActionListener contains only one method actionPerformed(ActionEvent e), and KeyListener contains three methods keyPressed(KeyEvent e), keyReleased(KeyEvent e) and keyTyped(KeyEvent e), So if we are implementing these interfaces in our class, then we must have to override their methods into that class.
- Next, we will create the main method (public static void main(String[] args) of our class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
//importing necessary packages import javax.swing.*; import javax.swing.text.*; import java.awt.*; import java.awt.event.*; import java.util.Random; //Creating class and implementing intefaces public class GuessingGameJava implements ActionListener, KeyListener { @Override public void keyPressed(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } @Override public void actionPerformed(ActionEvent e) { } //Creating main method public static void main(String[] args) { } } |
Creating GUI for Number Guessing Game in Java
Step 3
- In this step, we will prepare the GUI of our Number Guessing Game.
- For this, we will create the constructor of our class.
- Now, create the object of one JFrame and two JPanel.
- Next, we will set the properties of the JFrame and Jpanel using their objects.
- Next, we will add the Jpanels to the JFrame.
- Next, we will create the object of our class inside the main method.
- Below is the code, and the explanations are given in the comments.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
//importing necessary packages import javax.swing.*; import javax.swing.text.*; import java.awt.*; import java.awt.event.*; import java.util.Random; //Creating class and implementing interfaces public class GuessingGameJava implements ActionListener, KeyListener { //Creating objects of JFrame and JPanel JFrame frame; JPanel panel1; JPanel panel2; //Creating Constructor GuessingGameJava(){ //Setting properties of JFrame frame =new JFrame(); frame.setTitle("Number Guessing Game"); frame.getContentPane().setLayout(null); //Setting Properties of JPanel one and two panel1 =new JPanel(); panel1.setLayout(null); panel1.setBackground(new Color(128,0,128)); panel1.setBounds(0,0,350,500); panel2=new JPanel(); panel2.setLayout(null); panel2.setBackground(new Color(255,150,134)); panel2.setBounds(351,370,350,100); //Adding panels to JFrame frame.add(panel1); frame.add(panel2); //Setting properties of JFrame frame.getContentPane().setBackground(Color.white); frame.setSize(700,500); frame.setLocationRelativeTo(null); frame.setResizable(false); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } @Override public void keyPressed(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } @Override public void actionPerformed(ActionEvent e) { } //Creating main method public static void main(String[] args) { //Creating object of the class GuessingGameJava guessingGameJava=new GuessingGameJava(); } } |
- Now run your program.
- As you can see in the above figure, we have successfully created the GUI for our Number Guessing Game in Java Swing.
- In the next step, we will add components to it.
Adding Components
Step 4
- In this step, we will add all the desired components into GUI to create our number guessing game.
- For this, we will first create the objects of the components and then set some of their properties using their respective methods, and then lastly, we will add them to the container.
- We will create,
- 9 JLabel in which,
- 8 JLabel will be used to display the text, and 1 JLabel will be used to display the image using the ImageIcon class. The image should be within the project folder. I will provide the image with the source code, or you can either choose your particular image as per your requirements.
- 4 JTextField in which,
- 1 JTextField will be used to input the guessed number, and the other 3 JTextFields will be used to display the number of attempts made by the player, the highest score, and the time taken by the player, respectively.
- We will also restrict the character limit of the guessing JTextField to 2 characters using the PlainDocument class so that only two characters can be entered by the player.
- 4 JButton in which,
- The first JButton will be used to guess the number, the second JButton will allow the player to give up and reveal the number if they choose not to guess, and the third JButton will be used to start a new game.
- 9 JLabel in which,
- The code is given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 |
//importing necessary packages import javax.swing.*; import javax.swing.text.*; import java.awt.*; import java.awt.event.*; import java.util.Random; //Creating class and implementing interfaces public class GuessingGameJava implements ActionListener, KeyListener { //Creating objects of JFrame and JPanel JFrame frame; JPanel panel1; JPanel panel2; //Creating objects of components JLabel textLabel1; JLabel textLabel2; JLabel textLabel3; JLabel textLabel4; JLabel textLabel5; JLabel imageLabel; JTextField guessTextField; JButton guessButton; JButton giveUpButton; JButton newGameButton; JLabel attemptsLabel; JLabel highestScoreLabel; JLabel timeTakenLabel; JTextField attemptsField; JTextField highestScoreField; JTextField timeTakenField; GuessingGameJava(){ //Setting properties of JFrame frame =new JFrame(); frame.setTitle("Number Guessing Game"); frame.getContentPane().setLayout(null); //Setting Properties of JPanel one and two panel1 =new JPanel(); panel1.setLayout(null); panel1.setBackground(new Color(128,0,128)); panel1.setBounds(0,0,350,500); panel2=new JPanel(); panel2.setLayout(null); panel2.setBackground(new Color(255,150,134)); panel2.setBounds(351,370,350,100); //Setting properties of the components textLabel1 =new JLabel(); textLabel1.setText("Number"); textLabel1.setFont(new Font("Comic Sans MS", Font.BOLD, 50)); textLabel1.setForeground(Color.WHITE); textLabel1.setBounds(78,20,300,100); textLabel2 =new JLabel(); textLabel2.setText("Guessing Game"); textLabel2.setFont(new Font("Comic Sans MS", Font.PLAIN, 35)); textLabel2.setForeground(Color.WHITE); textLabel2.setBounds(48,80,300,100); textLabel3 =new JLabel(); textLabel3.setText("Guess the Number"); textLabel3.setFont(new Font("Comic Sans MS", Font.BOLD, 30)); textLabel3.setForeground(new Color(128,0,128)); textLabel3.setBounds(390,20,300,100); textLabel4 =new JLabel(); textLabel4.setText("( B/W 0 to 100 )"); textLabel4.setFont(new Font("Comic Sans MS", Font.PLAIN, 20)); textLabel4.setForeground(Color.blue); textLabel4.setBounds(440,80,300,100); guessTextField =new JTextField(); guessTextField.setDocument(new JTextFieldCharLimit(2)); guessTextField.setHorizontalAlignment(SwingConstants.CENTER); guessTextField.setBounds(440,170,145,30); guessTextField.setFont(new Font("Comic Sans MS",Font.BOLD,20)); guessTextField.setBackground(new Color(232,232,232)); guessTextField.setBorder(BorderFactory.createBevelBorder(1)); guessButton = new JButton(); guessButton.setText("Guess"); guessButton.setFont(new Font("Comic Sans MS",Font.BOLD,20)); guessButton.setBounds(450,215,125,35); guessButton.setFocusable(false); guessButton.setBackground(new Color(128,0,128)); guessButton.setForeground(Color.white); textLabel5 =new JLabel(); textLabel5.setText(""); textLabel5.setFont(new Font("Comic Sans MS", Font.PLAIN, 18)); textLabel5.setForeground(Color.red); textLabel5.setHorizontalAlignment(SwingConstants.CENTER); textLabel5.setBounds(420,220,180,100); giveUpButton = new JButton(); giveUpButton.setText("Give UP!"); giveUpButton.setFont(new Font("Comic Sans MS",Font.BOLD,17)); giveUpButton.setBounds(390,310,125,35); giveUpButton.setFocusable(false); giveUpButton.setBackground(new Color(128,0,128)); giveUpButton.setForeground(Color.white); newGameButton = new JButton(); newGameButton.setText("New Game"); newGameButton.setFont(new Font("Comic Sans MS",Font.BOLD,17)); newGameButton.setBounds(530,310,125,35); newGameButton.setFocusable(false); newGameButton.setBackground(new Color(128,0,128)); newGameButton.setForeground(Color.white); attemptsLabel=new JLabel(); attemptsLabel.setText("Attempts Made"); attemptsLabel.setFont(new Font("Comic Sans MS",Font.BOLD,15)); attemptsLabel.setBounds(10,5,125,35); attemptsLabel.setForeground(Color.black); highestScoreLabel=new JLabel(); highestScoreLabel.setText("Highest Score"); highestScoreLabel.setFont(new Font("Comic Sans MS",Font.BOLD,15)); highestScoreLabel.setBounds(10,30,125,35); highestScoreLabel.setForeground(Color.black); timeTakenLabel=new JLabel(); timeTakenLabel.setText("Time Taken (MM:SS)"); timeTakenLabel.setFont(new Font("Comic Sans MS",Font.BOLD,15)); timeTakenLabel.setBounds(10,55,160,35); timeTakenLabel.setForeground(Color.black); attemptsField=new JTextField(); attemptsField.setEditable(false); attemptsField.setBounds(230,14,70,15); attemptsField.setHorizontalAlignment(SwingConstants.CENTER); attemptsField.setFont(new Font("Comic Sans MS",Font.BOLD,13)); attemptsField.setBorder(BorderFactory.createBevelBorder(1)); highestScoreField=new JTextField(); highestScoreField.setEditable(false); highestScoreField.setText(""); highestScoreField.setBounds(230,39,70,15); highestScoreField.setHorizontalAlignment(SwingConstants.CENTER); highestScoreField.setFont(new Font("Comic Sans MS",Font.BOLD,13)); highestScoreField.setBorder(BorderFactory.createBevelBorder(1)); timeTakenField=new JTextField(); timeTakenField.setEditable(false); timeTakenField.setBounds(230,64,70,15); timeTakenField.setHorizontalAlignment(SwingConstants.CENTER); timeTakenField.setFont(new Font("Comic Sans MS",Font.BOLD,13)); timeTakenField.setBorder(BorderFactory.createBevelBorder(1)); ImageIcon icon=new ImageIcon("Guessing Game.png"); imageLabel=new JLabel(icon); imageLabel.setBounds(70,200,icon.getIconWidth(),icon.getIconHeight()); //Adding panels to JFrame frame.add(panel1); frame.add(panel2); //Adding components to the container panel1.add(textLabel1); panel1.add(textLabel2); panel2.add(attemptsLabel); panel2.add(highestScoreLabel); panel2.add(timeTakenLabel); panel2.add(attemptsField); panel2.add(highestScoreField); panel2.add(timeTakenField); frame.add(textLabel3); frame.add(textLabel4); frame.add(textLabel5); frame.add(guessTextField); frame.add(guessButton); frame.add(giveUpButton); frame.add(newGameButton); panel1.add(imageLabel); //Setting properties of JFrame frame.getContentPane().setBackground(Color.white); frame.setSize(700,500); frame.setLocationRelativeTo(null); frame.setResizable(false); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } @Override public void keyPressed(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } @Override public void actionPerformed(ActionEvent e) { } //Creating main method public static void main(String[] args) { //Creating object of the class GuessingGameJava guessingGameJava=new GuessingGameJava(); } } //Restricting JTextField Character limits using PlainDocument class class JTextFieldCharLimit extends PlainDocument { int limit; public JTextFieldCharLimit(int limitation){ this.limit=limitation; } public void insertString(int offset, String str, AttributeSet set)throws BadLocationException { if(str==null){ return; }else if(getLength() + str.length() <=limit){ super.insertString(offset, str, set); } else if(getLength() + str.length() >limit){ Toolkit.getDefaultToolkit().beep(); } } } |
- Now run your program.
- As you can see in the above figure, we have successfully added the components to the container.
- In the following step, we need to implement the necessary functionalities for our JButtons and JTextField so that when the buttons are clicked and text is entered into the JTextField, corresponding actions are performed.
Adding Event Handling to JButtons and JTextField
Step 5
- To add event handling to our JButtons and JTextField, we first have to register(add) ActionListener to JButtons and KeyListener to JTextField.
- For JButtons, we will call the addActionListener() method using the object of the desired component. The parameter of the addActionListener is the object of that class in which the ActionListener interface is implemented, and since we are in the same class so we will pass this as argument.
- For JTextField, we will call the addKeyListener() method using the object of the desired component. The parameter of the addKeyListener is the object of that class in which the ActionListener interface is implemented, and since we are in the same class so we will pass this as argument.
- By registering the JButtons, the actionPerformed() will be called whenever we click on any of the registered JButtons.
- By registering the JTextField to KeyListener, three methods will be called whenever we input any text into the JTextField, which are,
- keyTyped(KeyEvent e)
- keyPressed(KeyEvent e)
- keyReleased(KeyEvent e)
- Code is given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 |
//importing necessary packages import javax.swing.*; import javax.swing.text.*; import java.awt.*; import java.awt.event.*; import java.util.Random; //Creating class and implementing interfaces public class GuessingGameJava implements ActionListener, KeyListener { //Creating objects of JFrame and JPanel JFrame frame; JPanel panel1; JPanel panel2; //Creating objects of components JLabel textLabel1; JLabel textLabel2; JLabel textLabel3; JLabel textLabel4; JLabel textLabel5; JLabel imageLabel; JTextField guessTextField; JButton guessButton; JButton giveUpButton; JButton newGameButton; JLabel attemptsLabel; JLabel highestScoreLabel; JLabel timeTakenLabel; JTextField attemptsField; JTextField highestScoreField; JTextField timeTakenField; GuessingGameJava(){ //Setting properties of JFrame frame =new JFrame(); frame.setTitle("Number Guessing Game"); frame.getContentPane().setLayout(null); //Setting Properties of JPanel one and two panel1 =new JPanel(); panel1.setLayout(null); panel1.setBackground(new Color(128,0,128)); panel1.setBounds(0,0,350,500); panel2=new JPanel(); panel2.setLayout(null); panel2.setBackground(new Color(255,150,134)); panel2.setBounds(351,370,350,100); //Setting properties of the components textLabel1 =new JLabel(); textLabel1.setText("Number"); textLabel1.setFont(new Font("Comic Sans MS", Font.BOLD, 50)); textLabel1.setForeground(Color.WHITE); textLabel1.setBounds(78,20,300,100); textLabel2 =new JLabel(); textLabel2.setText("Guessing Game"); textLabel2.setFont(new Font("Comic Sans MS", Font.PLAIN, 35)); textLabel2.setForeground(Color.WHITE); textLabel2.setBounds(48,80,300,100); textLabel3 =new JLabel(); textLabel3.setText("Guess the Number"); textLabel3.setFont(new Font("Comic Sans MS", Font.BOLD, 30)); textLabel3.setForeground(new Color(128,0,128)); textLabel3.setBounds(390,20,300,100); textLabel4 =new JLabel(); textLabel4.setText("( B/W 0 to 100 )"); textLabel4.setFont(new Font("Comic Sans MS", Font.PLAIN, 20)); textLabel4.setForeground(Color.blue); textLabel4.setBounds(440,80,300,100); guessTextField =new JTextField(); guessTextField.setDocument(new JTextFieldCharLimit(2)); guessTextField.setHorizontalAlignment(SwingConstants.CENTER); guessTextField.setBounds(440,170,145,30); guessTextField.setFont(new Font("Comic Sans MS",Font.BOLD,20)); guessTextField.setBackground(new Color(232,232,232)); guessTextField.setBorder(BorderFactory.createBevelBorder(1)); guessButton = new JButton(); guessButton.setText("Guess"); guessButton.setFont(new Font("Comic Sans MS",Font.BOLD,20)); guessButton.setBounds(450,215,125,35); guessButton.setFocusable(false); guessButton.setBackground(new Color(128,0,128)); guessButton.setForeground(Color.white); textLabel5 =new JLabel(); textLabel5.setText(""); textLabel5.setFont(new Font("Comic Sans MS", Font.PLAIN, 18)); textLabel5.setForeground(Color.red); textLabel5.setHorizontalAlignment(SwingConstants.CENTER); textLabel5.setBounds(420,220,180,100); giveUpButton = new JButton(); giveUpButton.setText("Give UP!"); giveUpButton.setFont(new Font("Comic Sans MS",Font.BOLD,17)); giveUpButton.setBounds(390,310,125,35); giveUpButton.setFocusable(false); giveUpButton.setBackground(new Color(128,0,128)); giveUpButton.setForeground(Color.white); newGameButton = new JButton(); newGameButton.setText("New Game"); newGameButton.setFont(new Font("Comic Sans MS",Font.BOLD,17)); newGameButton.setBounds(530,310,125,35); newGameButton.setFocusable(false); newGameButton.setBackground(new Color(128,0,128)); newGameButton.setForeground(Color.white); attemptsLabel=new JLabel(); attemptsLabel.setText("Attempts Made"); attemptsLabel.setFont(new Font("Comic Sans MS",Font.BOLD,15)); attemptsLabel.setBounds(10,5,125,35); attemptsLabel.setForeground(Color.black); highestScoreLabel=new JLabel(); highestScoreLabel.setText("Highest Score"); highestScoreLabel.setFont(new Font("Comic Sans MS",Font.BOLD,15)); highestScoreLabel.setBounds(10,30,125,35); highestScoreLabel.setForeground(Color.black); timeTakenLabel=new JLabel(); timeTakenLabel.setText("Time Taken (MM:SS)"); timeTakenLabel.setFont(new Font("Comic Sans MS",Font.BOLD,15)); timeTakenLabel.setBounds(10,55,160,35); timeTakenLabel.setForeground(Color.black); attemptsField=new JTextField(); attemptsField.setEditable(false); attemptsField.setBounds(230,14,70,15); attemptsField.setHorizontalAlignment(SwingConstants.CENTER); attemptsField.setFont(new Font("Comic Sans MS",Font.BOLD,13)); attemptsField.setBorder(BorderFactory.createBevelBorder(1)); highestScoreField=new JTextField(); highestScoreField.setEditable(false); highestScoreField.setText(""); highestScoreField.setBounds(230,39,70,15); highestScoreField.setHorizontalAlignment(SwingConstants.CENTER); highestScoreField.setFont(new Font("Comic Sans MS",Font.BOLD,13)); highestScoreField.setBorder(BorderFactory.createBevelBorder(1)); timeTakenField=new JTextField(); timeTakenField.setEditable(false); timeTakenField.setBounds(230,64,70,15); timeTakenField.setHorizontalAlignment(SwingConstants.CENTER); timeTakenField.setFont(new Font("Comic Sans MS",Font.BOLD,13)); timeTakenField.setBorder(BorderFactory.createBevelBorder(1)); ImageIcon icon=new ImageIcon("Guessing Game.png"); imageLabel=new JLabel(icon); imageLabel.setBounds(70,200,icon.getIconWidth(),icon.getIconHeight()); //Adding Action Listener to JButtons guessButton.addActionListener(this); giveUpButton.addActionListener(this); newGameButton.addActionListener(this); //Adding Key Listener to JTextField guessTextField.addKeyListener(this); //Adding panels to JFrame frame.add(panel1); frame.add(panel2); //Adding components to the container panel1.add(textLabel1); panel1.add(textLabel2); panel2.add(attemptsLabel); panel2.add(highestScoreLabel); panel2.add(timeTakenLabel); panel2.add(attemptsField); panel2.add(highestScoreField); panel2.add(timeTakenField); frame.add(textLabel3); frame.add(textLabel4); frame.add(textLabel5); frame.add(guessTextField); frame.add(guessButton); frame.add(giveUpButton); frame.add(newGameButton); panel1.add(imageLabel); //Setting properties of JFrame frame.getContentPane().setBackground(Color.white); frame.setSize(700,500); frame.setLocationRelativeTo(null); frame.setResizable(false); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } @Override public void keyPressed(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } @Override public void actionPerformed(ActionEvent e) { } //Creating main method public static void main(String[] args) { //Creating object of the class GuessingGameJava guessingGameJava=new GuessingGameJava(); } } //Restricting JTextField Character limits using PlainDocument class class JTextFieldCharLimit extends PlainDocument { int limit; public JTextFieldCharLimit(int limitation){ this.limit=limitation; } public void insertString(int offset, String str, AttributeSet set)throws BadLocationException { if(str==null){ return; }else if(getLength() + str.length() <=limit){ super.insertString(offset, str, set); } else if(getLength() + str.length() >limit){ Toolkit.getDefaultToolkit().beep(); } } } |
Implementing Game Logic
Step 6
Now we want that,
- Upon executing the program, a random number within the range between 0 to 100 should be generated. To accomplish this, we will use the Random class in Java.
- Whenever the player enters the number to be guessed in the JTextField, only numerical input should be permitted, and alphabets or other characters should not be accepted. For this, we will code the desired code inside the keyTyped(KeyEvent e) method.
- The desired actions that we want in response whenever we click on the Jbuttons will be coded inside the actionPerformed(ActionEvent e) method.
- Upon clicking the Guess Button,
- If the guess text field is empty, the message dialog box should be displayed with the message “Invalid Input.” For the message dialog box, we will use the showMessageDialog() method of JOptionPane class.
- If the guessed number matches the random number generated by the program, a victory message should be displayed in the message dialog box.
- If the guessed number is low, then the hint should be displayed to the player that “try again this guessed number is low.”
- If the guessed number is high, then the hint should be displayed to the player that “try again this guessed number is high.”
- Counter variables will also be created to store the values of attempts made by the player and the highest score of the player.
- The highest score will be determined based on the following logic: if the player is playing for the first time, it will be equal to the number of attempts made to guess the correct number. However, if the player starts a new game without exiting the program, the highest score will be the lowest number of attempts made across all games to reach the target.
- The player will also be presented with a timer that begins upon running the program and functions as a stopwatch, showcasing the elapsed time.
- Upon clicking the Give Up button,
- The timer should be stopped, and the correct number should be revealed to the player through the message dialog box.
- Upon clicking the New Game button,
- A new Game should be opened with timer starting from 0 and the program generating a new random number so the player can guess again.
- The final code of our project, Number Guessing Game in Java Swing, is given below with explanations in the comments.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 |
//importing necessary packages import javax.swing.*; import javax.swing.text.*; import java.awt.*; import java.awt.event.*; import java.util.Random; //Creating class and implementing interfaces public class GuessingGameJava implements ActionListener, KeyListener { //Crating Object of UIManager class to manage the look and feel UIManager UI=new UIManager(); //Creating objects of JFrame and JPanel JFrame frame; JPanel panel1; JPanel panel2; //Creating objects of components JLabel textLabel1; JLabel textLabel2; JLabel textLabel3; JLabel textLabel4; JLabel textLabel5; JLabel imageLabel; JTextField guessTextField; JButton guessButton; JButton giveUpButton; JButton newGameButton; JLabel attemptsLabel; JLabel highestScoreLabel; JLabel timeTakenLabel; JTextField attemptsField; JTextField highestScoreField; JTextField timeTakenField; //Creating object of Timer class Timer timer; //Creating object of Random class Random random=new Random(); int randomNumber=random.nextInt(100)+1; //declaring and initializing variables int attemptCount =0; int scoreCount=0; int elapsedTime=0; int minutes=0; int seconds=0; int temp=0; String second_string=String.format("%02d",seconds); String minute_string=String.format("%02d",minutes); GuessingGameJava(){ //Managing look and feel of JOptionPane UI.put("OptionPane.background",new Color(1,16,247)); UI.put("Panel.background", new Color(1,16,247)); UI.put("OptionPane.messageForeground", Color.white); UI.put("OptionPane.messageFont",new Font("Comic Sans MS",Font.BOLD,13)); //Setting properties of JFrame frame =new JFrame(); frame.setTitle("Number Guessing Game"); frame.getContentPane().setLayout(null); //Setting Properties of JPanel one and two panel1 =new JPanel(); panel1.setLayout(null); panel1.setBackground(new Color(128,0,128)); panel1.setBounds(0,0,350,500); panel2=new JPanel(); panel2.setLayout(null); panel2.setBackground(new Color(255,150,134)); panel2.setBounds(351,370,350,100); //Setting properties of the components textLabel1 =new JLabel(); textLabel1.setText("Number"); textLabel1.setFont(new Font("Comic Sans MS", Font.BOLD, 50)); textLabel1.setForeground(Color.WHITE); textLabel1.setBounds(78,20,300,100); textLabel2 =new JLabel(); textLabel2.setText("Guessing Game"); textLabel2.setFont(new Font("Comic Sans MS", Font.PLAIN, 35)); textLabel2.setForeground(Color.WHITE); textLabel2.setBounds(48,80,300,100); textLabel3 =new JLabel(); textLabel3.setText("Guess the Number"); textLabel3.setFont(new Font("Comic Sans MS", Font.BOLD, 30)); textLabel3.setForeground(new Color(128,0,128)); textLabel3.setBounds(390,20,300,100); textLabel4 =new JLabel(); textLabel4.setText("( B/W 0 to 100 )"); textLabel4.setFont(new Font("Comic Sans MS", Font.PLAIN, 20)); textLabel4.setForeground(Color.blue); textLabel4.setBounds(440,80,300,100); guessTextField =new JTextField(); guessTextField.setDocument(new JTextFieldCharLimit(2)); guessTextField.setHorizontalAlignment(SwingConstants.CENTER); guessTextField.setBounds(440,170,145,30); guessTextField.setFont(new Font("Comic Sans MS",Font.BOLD,20)); guessTextField.setBackground(new Color(232,232,232)); guessTextField.setBorder(BorderFactory.createBevelBorder(1)); guessButton = new JButton(); guessButton.setText("Guess"); guessButton.setFont(new Font("Comic Sans MS",Font.BOLD,20)); guessButton.setBounds(450,215,125,35); guessButton.setFocusable(false); guessButton.setBackground(new Color(128,0,128)); guessButton.setForeground(Color.white); textLabel5 =new JLabel(); textLabel5.setText(""); textLabel5.setFont(new Font("Comic Sans MS", Font.PLAIN, 18)); textLabel5.setForeground(Color.red); textLabel5.setHorizontalAlignment(SwingConstants.CENTER); textLabel5.setBounds(420,220,180,100); giveUpButton = new JButton(); giveUpButton.setText("Give UP!"); giveUpButton.setFont(new Font("Comic Sans MS",Font.BOLD,17)); giveUpButton.setBounds(390,310,125,35); giveUpButton.setFocusable(false); giveUpButton.setBackground(new Color(128,0,128)); giveUpButton.setForeground(Color.white); newGameButton = new JButton(); newGameButton.setText("New Game"); newGameButton.setFont(new Font("Comic Sans MS",Font.BOLD,17)); newGameButton.setBounds(530,310,125,35); newGameButton.setFocusable(false); newGameButton.setBackground(new Color(128,0,128)); newGameButton.setForeground(Color.white); attemptsLabel=new JLabel(); attemptsLabel.setText("Attempts Made"); attemptsLabel.setFont(new Font("Comic Sans MS",Font.BOLD,15)); attemptsLabel.setBounds(10,5,125,35); attemptsLabel.setForeground(Color.black); highestScoreLabel=new JLabel(); highestScoreLabel.setText("Highest Score"); highestScoreLabel.setFont(new Font("Comic Sans MS",Font.BOLD,15)); highestScoreLabel.setBounds(10,30,125,35); highestScoreLabel.setForeground(Color.black); timeTakenLabel=new JLabel(); timeTakenLabel.setText("Time Taken (MM:SS)"); timeTakenLabel.setFont(new Font("Comic Sans MS",Font.BOLD,15)); timeTakenLabel.setBounds(10,55,160,35); timeTakenLabel.setForeground(Color.black); attemptsField=new JTextField(); attemptsField.setEditable(false); attemptsField.setBounds(230,14,70,15); attemptsField.setHorizontalAlignment(SwingConstants.CENTER); attemptsField.setFont(new Font("Comic Sans MS",Font.BOLD,13)); attemptsField.setBorder(BorderFactory.createBevelBorder(1)); highestScoreField=new JTextField(); highestScoreField.setEditable(false); highestScoreField.setText(""); highestScoreField.setBounds(230,39,70,15); highestScoreField.setHorizontalAlignment(SwingConstants.CENTER); highestScoreField.setFont(new Font("Comic Sans MS",Font.BOLD,13)); highestScoreField.setBorder(BorderFactory.createBevelBorder(1)); timeTakenField=new JTextField(); timeTakenField.setEditable(false); timeTakenField.setBounds(230,64,70,15); timeTakenField.setHorizontalAlignment(SwingConstants.CENTER); timeTakenField.setFont(new Font("Comic Sans MS",Font.BOLD,13)); timeTakenField.setBorder(BorderFactory.createBevelBorder(1)); ImageIcon icon=new ImageIcon("Guessing Game.png"); imageLabel=new JLabel(icon); imageLabel.setBounds(70,200,icon.getIconWidth(),icon.getIconHeight()); //Adding Action Listener to JButtons guessButton.addActionListener(this); giveUpButton.addActionListener(this); newGameButton.addActionListener(this); //Adding Key Listener to JTextField guessTextField.addKeyListener(this); //Adding panels to JFrame frame.add(panel1); frame.add(panel2); //Adding components to the container panel1.add(textLabel1); panel1.add(textLabel2); panel2.add(attemptsLabel); panel2.add(highestScoreLabel); panel2.add(timeTakenLabel); panel2.add(attemptsField); panel2.add(highestScoreField); panel2.add(timeTakenField); frame.add(textLabel3); frame.add(textLabel4); frame.add(textLabel5); frame.add(guessTextField); frame.add(guessButton); frame.add(giveUpButton); frame.add(newGameButton); panel1.add(imageLabel); //Setting properties of JFrame frame.getContentPane().setBackground(Color.white); frame.setSize(700,500); frame.setLocationRelativeTo(null); frame.setResizable(false); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //calling method countDownTimer() countDownTimer(); //Starting timer timer.start(); } @Override public void keyPressed(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { //Restricting JTextField to accept only numbers char c=e.getKeyChar(); if(!Character.isDigit(c)||Character.isWhitespace(c)){ if(!(e.getKeyChar()==KeyEvent.VK_BACK_SPACE)){ Toolkit.getDefaultToolkit().beep(); } e.consume(); } } @Override public void actionPerformed(ActionEvent e) { //Code for Guess Button if(e.getSource()==guessButton) { if (guessTextField.getText().equals("")) { Toolkit.getDefaultToolkit().beep(); JOptionPane.showMessageDialog(null, "Invalid Input","Error",JOptionPane.ERROR_MESSAGE); } else { attemptCount++; attemptsField.setText(Integer.toString(attemptCount)); int number = Integer.parseInt(guessTextField.getText()); if (randomNumber == number) { timer.stop(); guessTextField.setEditable(false); guessTextField.getCaret().setVisible(false); textLabel5.setText(""); guessTextField.setText(""); temp++; if(temp==1){ highestScoreField.setText(String.valueOf(attemptCount)); scoreCount=attemptCount; }else{ if(attemptCount<=scoreCount){ highestScoreField.setText(String.valueOf(attemptCount)); scoreCount=attemptCount; } } JOptionPane.showMessageDialog(null,"YOU WIN! Correct Guess was "+randomNumber+"\nClick on New Game to Play Again","Victory",JOptionPane.INFORMATION_MESSAGE); } else if (randomNumber > number) { textLabel5.setText(number + " is Low. Try Again!"); } else if (randomNumber < number) { textLabel5.setText(number + " is High. Try Again!"); } } } //Code for Give UP Button if(e.getSource()==giveUpButton){ timer.stop(); textLabel5.setText(""); guessTextField.setText(""); guessTextField.setEnabled(false); JOptionPane.showMessageDialog(null,+randomNumber+" is the right guess"); } //Code for New Game Button if(e.getSource()==newGameButton){ elapsedTime=0; seconds=0; minutes=0; timer.start(); attemptCount =0; textLabel5.setText(""); timeTakenField.setText(""); attemptsField.setText(""); guessTextField.setText(""); guessTextField.setEnabled(true); guessTextField.setEditable(true); guessTextField.getCaret().setVisible(true); guessTextField.requestFocus(); randomNumber=random.nextInt(100)+1; } } //Code for displaying Timer public void countDownTimer(){ timer=new Timer(1000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { elapsedTime=elapsedTime+1000; minutes=(elapsedTime/60000)%60; seconds=(elapsedTime/1000)%60; second_string=String.format("%02d",seconds); minute_string=String.format("%02d",minutes); timeTakenField.setText(minute_string+":"+second_string); } }); } //Creating main method public static void main(String[] args) { //Creating object of the class GuessingGameJava guessingGameJava=new GuessingGameJava(); } } //Restricting JTextField Character limits using PlainDocument class class JTextFieldCharLimit extends PlainDocument { int limit; public JTextFieldCharLimit(int limitation){ this.limit=limitation; } public void insertString(int offset, String str, AttributeSet set)throws BadLocationException { if(str==null){ return; }else if(getLength() + str.length() <=limit){ super.insertString(offset, str, set); } else if(getLength() + str.length() >limit){ Toolkit.getDefaultToolkit().beep(); } } } |
- Now run your program.
- So, we have successfully created our number guessing game in Java with GUI, as you can see in the above animation.
Screenshots of the Number Guessing Game in Java Swing
Number Guessing Game in Java Swing with Source Code Download
- You can download the source code of the number guessing game in Java with GUI by clicking the button below.
Number Guessing Game in Java PDF Download
- You can download the PDF file of this tutorial by clicking the button below.
Wrapping Up
To wrap up, that was the complete tutorial on creating a Number Guessing Game in Java Swing, along with the source code. If you have any queries or need additional assistance, feel free to ask by commenting on this post. Thank you.
People Are Also Reading…
- Login Form in Java Swing with Source Code
- Calculator Program in Java Swing/JFrame with Source Code
- How to Play Mp3 File in Java Tutorial | Simple Steps
- Text to Speech in Java
- Menu Driven Program in Java Using Switch Case
- Registration Form in Java With Database Connectivity
- How to Create Login Form in Java Swing
- How to Create Splash Screen in Java
- Best Laptop for Java Programming