简体   繁体   English

java:表单加载时将焦点设置为文本字段

[英]java:set the focus to textfield when form load

I have a jTextfield.我有一个 jTextfield。 I want to set focus on this when the form is loaded.我想在加载表单时将重点放在这个上。 How can I do this?我怎样才能做到这一点? I am using Netbeans.我正在使用 Netbeans。 I use requestFocus() but it is not working.我使用requestFocus()但它不起作用。

This link might be helpful for you: How to Use the Focus Subsystem此链接可能对您有所帮助: 如何使用焦点子系统

I would suggest that you use requestFocusInWindow() instead of requestFocus() to achieve the desired functionality.我建议您使用 requestFocusInWindow() 而不是 requestFocus() 来实现所需的功能。

The reason: (from the same link)原因:(来自同一个链接)

These methods are now deprecated.这些方法现已弃用。 Another method, requestFocus, is discouraged because it tries to give the focus to the component's window, which is not always possible.另一种方法 requestFocus 是不鼓励的,因为它试图将焦点赋予组件的窗口,这并不总是可行的。 As of JDK 1.4, you should instead use the requestFocusInWindow method, which does not attempt to make the component's window focused.从 JDK 1.4 开始,您应该改为使用 requestFocusInWindow 方法,该方法不会尝试使组件的窗口获得焦点。 The method returns a boolean value indicating whether the method succeeded.该方法返回一个布尔值,指示该方法是否成功。

This would be a crude example, but I think you can use this to get started:这将是一个粗略的示例,但我认为您可以使用它来开始:

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class TestFrame extends JFrame {

    JButton button1;
    JButton button2;

    JTextField textField;

    public TestFrame() {
        initComponents();
    }

    private void initComponents(){
        button1 = new JButton("Button 1");
        button2 = new JButton("Button 2");
        textField = new JTextField();

        button1.setPreferredSize(new Dimension(100,20));
        button2.setPreferredSize(new Dimension(100,20));
        textField.setPreferredSize(new Dimension(300,20));

        this.setSize(new Dimension(600, 300));
        this.setLayout(new BorderLayout());

        getContentPane().add(button1, BorderLayout.WEST);
        getContentPane().add(button2, BorderLayout.CENTER);
        getContentPane().add(textField, BorderLayout.EAST);
        this.pack();
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //This will set focus on the text field
        textField.requestFocusInWindow();
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TestFrame();
            }
        });
    }
}

LATEST EDIT : FOR NETBEANS最新编辑:对于 NETBEANS

CODE USED :使用的代码:

package focusexample;

public class FocusExample extends javax.swing.JFrame {

    public FocusExample() {
        initComponents();
        jTextField1.requestFocusInWindow();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("jButton1");

        jButton2.setText("jButton2");

        jTextField1.setText("jTextField1");

        jTextField2.setText("jTextField2");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(87, 87, 87)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jTextField1))
                .addGap(69, 69, 69)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jTextField2))
                .addContainerGap(98, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(95, 95, 95)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addGap(58, 58, 58)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(104, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>


    public static void main(String args[]) {

        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FocusExample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FocusExample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FocusExample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FocusExample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new FocusExample().setVisible(true);                
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration
}

I used the textfield.requestFocusInWindow();我使用了 textfield.requestFocusInWindow(); line given above, in a GUI that contains a number of form elements (several of which are textfields).上面给出的行,在包含许多表单元素(其中几个是文本字段)的 GUI 中。 It works great.它工作得很好。 Just replace "textfield" with whatever name you have given the element in question.只需将“文本字段”替换为您为相关元素指定的任何名称。 In my case it's repId.就我而言,它是repId。 So I use repID.requestFocusInWindow();所以我使用 repID.requestFocusInWindow(); and put the line at the bottom of my ENTER button handler.并将该行放在我的 ENTER 按钮处理程序的底部。 Now, when a user types data into the form fields and presses ENTER, focus returns to the first textfield: "repID".现在,当用户在表单字段中键入数据并按 ENTER 键时,焦点将返回到第一个文本字段:“repID”。 Thanks for the answer.感谢你的回答。

Also of note, make sure you place the requestFocusInWindow() method after the pack() method.另请注意,请确保将requestFocusInWindow()方法放在pack()方法之后。 When I was placing the requestFocusInWindow() method before the pack() method, it didn't work.当我将requestFocusInWindow()方法放在pack()方法之前时,它不起作用。 I placed the requestFocusInWindow() method after the pack() method and it worked.我在pack()方法之后放置了requestFocusInWindow() pack()方法并且它起作用了。 Little things like that just make life so much easier for us n00bs.像这样的小事情只会让我们的生活变得更轻松。

I hope this example will help you:我希望这个例子能帮助你:

        JTextField inputText = new JTextField(20);

        frame.addWindowFocusListener(new WindowAdapter() {
        public void windowGainedFocus(WindowEvent e) {
            inputText.requestFocusInWindow();
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM