Advertisement
Guest User

Lab05 WidgetViewer Help

a guest
Jun 11th, 2019
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.70 KB | None | 0 0
  1. package lab05;
  2.  
  3. import java.awt.event.*;
  4. import java.util.*;
  5. import javax.swing.*;
  6.  
  7. public class ChooseYourOperation {
  8.  
  9.     public static void main(String[] args) {
  10.        
  11.         WidgetViewer wv = new WidgetViewer();
  12.        
  13.         Random rand = new Random();
  14.        
  15.         int x = rand.nextInt(10); // Generate first random number 0-9 inclusive
  16.         int y = rand.nextInt(10); // Generate second random number 0-9 inclusive
  17.        
  18.         String text = "x: " + x + " y: " + y; // Ask user what the answer is
  19.         wv.add(new JLabel(text)); // Create text GUI
  20.        
  21.         String instruction = "Enter an operation number"; // Ask user what the answer is
  22.         wv.add(new JLabel(instruction)); // Create text GUI
  23.        
  24.         JTextField textField = new JTextField(10); // Store users answer
  25.         wv.add(textField);
  26.    
  27.         JButton button = new JButton("Press here when you've entered your operation"); // Button for user to hit once entered answer
  28.         wv.addAndWait(button);
  29.        
  30.         button.addActionListener(new ActionListener() {
  31.  
  32.             @Override
  33.             public void actionPerformed(ActionEvent arg0) {
  34.                
  35.                 int operationNumber = Integer.parseInt(textField.getText()); // Evaluates stored value
  36.  
  37.                 String result = "";
  38.  
  39.                 if (operationNumber >= 1 && operationNumber <= 10) {
  40.                     result = String.valueOf(x+y);
  41.  
  42.                 }
  43.                
  44.                 else if (operationNumber % 4 == 0) {
  45.                     result = String.valueOf(x-y);
  46.  
  47.                 }
  48.                
  49.                 else if (operationNumber % 5 == 0) {
  50.                     result = String.valueOf(x/y);
  51.                 }
  52.                
  53.                 else if (operationNumber % 2 == 0) {
  54.                     result = String.valueOf((float)x/y);
  55.                 }
  56.                
  57.                 else {
  58.                     result = String.valueOf(x*y);
  59.                 }
  60.  // Ask user what the answer is
  61.                 wv.add(new JLabel(result)); // Create text GUI             
  62.             }
  63.         });
  64.        
  65.     }
  66.    
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement