Torna indietro   Hardware Upgrade Forum > Software > Programmazione

Recensione REDMI Note 17 Pro: il midrange con batteria da 8.340 mAh e ricarica veloce
Recensione REDMI Note 17 Pro: il midrange con batteria da 8.340 mAh e ricarica veloce
REDMI Note 17 Pro porta in fascia media una batteria da 8.340 mAh con ricarica HyperCharge a 67W, un display AMOLED da 6,83 pollici capace di picchi di luminosità molto elevati e una struttura certificata TÜV SÜD contro cadute e infiltrazioni d'acqua, il tutto racchiuso in una scocca da 223 grammi. Lo abbiamo provato per diversi giorni tra fotocamera, prestazioni, autonomia e prezzo sul mercato italiano
Insta360 Luna Ultra: la potenza del sensore da 1 pollice incontra la portabilità estrema
Insta360 Luna Ultra: la potenza del sensore da 1 pollice incontra la portabilità estrema
Insta360 Luna Ultra integra un sensore da 1 pollice 8K, ottiche Leica e triplo chip IA. Tra schermo OLED rimovibile, workflow I-Log a 10 bit e stabilizzazione a tre assi, analizziamo le doti tecniche di una gimbal camera pensata per i professionisti
Marvel's Wolverine, la recensione: Logan torna protagonista in un'avventura brutale e intensa
Marvel's Wolverine, la recensione: Logan torna protagonista in un'avventura brutale e intensa
Marvel's Wolverine porta Logan in un'avventura inedita, violenta e fortemente narrativa, costruita attorno alla sua natura di combattente e al difficile rapporto con il proprio passato. Insomniac Games punta su combattimenti spettacolari, progressione e personalizzazione, inserendo l'azione in un mondo segnato dalla persecuzione dei mutanti. Un viaggio intenso, che alterna mattanza, esplorazione e momenti sorprendentemente emotivi.
Tutti gli articoli Tutte le news

Vai al Forum
Rispondi
 
Strumenti
Old 22-07-2010, 14:54   #1
banryu79
Senior Member
 
L'Avatar di banryu79
 
Iscritto dal: Oct 2007
Città: Padova
Messaggi: 4131
[JAVA-Swing] Dubbio su invokeLater

Salve,
ho un'implementazione casereccia di un JFrame che usa un content pane customizzato in modo tale da sembrare trasparente.
Il content pane in pratica, fa una "foto" del desktop e la usa, traslata a dovere, come sfondo del frame.

Ovviamente allo scatenarsi di certi eventi è neccessario "rifotografare" il desktop per aggiornare lo sfondo, in modo che tutto sembri sempre coerente.
Tralasciando questioni secondarie, la classe che implementa questo content pane "trasparente" è dotata di una classe interna ScreenshotUpdater, che in pratica è un thread che ciclicamente controlla se è neccessario fare la nuova foto al desktop, e in tale caso deve:
1 - spostare il frame trasparente fuori dall'area visibile dello schermo;
2 - fare la foto allo schermo;
3 - rimettere il frame dove si trovava.

Io eseguo il punto 1 accodando l'operazione nell'EDT con SwingUtilities.invokeAndWait() e la mia aspettativa era che tale operazione venisse completata in toto (frame *effettivamente* mosso) prima che venisse eseguito il punto 2, ma pare non sia *sempre* così.

Per ovviare ho dovuto aggiungere tra 1 e 2 una chiamata a sleep sul thread corrente.

Questo è il codice (in marroncino la parte contingente, il resto serve per capire il contesto):
Codice:
   /**
     * Encapsulate calls on the EDT to setLocation.
     * Used to move the frame associated with this
     * component out of visible desktop area before
     * taking a screenshot.
     */
    class SetLocationCaller implements Runnable
    {
        final int X;
        final int Y;

        SetLocationCaller(Point p) {
            this(p.x, p.y);
        }

        SetLocationCaller(int x, int y) {
            X = x;
            Y = y;
        }

        public void run() {
            frame.setLocation(X, Y);
        }
    }

    // TASK: Improve ScreenshotUpdater
    // Also all frame children of this 'frame' must be considered
    // when moving out of desktop visible area at snapshot-time.

    /**
     * Used to encapsulate the task of taking a screenshot.
     * It should always run out of the EDT, and need to syncrho/wait
     * correctly with SetLocationCaller, for taking snapshot correctly.
     */
    class ScreenshotUpdater implements Runnable
    {
        SetLocationCaller moveBack, moveOut;

        private void pauseThread(long millis) {
            try {
                Thread.sleep(millis);
            } catch (InterruptedException ignored) {}
        }

        public void run() {
            while (frameIsNotClosing) {
                pauseThread(75);
                long now = System.currentTimeMillis();
                if (refreshRequested && ((now - lastUpdate) > 500)) {
                    if (frame.isVisible()) {
                        moveBack = new SetLocationCaller(frame.getLocation());
                        moveOut = new SetLocationCaller(-frame.getWidth(),
                                                        -frame.getHeight());
                        try {
                            SwingUtilities.invokeAndWait(moveOut);
                        } catch (Exception ignored) {}
                        pauseThread(10); // nedeed, invokeAndWait it's not enough!
                        takeScreenSnapshot();
                        SwingUtilities.invokeLater(moveBack);
                    }
                    lastUpdate = now;
                    refreshRequested = false;
                }
            }
        }
    }
Ma invokeAndWait non è bloccante?
E il run() del runnable che esegue dovrebbe venire eseguito tutto; l'unica cosa che fa è una chiamata a setLocation: ho provato a cercare nei sorgenti per vedere se setLocation non combinasse qualcosa di strano (magari l'esecuzione effettiva è asincrona) ma non ne sono venuto a capo.

Qualcuno vede l'errore?
__________________

As long as you are basically literate in programming, you should be able to express any logical relationship you understand.
If you don’t understand a logical relationship, you can use the attempt to program it as a means to learn about it.
(Chris Crawford)

Ultima modifica di banryu79 : 22-07-2010 alle 15:01.
banryu79 è offline   Rispondi citando il messaggio o parte di esso
Old 23-07-2010, 15:06   #2
banryu79
Senior Member
 
L'Avatar di banryu79
 
Iscritto dal: Oct 2007
Città: Padova
Messaggi: 4131
up
__________________

As long as you are basically literate in programming, you should be able to express any logical relationship you understand.
If you don’t understand a logical relationship, you can use the attempt to program it as a means to learn about it.
(Chris Crawford)
banryu79 è offline   Rispondi citando il messaggio o parte di esso
Old 29-07-2010, 17:40   #3
banryu79
Senior Member
 
L'Avatar di banryu79
 
Iscritto dal: Oct 2007
Città: Padova
Messaggi: 4131
ecchecazz... up!
__________________

As long as you are basically literate in programming, you should be able to express any logical relationship you understand.
If you don’t understand a logical relationship, you can use the attempt to program it as a means to learn about it.
(Chris Crawford)
banryu79 è offline   Rispondi citando il messaggio o parte di esso
Old 29-07-2010, 17:51   #4
PGI-Bis
Senior Member
 
L'Avatar di PGI-Bis
 
Iscritto dal: Nov 2004
Città: Tra Verona e Mantova
Messaggi: 4553
setPosition per una finestra non sposta la finestra, invia una richiesta al window manager del sistema operativo di spostare la finestra. La richiesta è eseguita da un altro processo, senza callback. Lo sleep è una sincronizzazione ottimistica. La via corretta sarebbe inviare la richiesta e attendere finchè la finestra effettivamente abbia raggiunto la posizione desiderata (se non erro puoi usare un component listener per sapere quando la finestra si sposta).
__________________
Uilliam Scecspir ti fa un baffo? Gioffri Cioser era uno straccione? E allora blogga anche tu, in inglese come me!
PGI-Bis è offline   Rispondi citando il messaggio o parte di esso
Old 30-07-2010, 08:37   #5
banryu79
Senior Member
 
L'Avatar di banryu79
 
Iscritto dal: Oct 2007
Città: Padova
Messaggi: 4131
Quote:
setPosition per una finestra non sposta la finestra, invia una richiesta al window manager del sistema operativo di spostare la finestra.
Grazie PGI.
Proprio non era passato manco per l'anticamera del cervello

Ho corretto così, e funziona:
Codice:
    /**
     * Encapsulate calls on the EDT to setLocation.
     * Used to move the frame associated with this
     * component out of visible desktop area before
     * taking a screenshot.
     */
    class CallSetLocation implements Runnable
    {
        final int X;
        final int Y;

        CallSetLocation(Point p) {
            this(p.x, p.y);
        }

        CallSetLocation(int x, int y) {
            X = x;
            Y = y;
        }

        public void run() {
            frame.setLocation(X, Y);
        }
    }

    /**
     * Used to encapsulate the task of taking a screenshot.
     * It should always run out of the EDT, and need to syncrho/wait
     * correctly with CallSetLocation, for taking snapshot correctly.
     */
    class ScreenshotUpdater extends ComponentAdapter implements Runnable
    {
        CallSetLocation moveBack, moveOut;
        boolean movedOutForScreenshot;

        ScreenshotUpdater() {
            frame.addComponentListener(this);
        }

        private void pauseThread(long millis) {
            try {
                Thread.sleep(millis);
            } catch (InterruptedException ignored) {}
        }

        public void run() {
            while (frameIsNotClosing) {
                pauseThread(75);
                long now = System.currentTimeMillis();
                if (refreshRequested && ((now - lastUpdate) > 500)) {
                    if (frame.isVisible()) {
                        moveBack = new CallSetLocation(frame.getLocation());
                        moveOut = new CallSetLocation(-frame.getWidth(),
                                                      -frame.getHeight());
                        movedOutForScreenshot = true;
                        SwingUtilities.invokeLater(moveOut);
                        // from here:
                        // moveBack is then called in componentMoved.
                    }
                    lastUpdate = now;
                    refreshRequested = false;
                }
            }
        }

        @Override 
        public void componentMoved(ComponentEvent e) {
            if (movedOutForScreenshot) {
                movedOutForScreenshot = false;
                takeScreenSnapshot();
                moveBack.run(); // we already are on the EDT here.
            }
        }
    }
__________________

As long as you are basically literate in programming, you should be able to express any logical relationship you understand.
If you don’t understand a logical relationship, you can use the attempt to program it as a means to learn about it.
(Chris Crawford)

Ultima modifica di banryu79 : 30-07-2010 alle 08:51.
banryu79 è offline   Rispondi citando il messaggio o parte di esso
 Rispondi


Recensione REDMI Note 17 Pro: il midrange con batteria da 8.340 mAh e ricarica veloce Recensione REDMI Note 17 Pro: il midrange con ba...
Insta360 Luna Ultra: la potenza del sensore da 1 pollice incontra la portabilità estrema Insta360 Luna Ultra: la potenza del sensore da 1...
Marvel's Wolverine, la recensione: Logan torna protagonista in un'avventura brutale e intensa Marvel's Wolverine, la recensione: Logan torna p...
DJI Romo 2: tante novità lo rendono un robot completo DJI Romo 2: tante novità lo rendono un ro...
Sony Bravia 9 II: il True RGB alla prova, dove l'LCD sfida l'OLED Sony Bravia 9 II: il True RGB alla prova, dove l...
Space Pioneer starebbe realizzando un pr...
SpaceX ritirerà ''a breve'' il Fa...
La Luna ha un nuovo cratere di grandi di...
ROG Cronox: ASUS alza l'asticella dei ca...
Lenovo annuncia nuovi sistemi per la vir...
M6 e M5 Ultra, i primi benchmark conferm...
La nuova falla della cybersecurity &egra...
The Blood of Dawnwalker, il sequel potre...
Colpiti i data center Amazon: irrecupera...
Google Wallet, nuova interfaccia in arri...
iPhone Duo, problemi di produzione per i...
Firefox diventa più veloce con PDF e JPE...
WhatsApp, arriva su iOS la nuova scorcia...
Snap presenta Specs: realtà aumentata, c...
SteamOS verso un cambiamento epocale: ar...
Chromium
GPU-Z
OCCT
LibreOffice Portable
Opera One Portable
Opera One 106
CCleaner Portable
CCleaner Standard
Cpu-Z
Driver NVIDIA GeForce 546.65 WHQL
SmartFTP
Trillian
Google Chrome Portable
Google Chrome 120
VirtualBox
Tutti gli articoli Tutte le news Tutti i download

Strumenti

Regole
Non Puoi aprire nuove discussioni
Non Puoi rispondere ai messaggi
Non Puoi allegare file
Non Puoi modificare i tuoi messaggi

Il codice vB è On
Le Faccine sono On
Il codice [IMG] è On
Il codice HTML è Off
Vai al Forum


Tutti gli orari sono GMT +1. Ora sono le: 23:12.


Powered by vBulletin® Version 3.6.4
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.
Served by www3v