码迷,mamicode.com
首页 > Windows程序 > 详细

e614. Setting the Initial Focused Component in a Window

时间:2018-09-06 10:58:39      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:method   owa   setting   bsp   public   focus   red   enter   rem   

There is no straightforward way to set the initial focused component in a window. The typical method is to add a window listener to listen for the window opened event and then make the desired component request the focus.

    // Create frame and three buttons
    JFrame frame = new JFrame();
    JButton component1 = new JButton("1");
    JButton component2 = new JButton("2");
    JButton component3 = new JButton("3");
    
    // Set component with initial focus; must be done before the frame is made visible
    InitialFocusSetter.setInitialFocus(frame, component2);
    
    class InitialFocusSetter {
        public static void setInitialFocus(Window w, Component c) {
            w.addWindowListener(new FocusSetter(c));
        }
    
        public static class FocusSetter extends WindowAdapter {
            Component initComp;
            FocusSetter(Component c) {
                initComp = c;
            }
            public void windowOpened(WindowEvent e) {
                initComp.requestFocus();
    
                // Since this listener is no longer needed, remove it
                e.getWindow().removeWindowListener(this);
            }
        }
    }

 

Related Examples

e614. Setting the Initial Focused Component in a Window

标签:method   owa   setting   bsp   public   focus   red   enter   rem   

原文地址:https://www.cnblogs.com/borter/p/9596095.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!