Mouse listener and mouse events in Java AWT: Here is a simple tutorial that explains about mouse events. There are 2 example programs with source code available for your reference. And these two java programs are talking about following classes,
- Mouse Listener,
- Mouse events,
- MouseAdapter
Read: WindowListener in Java AWT with Tutorial
PROGRAM 1:
MOUSE POINTER IN JAVA
This java program is used to find the mouse positions of ‘x’ and ‘y’ values of a cursor in the screen. And it gives the mouse value for each and every movement of moving.
Read: Java AWT Scrollbar Tutorial
//Import statements import java.awt.*; import java.awt.event.*; //Class definition class MouseDemo extends Frame { public MouseDemo() { setTitle("MOUSE DEMO"); addMouseListener(new MyMouseListener()); addWindowListener(new MyWindowListener()); setSize(300,300); show(); } public static void main(String str[]) { new MouseDemo(); } } class MyMouseListener extends MouseAdapter { public void mouseReleased(MouseEvent me) { String str="Mouse Released at "+me.getX()+","+me.getY(); System.out.print(str); } } class MyWindowListener extends WindowAdapter { public void windowClosing(WindowEvent we) { System.exit(0); } }
PROGRAM 2:
MOUSE EVENTS IN JAVA
This program will give the details about the mouse performing actions in the screen like mouse clicked, mouse released, mouse dragged and it will also give the x and y values of the mouse.
[Useful: C Program Tutorials] & [IT Companies Details]
//Import statements import java.awt.*; import java.awt.event.*; //Class definition class MouseEvents extends Frame implements MouseListener { Variable declaration int xa,ya; String mg; public MouseEvents() { setTitle("Mouse Demo"); mg="Operate the mouse"; addMouseListener(this); setBackground(Color.red); setSize(300,300); show(); } public void mouseClicked(MouseEvent me1) { xa=me1.getX(); ya=me1.getY(); mg="Mouse clicked at "+xa+","+ya; repaint(); System.out.print("MOUSE CLICKED"); } public void mousePressed(MouseEvent me2) { xa=me2.getXa(); ya=me2.getYa(); mg="Mouse Pressed at "+xa+","+ya; repaint(); } public void mouseReleased(MouseEvent me3) { xa=me3.getXa(); ya=me3.getYa(); mg="Mouse Released at "+xa+","+ya; repaint(); } public void mouseEntered(MouseEvent me4) { xa=me4.getXa(); ya=me4.getYa(); mg="Mouse Entered at "+xa+","+ya; repaint(); } public void mouseExited(MouseEvent me5) { xa=me5.getXa(); ya=me5.getYa(); mg="Mouse exited at "+xa+","+ya; repaint(); } public void paint(Graphics g) { g.setColor(Color.blue); // g.setFont(new Font("Courier",Font.ITALIC,)); g.drawString(mg,xa,ya); } public static void main(String args[]) { MouseEvents m=new MouseEvents(); } }
SEE: All Examination Results & News