2010-03-11 131 views
3

如何跟踪JFrame本身的运动?我想注册一个听众,每回JFrame.getLocation()就会返回一个新的值。Java:如何注册侦听JFrame运动的侦听器

编辑这里是显示所接受的回答是解决我的问题代码:

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

} 
+0

注意,这不是一个关于面向对象的设计,也没有关于使用或不使用* *决赛等问题是有关如何注册一个回调疑问,可以在每次JFrame的位置发生变化时触发,并且代码片段只是一个快速入侵,充当概念证明以插入正确答案。 – cocotwo 2010-03-11 18:58:31

回答

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

是你在找什么,我想。

1

您可以在JFrame注册一个HierarchyBoundsListener,或使用ComponentListener别人的建议。

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

    @Override 
    public void ancestorMoved(HierarchyEvent e) { 
     updateText(jf, jl); 
    } 
}); 
7

使用addComponentListener()ComponentAdapter

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

+1:我会接受你的答案,因为你提供的链接和一个工作示例:) – 2010-03-11 19:12:19

+0

@mmyers:非常感谢,+1 – cocotwo 2010-03-11 19:12:42

+0

我会接受无论哪个答案首先发布。没有必要提供到API的链接。答案是使用ComponentListener。每个程序员都应该可以直接访问API,并且应该知道如何使用它。如果你想提供一个链接,那么它应该是关于“如何编写组件监听器”的Swing教程。这样,当海报看起来那里时,他们也会找到关于如何为所有其他Swing事件侦听器编写侦听器的部分。让人们有自己的工具来解决问题,而不是他们期待我们一直提供答案。 – camickr 2010-03-11 20:34:46