كيف يمكنني تحديد أي مراقبة يحدث حدث الماوس الأرجوحة؟

StackOverflow https://stackoverflow.com/questions/1248386

سؤال

لدي Java Mouselistener على أحد مكونات الكشف عن مكابس الماوس. كيف يمكنني معرفة أي مراقبة حدثت الصحافة الماوس؟

@Override
public void mousePressed(MouseEvent e) {
  // I want to make something happen on the monitor the user clicked in
}

التأثير الذي أحاول تحقيقه هو: عندما يضغط المستخدم على زر الماوس في تطبيقي، تظهر نافذة منبثقة بعض المعلومات، حتى يتم إصدار الماوس. أريد أن أضمن وضع هذه النافذة حيث ينقر المستخدم، لكنني بحاجة إلى ضبط موضع النافذة على الشاشة الحالية بحيث تكون النافذة بأكملها مرئية.

هل كانت مفيدة؟

المحلول

يمكنك الحصول على معلومات العرض من java.awt.graphicsenvironment.. وبعد يمكنك استخدام هذا للحصول على معلومات حول النظام المحلي الخاص بك. بما في ذلك حدود كل شاشة.

Point point = event.getPoint();

GraphicsEnvironment e 
     = GraphicsEnvironment.getLocalGraphicsEnvironment();

GraphicsDevice[] devices = e.getScreenDevices();

Rectangle displayBounds = null;

//now get the configurations for each device
for (GraphicsDevice device: devices) { 

    GraphicsConfiguration[] configurations =
        device.getConfigurations();
    for (GraphicsConfiguration config: configurations) {
        Rectangle gcBounds = config.getBounds();

        if(gcBounds.contains(point)) {
            displayBounds = gcBounds;
        }
    }
}

if(displayBounds == null) {
    //not found, get the bounds for the default display
    GraphicsDevice device = e.getDefaultScreenDevice();

    displayBounds =device.getDefaultConfiguration().getBounds();
}
//do something with the bounds
...

نصائح أخرى

ساعدني إجابة غنية في العثور على حل كامل:

public void mousePressed(MouseEvent e) {
    final Point p = e.getPoint();
    SwingUtilities.convertPointToScreen(p, e.getComponent());
    Rectangle bounds = getBoundsForPoint(p);
    // now bounds contains the bounds for the monitor in which mouse pressed occurred
    // ... do more stuff here
}


private static Rectangle getBoundsForPoint(Point point) {
    for (GraphicsDevice device : GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()) {
        for (GraphicsConfiguration config : device.getConfigurations()) {
            final Rectangle gcBounds = config.getBounds();
            if (gcBounds.contains(point)) {
                return gcBounds;
            }
        }
    }
    // if point is outside all monitors, default to default monitor
    return GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
}

نظرا لأن Java 1.6 يمكنك استخدام GetLocationOscreen، في الإصدارات السابقة، يجب عليك الحصول على موقع المكون الذي ولدت الحدث:

Point loc;
// in Java 1.6
loc = e.getLocationOnScreen();
// in Java 1.5 or previous
loc = e.getComponent().getLocationOnScreen();

سيتعين عليك استخدام فئة GraphicsenVironment للحصول على مدى ملزمة الشاشة.

ربما e.getlocationonscreen ()؛ سيعمل؟ انها فقط ل Java 1.6.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top