java:在表单加载时将焦点设置为textfield

时间:2012-06-30 03:44:09

标签: java swing netbeans

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

4 个答案:

答案 0 :(得分:3)

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

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

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

  

现已弃用这些方法。不鼓励使用另一种方法requestFocus,因为它试图将焦点放在组件的窗口上,这并不总是可行的。从JDK 1.4开始,您应该使用requestFocusInWindow方法,该方法不会尝试使组件的窗口集中。该方法返回一个布尔值,指示方法是否成功。

这将是一个粗略的例子,但我认为你可以用它来开始:

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
}

答案 1 :(得分:0)

我使用了textfield.requestFocusInWindow();上面给出的行,在包含许多表单元素(其中几个是文本字段)的GUI中。它很棒。只需替换&#34; textfield&#34;无论你给出的元素有什么名称。在我的情况下它是repId。所以我使用repID.requestFocusInWindow();并将该行放在我的ENTER按钮处理程序的底部。现在,当用户在表单字段中键入数据并按ENTER键时,焦点将返回到第一个文本字段:&#34; repID&#34;。谢谢你的回答。

答案 2 :(得分:0)

另外请注意,请确保在requestFocusInWindow()方法之后放置pack()方法。当我在requestFocusInWindow()方法之前放置pack()方法时,它无法正常工作。我在requestFocusInWindow()方法之后放置了pack()方法并且它有效。这样的小事只会让我们的生活变得更加容易n00bs。

答案 3 :(得分:0)

我希望这个例子对您有帮助:

        JTextField inputText = new JTextField(20);

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