views:

200

answers:

3

How can you track the movement of a JFrame itself? I'd like to register a listener that would be called back every single time JFrame.getLocation() is going to return a new value.

EDIT Here's a code showing that the accepted answered is solving my problem:

import javax.swing.*;

public class SO {

    public static void main( String[] args ) throws Exception {
        SwingUtilities.invokeAndWait( new Runnable() {
            public void run() {
                final JFrame jf = new JFrame();
                final JPanel jp = new JPanel();
                final JLabel jl = new JLabel();
                updateText( jf, jl );
                jp.add( jl );
                jf.add( jp );
                jf.pack();
                jf.setVisible( true );
                jf.addComponentListener( new ComponentListener() {
                    public void componentResized( ComponentEvent e ) {}
                    public void componentMoved( ComponentEvent e ) {
                        updateText( jf, jl );
                    }
                    public void componentShown( ComponentEvent e ) {}
                    public void componentHidden( ComponentEvent e ) {}
                } );
            }
        } );
    }

    private static void updateText( final JFrame jf, final JLabel jl ) {
        // this method shall always be called from the EDT
        jl.setText( "JFrame is located at: " + jf.getLocation() );
        jl.repaint();
    }

}
+1  A: 

You can register a HierarchyBoundsListener on your JFrame, or use a ComponentListener as suggested by others.

jf.getContentPane().addHierarchyBoundsListener(new HierarchyBoundsAdapter() {

    @Override
    public void ancestorMoved(HierarchyEvent e) {
        updateText(jf, jl);
    }
});
Peter Lang
+2  A: 
JFrame jf = new JFrame();
jf.addComponentListener(new ComponentListener() {...});

is what you are looking for, I think.

Steve McLeod
+3  A: 

Using addComponentListener() with a ComponentAdapter:

jf.addComponentListener(new ComponentAdapter() {
    public void componentMoved(ComponentEvent e) {
        updateText(jf, jl);
    }
});
Michael Myers
+1: I would have accepted your answer since you provided links and a working example :)
Peter Lang
@mmyers: thanks a lot, +1
cocotwo
I would have accepted whichever answer was posted first. There is no need to provide a link to the API. The answer is to use a ComponentListener. Every programmer should have direct access to the API and should know how to use it. If you want to provide a link then it should be to the Swing tutorial on "How to Write a Component Listener". That way when the poster looks there they will also find section on how to write listeners for all other Swing event listeners. Lets give people the tools to solve problems on there own rather than them expecting us to spoon feed the answer all the time.
camickr