Java: how to register a listener that listen to a JFrame movement

六月ゝ 毕业季﹏ 提交于 2019-12-04 04:39:11

问题


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:


JFrame jf = new JFrame();
jf.addComponentListener(new ComponentListener() {...});

is what you are looking for, I think.




回答2:


Using addComponentListener() with a ComponentAdapter:

jf.addComponentListener(new ComponentAdapter() {
    public void componentMoved(ComponentEvent e) {
        updateText(jf, jl);
    }
});



回答3:


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);
    }
});


来源:https://stackoverflow.com/questions/2427815/java-how-to-register-a-listener-that-listen-to-a-jframe-movement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!