Advertisement
RupeshAcharya60

2078

Mar 25th, 2023
905
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.28 KB | Source Code | 0 0
  1. `import javax.swing.*;
  2. import java.awt.*;
  3. import java.awt.event.*;
  4.  
  5. public class ExamQuestion extends JFrame implements MouseListener {
  6.     private JTextField num1Field, num2Field;
  7.     private JLabel resultLabel;
  8.     private int num1, num2;
  9.  
  10.     public ExamQuestion() {
  11.         // Set up the JFrame
  12.         super("Sum and Difference Calculator");
  13.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  14.         setLayout(new GridLayout(4, 2));
  15.  
  16.         // Create the input text fields
  17.         num1Field = new JTextField();
  18.         num2Field = new JTextField();
  19.         add(new JLabel("Enter first number: "));
  20.         add(num1Field);
  21.         add(new JLabel("Enter second number: "));
  22.         add(num2Field);
  23.  
  24.         // Create the Calculate button
  25.         JButton calculateButton = new JButton("Calculate");
  26.         add(calculateButton);
  27.  
  28.         // Create the output label
  29.         resultLabel = new JLabel();
  30.         add(resultLabel);
  31.  
  32.         // Add mouse listener to the label
  33.         calculateButton.addMouseListener(this);
  34.  
  35.         // Show the JFrame
  36.         pack();
  37.         setVisible(true);
  38.     }
  39.  
  40.  
  41.  
  42.  
  43.     // Mouse listener methods
  44.     public void mousePressed(MouseEvent e) {
  45.         // Calculate the sum and display it when the button is clicked
  46.         try {
  47.             num1 = Integer.parseInt(num1Field.getText());
  48.             num2 = Integer.parseInt(num2Field.getText());
  49.             resultLabel.setText("Sum: " + (num1 + num2));
  50.         } catch (NumberFormatException ex) {
  51.             resultLabel.setText("Invalid input!");
  52.         }
  53.     }
  54.  
  55.     public void mouseReleased(MouseEvent e) {
  56.         // Calculate the difference and display it when the mouse is released over the label
  57.         try {
  58.             num1 = Integer.parseInt(num1Field.getText());
  59.             num2 = Integer.parseInt(num2Field.getText());
  60.             resultLabel.setText("Difference: " + (num1 - num2));
  61.         } catch (NumberFormatException ex) {
  62.             resultLabel.setText("Invalid input!");
  63.         }
  64.     }
  65.  
  66.     // Unused mouse listener methods
  67.     public void mouseClicked(MouseEvent e) {}
  68.     public void mouseEntered(MouseEvent e) {}
  69.     public void mouseExited(MouseEvent e) {}
  70.  
  71.     public static void main(String[] args) {
  72.         new ExamQuestion();
  73.     }
  74. }`
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement