Java:如何注册一个监听 JFrame 运动的监听器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2427815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: how to register a listener that listen to a JFrame movement
提问by cocotwo
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.
如何跟踪 JFrame 本身的运动?我想注册一个监听器,每次都会被回调JFrame.getLocation()并返回一个新值。
EDITHere'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();
}
}
回答by Michael Myers
Using addComponentListener()with a ComponentAdapter:
使用addComponentListener()了ComponentAdapter:
jf.addComponentListener(new ComponentAdapter() {
public void componentMoved(ComponentEvent e) {
updateText(jf, jl);
}
});
回答by Steve McLeod
JFrame jf = new JFrame();
jf.addComponentListener(new ComponentListener() {...});
is what you are looking for, I think.
是你要找的,我想。
回答by Peter Lang
You can register a HierarchyBoundsListeneron your JFrame, or use a ComponentListeneras suggested by others.
您可以HierarchyBoundsListener在您的上注册 a JFrame,也可以ComponentListener按照其他人的建议使用 a 。
jf.getContentPane().addHierarchyBoundsListener(new HierarchyBoundsAdapter() {
@Override
public void ancestorMoved(HierarchyEvent e) {
updateText(jf, jl);
}
});

