Advertisement
Guest User

Number guessing game

a guest
Apr 19th, 2024
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 14.70 KB | Source Code | 0 0
  1. This is my first ever project in Java. It is a small number guessing game with GUl. On gui, there are three buttons (yes,no, enter) and a textfield to get random number. Yes and no buttons are for input like "if you wanna start playin, and if i click yes" the game starts, No button is for "i dont want to start". This game doesn't involve any visual, it only runs by console. I redirected console to the jtextarea via printstream.So, the issue is I can't input anything by clicking yes, no buttons even though there are actionlisteners implemented in correct methods. I have been solving that problem for a week, and i've also tried various methods from chatgpt and also didn't work out. Does scanner input also work well with gui?
  2.  
  3. CODE :
  4. package JavaApplication1;
  5. import java.util.Random;
  6. import java.util.Scanner;
  7. import java.awt.*;
  8. import java.awt.event.*;
  9. import javax.swing.*;
  10. import javax.swing.event.*;
  11. import java.io.*;
  12. import java.util.*;
  13. import java.io.OutputStream;
  14. import java.io.PrintStream;
  15. public  class JavaApplication1
  16. {
  17.      JButton start,about,close,yes,no,enter;
  18.      JFrame frame1,frame2,fram;
  19.      JPanel jp,jp2,centerpanel;
  20.      JTextArea jta;
  21.      JTextField numinput;
  22.      String choice = "";
  23.      JScrollPane js;
  24.      Scanner scanner = new Scanner(System.in);
  25.      
  26.     private void setGuiEnabled(boolean enabled) {
  27.         // Enable/disable GUI components
  28.         yes.setEnabled(enabled);
  29.         no.setEnabled(enabled);
  30.         numinput.setEnabled(enabled);
  31.         enter.setEnabled(enabled);
  32.     }
  33.  
  34.      public  void homepage()
  35.      {
  36.          try {
  37.          PrintStream printStream = new PrintStream(new OutputStream() {
  38.              @Override
  39.              public void write(int b) {
  40.                 jta.append(String.valueOf((char) b));
  41.                  jta.setCaretPosition(jta.getDocument().getLength());
  42.              }
  43.          });
  44.           System.setOut(printStream);
  45.              System.setErr(printStream);
  46.          frame1 = new JFrame();
  47.              frame1.setBounds(500,500,400,300);
  48.              frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  49.              frame1.setLayout(new GridLayout(4,1));
  50.              
  51.              
  52.              JLabel lb = new JLabel("Number guessing game for hnin oo wai");
  53.              lb.setBackground(Color.PINK);
  54.              lb.setOpaque(true);
  55.              lb.setFont(new Font("Calibri",Font.BOLD,17));
  56.              lb.setHorizontalAlignment(SwingConstants.CENTER);;
  57.              frame1.add(lb);
  58.              
  59.              start = new JButton("Start");
  60.              start.setBackground(Color.GREEN);
  61.              start.setFont(new Font("Roboto",Font.BOLD,20));
  62.              start.addActionListener(new ActionListener()
  63.                      {
  64.                         public void actionPerformed(ActionEvent ae)
  65.                         {
  66.                                                      SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
  67.                 @Override
  68.                 protected Void doInBackground() throws Exception {
  69.                     gamepage();
  70.                     core();
  71.                     return null;
  72.                 }
  73.  
  74.                 @Override
  75.                 protected void done() {
  76.                     // Re-enable GUI components after task completion
  77.                     setGuiEnabled(true);
  78.                 }
  79.             };
  80.             worker.execute();
  81.                         }
  82.                  
  83.                      }
  84.                      
  85.                      );
  86.              frame1.add(start);
  87.              
  88.              
  89.              frame2 = new JFrame();
  90.              frame2.setBounds(100, 100, 400, 300);
  91.             frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  92.              JTextArea aboutmsg = new JTextArea();
  93.             aboutmsg.setFont(new Font("Arial", Font.BOLD, 16)); // Set font with bold style and increased size
  94.             aboutmsg.setForeground(Color.BLUE); // Set text color to blue
  95.             aboutmsg.setBackground(new Color(240, 240, 240)); // Set background color
  96.             aboutmsg.setBorder(BorderFactory.createCompoundBorder(
  97.                     BorderFactory.createEmptyBorder(10, 10, 10, 10), // Add padding
  98.                     BorderFactory.createLineBorder(Color.BLACK))); // Add border
  99.              aboutmsg.setLineWrap(true);
  100.              aboutmsg.setWrapStyleWord(true);
  101.              aboutmsg.setText("This game is developed by ."
  102.                                 + "He is very open minded ");
  103.              
  104.              about = new JButton("About");
  105.              about.setBackground(Color.GRAY);
  106.              about.setFont(new Font("Roboto",Font.BOLD,20));
  107.              about.addActionListener(new ActionListener()
  108.                      {   
  109.                  public void actionPerformed(ActionEvent ae)
  110.                  {
  111.                     frame2.getContentPane().add(aboutmsg, BorderLayout.CENTER);
  112.                     frame2.setVisible(true);
  113.                      
  114.                  }
  115.                      
  116.                      });
  117.              
  118.              frame1.add(about);
  119.              
  120.              close = new JButton("Close");
  121.              close.setBackground(Color.RED);
  122.              close.setFont(new Font("Roboto",Font.BOLD,20));
  123.              close.addActionListener(new ActionListener()
  124.                      {
  125.                             public void actionPerformed(ActionEvent ae)
  126.                             {
  127.                                 if (JOptionPane.showConfirmDialog(frame2, "Do you want to exit?", "Confirm Message",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE) == JOptionPane.YES_OPTION);
  128.                                 {System.exit(0); }
  129.                                
  130.                                 frame2.add(aboutmsg);
  131.                                 frame2.setVisible(true);
  132.                             }
  133.                      } );
  134.              frame1.add(close);          
  135.              frame1.setVisible(true);
  136.          }catch(Exception e)
  137.          {
  138.              System.out.println(e);
  139.          }
  140.        
  141.      }
  142.      
  143.     public void gamepage()
  144.     {
  145.          try {
  146.          fram = new JFrame("Number guessing game");
  147.         fram.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  148.        
  149.          jp = new JPanel();
  150.         jp.setBounds(0,0,440,400);
  151.         jp.setBorder(BorderFactory.createTitledBorder("Enjoy the game"));
  152.         jp.setLayout(null);
  153.          jta = new JTextArea();
  154.         jta.setBackground(Color.DARK_GRAY);
  155.         jta.setForeground(Color.WHITE);
  156.         JScrollPane js = new JScrollPane(jta);
  157.        
  158.         js.setBounds(5,20,430,375);
  159.         jp.add(js);
  160.         fram.add(jp);
  161.          jp2 = new JPanel(new BorderLayout());
  162.         jp2.setBounds(0,410,440,150);
  163.         jp2.setBorder(BorderFactory.createTitledBorder("Control"));
  164.        
  165.        
  166.        
  167.          yes = new JButton(" YES ");
  168.         yes.setBackground(Color.BLUE);
  169.        
  170.         yes.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
  171.          jp2.add(yes, BorderLayout.WEST);
  172.        
  173.         no = new JButton(" NO ");
  174.         no.setBackground(Color.BLUE);
  175.         no.setBackground(Color.red);
  176.         no.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
  177.          jp2.add(no, BorderLayout.EAST);
  178.         numinput = new JTextField(20);
  179.         numinput.setFont(new Font("Arial", Font.PLAIN, 14)); // Set font
  180.         numinput.setHorizontalAlignment(JTextField.CENTER); // Center-align text
  181.         numinput.setBackground(new Color(0xFAFAFA)); // Light gray background
  182.         numinput.setForeground(Color.BLACK); // Black text color
  183.         numinput.setBorder(BorderFactory.createLineBorder(Color.GRAY, 2)); // Gray border
  184.         numinput.setMargin(new Insets(5, 5, 5, 5)); // Add padding
  185.         numinput.setToolTipText("Enter a number");
  186.        
  187.        
  188.        
  189.          enter = new JButton("Enter");     
  190.          enter.setFont(new Font("Arial", Font.BOLD, 24));
  191.          enter.setBackground(Color.GRAY); // Light blue
  192.          enter.setOpaque(true); // Make button opaque to show background color
  193.          enter.setBorderPainted(false); // Hide default button border
  194.          enter.setMnemonic(KeyEvent.VK_ENTER);
  195.          
  196.          enter.addActionListener(new ActionListener()
  197.         {
  198.        
  199.                     public void actionPerformed(ActionEvent ae)
  200.                        
  201.                      {
  202.                         if (numinput.getText().isEmpty()) {
  203.                             JOptionPane.showMessageDialog(fram, "Please Enter a number");
  204.                         }
  205.                         else {
  206.                             try {
  207.                                
  208.                                 getnum();
  209.                                 numinput.setText("");
  210.                                 numinput.requestFocus();
  211.                             } catch (NumberFormatException e) {
  212.                                 // If parsing fails, show an error message
  213.                                 JOptionPane.showMessageDialog(fram, "Please Enter a valid number");
  214.                                 // Optionally, you can clear the input field or take other actions here
  215.                                 numinput.setText("");
  216.                                 numinput.requestFocus();
  217.                             }
  218.                        
  219.        
  220.                             }
  221.                      }});
  222.        
  223.          
  224.          enter.addMouseListener(new java.awt.event.MouseAdapter() {
  225.              public void mouseEntered(java.awt.event.MouseEvent evt) {
  226.                     enter.setBackground(new Color(0x007BFF)); // Dark blue
  227.                 }
  228.  
  229.                 public void mouseExited(java.awt.event.MouseEvent evt) {
  230.                     enter.setBackground(new Color(0x80A9FF)); // Light blue
  231.                 }
  232.             });
  233.  
  234.        
  235.        
  236.        
  237.    
  238.        
  239.        
  240.        
  241.         centerpanel = new JPanel (new GridLayout(2,1));
  242.         centerpanel.add(numinput);
  243.         centerpanel.add(enter);
  244.        
  245.        
  246.         jp2.add(centerpanel, BorderLayout.CENTER);
  247.        
  248.        
  249.        
  250.         fram.getContentPane().add(jp2);    
  251.        
  252.        
  253.        
  254.        
  255.         fram.setLayout(null);
  256.         fram.setBounds(300,300,460,600);
  257.         fram.setVisible(true);
  258.        
  259.        
  260.          }catch(Exception e)
  261.          {
  262.              System.out.println(e);
  263.          }
  264.        
  265.        
  266.     }
  267.    
  268.  
  269.  
  270.  
  271.   public static  void main (String[] args)
  272.   {
  273.    
  274.     JavaApplication1 game = new JavaApplication1();
  275.     game.homepage();
  276.    
  277.    
  278.  
  279.  
  280.  
  281.   }
  282.  
  283.  
  284.  
  285.  
  286. public void core() {
  287.     //String y_choice = "";
  288.        
  289.         try {
  290.             PrintStream printStream = new PrintStream(new OutputStream() {
  291.                 @Override
  292.                 public void write(int b) {
  293.                     jta.append(String.valueOf((char) b));
  294.                     jta.setCaretPosition(jta.getDocument().getLength());
  295.                 }
  296.             });
  297.             System.setOut(printStream);
  298.             System.setErr(printStream);
  299.  
  300.             HeartPattern heart1 = new HeartPattern();
  301.             Random rand = new Random();
  302.  
  303.             System.out.print("Number guessing game! Would you like to start now ? \n 'Yes' Or 'No' : ");
  304.                
  305.                 String choice_real = getinput_String();
  306.                
  307.              // Get user input
  308.                System.out.println();
  309.             while (choice_real.equalsIgnoreCase("Yes")) {
  310.                 System.out.print("Enter the minimum range of random num you would like to guess, \n minimum range : ");
  311.                 int minrange = getnum() ; //
  312.                 scanner.nextLine();
  313.  
  314.                 System.out.print("Enter the maximum range of random num you would like to guess, \n maximum range : ");
  315.                 int maxrange = getnum();
  316.                 scanner.nextLine(); // Consume newline character
  317.  
  318.                 System.out.print("Enter a number : ");
  319.                 int num = getnum() ; // Get user input
  320.                 scanner.nextLine(); // Consume newline character
  321.  
  322.                 int r_num = minrange + rand.nextInt(maxrange - minrange);
  323.  
  324.                 if (num == r_num) {
  325.                     System.out.println("You won ");
  326.                     System.out.println();
  327.                     heart1.heart();
  328.                 }
  329.  
  330.                 while (num != r_num) {
  331.                     determine_result(num, r_num);
  332.                     System.out.print("Enter a number : ");
  333.                     num = getnum() ; // Get user input
  334.                     scanner.nextLine(); // Consume newline character
  335.  
  336.                     if (num == r_num) {
  337.                         System.out.println("You won my princess\n you are so smart hnin oo wai, koko loves you so much, have fun on the trip ");
  338.                         System.out.println();
  339.                         heart1.heart();
  340.                         break;
  341.                     }
  342.                 }
  343.  
  344.                 System.out.println();
  345.                 System.out.print(" Would you like to start again ? \n 'Yes' Or 'No' : ");
  346.                 choice_real = getinput_String();
  347.             }
  348.  
  349.             if (choice_real.equalsIgnoreCase("No")) {
  350.                 System.out.println("Okay pr");
  351.             }
  352.         } catch (Exception e) {
  353.             System.out.println(e);
  354.         } finally {
  355.             scanner.close(); // Close the Scanner object to release resources
  356.         }
  357.     }
  358.  
  359.   public static void determine_result(int n, int r )
  360.   {
  361.     if (n < r)
  362.     {
  363.        System.out.println ("Higher");
  364.        System.out.println ();
  365.     }
  366.  
  367.     if (n > r)
  368.     {
  369.       System.out.println ("Lower");
  370.       System.out.println ();
  371.     }
  372.   }
  373.  
  374.   public int getnum() {
  375.         int num = 0;
  376.         String input = numinput.getText().trim(); // Get input from JTextField
  377.         if (!input.isEmpty()) { // Check if input is not empty
  378.             try {
  379.                 num = Integer.parseInt(input); // Parse input to integer
  380.             } catch (NumberFormatException e) {
  381.                 // Handle invalid input (non-numeric)
  382.                 e.printStackTrace();
  383.             }
  384.         } else {
  385.             // If the JTextField is empty, read input from the console using the provided Scanner
  386.             if (scanner.hasNextInt()) {
  387.                 num = scanner.nextInt();
  388.             } else {
  389.                 // Handle non-integer input
  390.                 System.out.println("Invalid input. Please enter an integer.");
  391.                 scanner.next(); // Consume the invalid input
  392.             }
  393.         }
  394.         return num;
  395.     }
  396.  
  397.    public String getinput_String() {
  398.        
  399.         //String choice = ""; // Default choice
  400.        
  401.         try {
  402.             // Create action listeners for the "Yes" and "No" buttons using lambda expressions
  403.             yes.addActionListener(e -> choice = "Yes"); // Update choice if "Yes" button is clicked
  404.             no.addActionListener(e -> choice = "No");   // Update choice if "No" button is clicked
  405.  
  406.         } catch (Exception e) {
  407.             JOptionPane.showMessageDialog(null, "Error occurred: " + e.getMessage());
  408.         }
  409.  
  410.         // Return the choice once it's made
  411.         return choice;
  412.     }
  413.  
  414.  
  415.  
  416.  
  417. }
  418.  
  419. class HeartPattern  
  420. {  
  421.          
  422.         public  void heart  ()  
  423.         {  
  424.                
  425.                 final int size = 4  ;  
  426.          
  427.                  
  428.             for (int m = 0; m < size; m++) {  
  429.                     for (int n = 0; n <= 4 * size; n++) {  
  430.                             double pos1 = Math.sqrt(Math.pow(m - size, 2) + Math.pow(n - size, 2));  
  431.                             double pos2 = Math.sqrt(Math.pow(m - size, 2) + Math.pow(n - 3 * size, 2));  
  432.    
  433.                             if (pos1 < size + 0.5 || pos2 < size + 0.5) {  
  434.                                     System.out.print('*');  
  435.                             } else {  
  436.                                     System.out.print(' ');  
  437.                             }  
  438.                         }  
  439.                         System.out.print(System.lineSeparator());  
  440.                 }  
  441.                
  442.                 for (int m = 1; m <= 2 * size; m++)  
  443.                 {  
  444.                     for (int n = 0; n < m; n++) {  
  445.                         System.out.print(' ');  
  446.                 }  
  447.                 for (int n = 0; n < 4 * size + 1 - 2 * m; n++) {  
  448.                         System.out.print("*");  
  449.                     }  
  450.                 System.out.print(System.lineSeparator());  
  451.                 }  
  452.     }  
  453. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement