Home > Blockchain >  MouseListener of TrayIcon Position is not correct
MouseListener of TrayIcon Position is not correct

Time:10-03

Is mouse position of trayicon of awt is correct consider a sample code,

import java.net.*;
import java.awt.*;
import javax.imageio.*;
import java.awt.event.*;
import javax.swing.SwingUtilities;

public class SampleTray extends MouseAdapter {
    private SystemTray tray = SystemTray.getSystemTray();
    private TrayIcon trayIcon;

    public SampleTray() {
        try {
            this.trayIcon = new TrayIcon(
                ImageIO.read(new URL("https://i.stack.imgur.com/lM3aS.png"))
            );
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }

        try {
            tray.add(trayIcon);
        } catch (AWTException e) {
            e.printStackTrace();
            System.exit(1);
        }

        this.trayIcon.setImageAutoSize(true);
        this.trayIcon.addMouseListener(this);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

        System.out.println("Screen Size is x "   screenSize.getWidth()   " y "   screenSize.getHeight());
        System.out.println("Mouse clicked at x "   e.getX()   " y "   e.getY());
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(SampleTray::new);
    }
}

Output of Above code:

Screen Size is x 1536.0 y 864.0
Mouse clicked at x 1638 y 1062

Why the x value is grater than the screen bounds ? My task bar is on bottom. How to get correct position relative to screen ?

Note : getXonScreen and getYonScreen return same and if the value is correct please explain me how this value is relative to screen from orgin (0 , 0).

Edit:

I am using this position to place the undecrotated window near that tray icon so i want this to be correct.

As @Gilbert Le Blanc Said problem is Scaling but when i change scale to 100% all are become too small and can't except that end-user is going to change the scaling for this software so what the way to solve this ?

Thanks.

CodePudding user response:

I solved using the following idea,

@Override
public void mouseClicked(MouseEvent e) {
    var scale = Toolkit.getDefaultToolkit().getScreenResolution() / 96.0;
    System.out.println("Scaling Size is x "   scale );
    System.out.println("Size : "   Toolkit.getDefaultToolkit().getScreenSize());
    System.out.println("Mouse clicked at x "   e.getXOnScreen() / scale   " y "   e.getYOnScreen() / scale);
}

Note: This is not actual code that i used, i use javafx like

var scaleX = Screen.getPrimary().getOutputScaleX();
var scaleY = Screen.getPrimary().getOutputScaleY();

But the idea is same, Hope this helps to feature readers.

  • Related