how-to

Graphics

How to convert screen coordinates to component-based coordinates ?

For this sample you must use:

import java.awt.*;
import javax.swing.*;

When you have screen coordinates you can convert it into any java.awt.Component based coordinates. This sample code shows converting screen coordinates to javax.swing.JButton based coordinates. The conversion is called throught button`s java.awt.event.ActionListener = after button click.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

  /* -- get screen mouse coordinates */
    
  PointerInfo pi = MouseInfo.getPointerInfo();
  if ( pi != null ) {
    System.out.println( "Screen coordinates = " + pi.getLocation().toString() );    

    /* -- convert it into jbutton-based coordinates */
      
    Point p = pi.getLocation();            
    SwingUtilities.convertPointFromScreen( p , jButton1 );
    System.out.println( "jButton1-based coordinates = " + p.toString() );            
  }
  
  ...   
}

The output could be:

Screen coordinates = java.awt.Point[x=288,y=272]
jButton1-based coordinates = java.awt.Point[x=57,y=10]