Setting the focus to a text field

前端 未结 9 1771
日久生厌
日久生厌 2020-12-16 14:50

I have an application developed in netbeans and I want to set the focus to a certain jTextField when a panel is displayed. I have read a number of post and have

相关标签:
9条回答
  • 2020-12-16 14:54

    None of the above worked for me, because my window is a JPopupMenu.

    What did work was this:

    addAncestorListener(new AncestorListener() {
        @Override
        public void ancestorAdded(AncestorEvent ae) {
            myEdit.requestFocus();
        }
    
        // ... other ancestor listener methods
    }
    
    0 讨论(0)
  • 2020-12-16 14:54

    This is an easy one:

    textField.setFocus();
    
    0 讨论(0)
  • 2020-12-16 15:01

    In a JFrame or JDialog you can always overwrite the setVisible() method, it works well. I haven't tried in a JPanel, but can be an alternative.

    @Override
    public void setVisible(boolean value) {
        super.setVisible(value);
        control.requestFocusInWindow();
    }
    
    0 讨论(0)
  • 2020-12-16 15:02

    I have had a similar scenario where I needed to set the focus on a text box within a panel when the panel was shown. The panel was loaded on application startup, so I couldn't set the focus in the constructor. As the panel wasn't being loaded or being given focus on show, this meant that I had no event to fire the focus request from.

    To solve this, I added a global method to my main that called a method in the panel that invoked requestFocusInWindow() on the text area. I put the call to the global method in the button that showed the panel, after the call to show. This meant that the panel would be shown and then the text area assigned the focus after showing the panel. Hope that makes sense and helps!

    Also, you can edit most of the auto-generated code by right clicking on the object in design view and selecting customize code, however I don't think that it allows you to edit panels.

    0 讨论(0)
  • 2020-12-16 15:03

    I have toyed with this for forever, and finally found something that seems to always work!

    textField = new JTextField() {
    
        public void addNotify() {
            super.addNotify();
            requestFocus();
        }
    };
    
    0 讨论(0)
  • 2020-12-16 15:15

    For me the easiest way to get it to work, is to put the component.requestFocus(); line, after the setVisible(true); line, at the bottom of your frame or panel constructor.

    This probably has something to do with asking for the focus, after all components have been created, because creating a new component, after asking for the focus request, will make your component loose te focus, and make the focus go to your newly created component. At least, that's what I assume.

    0 讨论(0)
提交回复
热议问题