deteksi kordinat mouse jFrame java

melihat kordita X dan Y pada Jframe

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
 
public class mouse extends JFrame 
{
 
  public static void main(String[] args)
  {
    SwingUtilities.invokeLater(new Runnable()
    {
      public void run()
      {
        displayJFrame();
      }
    });
  }
 
  static void displayJFrame()
  {
    JFrame jFrame = new JFrame();
    jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jFrame.setTitle("Deteksi Mouse ");
 
    jFrame.setPreferredSize(new Dimension(400, 300));
    jFrame.pack();
    jFrame.setLocationRelativeTo(null);
     
    final AlsXYMouseLabelComponent alsXYMouseLabel = new AlsXYMouseLabelComponent();
 
    JLayeredPane layeredPane = jFrame.getRootPane().getLayeredPane();
    layeredPane.add(alsXYMouseLabel, JLayeredPane.DRAG_LAYER);
    alsXYMouseLabel.setBounds(0, 0, jFrame.getWidth(), jFrame.getHeight());

    jFrame.addMouseMotionListener(new MouseMotionAdapter() {
      public void mouseMoved(MouseEvent me)
      {
        alsXYMouseLabel.x = me.getX();
        alsXYMouseLabel.y = me.getY();
        alsXYMouseLabel.repaint();
      }
    });
 
    jFrame.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
     
    jFrame.setVisible(true);
  }
   
}
 
class AlsXYMouseLabelComponent extends JComponent
{
  public int x;
  public int y;
   
  public AlsXYMouseLabelComponent() {
    this.setBackground(Color.blue);
  }
 
  protected void paintComponent(Graphics g)
  {
    super.paintComponent(g);
    String s = "posisi X : " +x+ ". posisi Y : " +y;
    g.setColor(Color.BLACK);
    g.drawString(s,x, y);;
  }
  
}


About Author

amir thoham


Comment & Discussions

    Please LOGIN before if you want to give the comment.