How to use MouseListener in java
Code = >
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
// Create a class and extend JFrame
// Second Step - implement MouseListener interface
// Third Step - create an component - Square = I am using with help of JLabel
// We add more thing - for see location we add something
public class simple extends JFrame implements MouseListener {
// Create Constructor
JLabel label;
JLabel label1;
Border border;
simple(){
// Create JFrame
this.setSize(400,400); // JFrame Size
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // For Closing JFrame by Click Cross button
//-----------We Add Border into frame for more good looking------
border =new LineBorder(Color.black,2); // calling Border instance and set Color with size;
//----------JLabel-------------
label=new JLabel(); // Create instance of JLabel;
label1=new JLabel(); // Create instance of JLabel1;
label.setBounds(10,40,50,50); // Set size of JLabel and Margin Also
label1.setBounds(20,40,100,20); // Set size of JLabel and Margin Also
label.setBackground(Color.GREEN); // Set Background of JLabel
label.setOpaque(true); // Set Visibilty of JLable if you choose false it is not visible
label.setBorder(border); // add border;
this.add(label); // then add into JFrame
this.add(label1); // then add into JFrame
label.addMouseListener(this); // It will be write here
this.setLayout(null); // Layout null
this.setVisible(true); // For visible JFrame
}
// Create Main Method
public static void main(String[]args){
// Create Class Object
simple simple=new simple();
}
@Override
public void mouseClicked(MouseEvent e) {
//--------------Last Step-------------
// using Mouse clicked
//int x=e.getX(); // By this , we get location , where i was clicked into frame;
//int y = e.getY(); // now we not need this
int width = 1365; // This is your screen Width size
int height=765; // And This is your Height of screen
int min = 40; // Min value it must be lie between your screen size
int x= (int)(Math.random() * (width - min + 1 ))+min; // get x int location value
int y= (int)(Math.random() * (height - min + 1 ))+min; // get y int location value
label1.setText("X : "+x+" "+"Y : "+y); // For seeing Location
int R= (int)(Math.random() * (255 - 10 + 1 ))+10;
int G= (int)(Math.random() * (255 - 10 + 1 ))+10;
int B= (int)(Math.random() * (255 - 10 + 1 ))+10;
// Now we add jLabel int this x and y location
label.setBackground(new Color(R,G,B)); // we will change background color with RGB value
label.setLocation(x,y);
// Last step is , we must will be added mouse listener into Lable
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}
Comments
Post a Comment