Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- `import javax.swing.*;
- import java.awt.*;
- import java.awt.event.*;
- public class ExamQuestion extends JFrame implements MouseListener {
- private JTextField num1Field, num2Field;
- private JLabel resultLabel;
- private int num1, num2;
- public ExamQuestion() {
- // Set up the JFrame
- super("Sum and Difference Calculator");
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- setLayout(new GridLayout(4, 2));
- // Create the input text fields
- num1Field = new JTextField();
- num2Field = new JTextField();
- add(new JLabel("Enter first number: "));
- add(num1Field);
- add(new JLabel("Enter second number: "));
- add(num2Field);
- // Create the Calculate button
- JButton calculateButton = new JButton("Calculate");
- add(calculateButton);
- // Create the output label
- resultLabel = new JLabel();
- add(resultLabel);
- // Add mouse listener to the label
- calculateButton.addMouseListener(this);
- // Show the JFrame
- pack();
- setVisible(true);
- }
- // Mouse listener methods
- public void mousePressed(MouseEvent e) {
- // Calculate the sum and display it when the button is clicked
- try {
- num1 = Integer.parseInt(num1Field.getText());
- num2 = Integer.parseInt(num2Field.getText());
- resultLabel.setText("Sum: " + (num1 + num2));
- } catch (NumberFormatException ex) {
- resultLabel.setText("Invalid input!");
- }
- }
- public void mouseReleased(MouseEvent e) {
- // Calculate the difference and display it when the mouse is released over the label
- try {
- num1 = Integer.parseInt(num1Field.getText());
- num2 = Integer.parseInt(num2Field.getText());
- resultLabel.setText("Difference: " + (num1 - num2));
- } catch (NumberFormatException ex) {
- resultLabel.setText("Invalid input!");
- }
- }
- // Unused mouse listener methods
- public void mouseClicked(MouseEvent e) {}
- public void mouseEntered(MouseEvent e) {}
- public void mouseExited(MouseEvent e) {}
- public static void main(String[] args) {
- new ExamQuestion();
- }
- }`
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement