You are on page 1of 5

Adapter class

Mouse pressed and released sum and diff example:


import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;

public class MyClass extends MouseAdapter {


JFrame f;
JTextField t1;
JTextField t2;
JLabel l;

public MyClass() {
f=new JFrame();
t1=new JTextField(20);
t1.setBounds(50,25,100,20);
t2=new JTextField(20);
t2.setBounds(50,55,100,20);
l=new JLabel();
l.setBounds(50,95,100,20);
f.add(t1);
f.add(t2);
f.add(l);

// Add the mouse adapter to the frame


l.addMouseListener(this);

// Set the size and show the frame


f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyClass();
}

@Override
public void mousePressed(MouseEvent e) {
int a=Integer.parseInt(t1.getText());
int b=Integer.parseInt(t2.getText());
int c=a+b;
l.setText(String.valueOf(c));
}

@Override
public void mouseReleased(MouseEvent e) {
int a=Integer.parseInt(t1.getText());
int b=Integer.parseInt(t2.getText());
int c=a-b;
l.setText(String.valueOf(c));
}
}

You might also like