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

标签 java swing netbeans

我有一个 jTextfield。我想在加载表单时将重点放在这上面。我怎样才能做到这一点?我正在使用 Netbeans。我使用 requestFocus() 但它不起作用。

最佳答案

此链接可能对您有帮助:How to Use the Focus Subsystem

我建议您使用 requestFocusInWindow() 而不是 requestFocus() 来实现所需的功能。

原因:(来自同一个链接)

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. As of JDK 1.4, you should instead use the requestFocusInWindow method, which does not attempt to make the component's window focused. The method returns a boolean value indicating whether the method succeeded.

这将是一个粗略的示例,但我认为您可以使用它开始:

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

最新编辑:针对 NETBEANS

使用的代码:

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
}

关于java: 表单加载时将焦点设置到文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11271226/

相关文章:

使用invokelater重新绘制时不会调用Java PaintComponent

Debian Linux 上的 Java 闪屏闪烁

java - 当我尝试检测内存泄漏时分析中的内存大小

Java - toString 到 Color

java - 设置 JList 不可调整大小

java - 在我的 Java 代码中创建的 xlsx 文件无法在 MS Excel 中打开,表示文件格式或文件扩展名无效

java - NetBeans maven 项目中的 Neo4j 2.1.6 Hello World

java - Docx4j 类未找到错误

java - 从 servlet 获取 jsp 页面的 Html

java - 如何在 while 循环条件下操作和随机化变量?