且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

创建时如何在JOptionPane中将焦点设置在特定的JTextfield上?

更新时间:2023-01-12 18:21:54

添加了addNotify后,您可以让txt2组件在获得焦点后立即请求焦点.像这样:

You could let the txt2 component request focus once it is added by overriding addNotify. Like this:

private JTextArea txt2 = new JTextArea() {
    public void addNotify() {
        super.addNotify();
        requestFocus();
    }
};


这是您的程序的功能齐全/经过测试的版本:


Here's a fully functional / tested version of your program:

import java.awt.Dimension;
import javax.swing.*;
public class Test extends JPanel {
    private JTextArea txt1 = new JTextArea();
    private JTextArea txt2 = new JTextArea() {
        public void addNotify() {
            super.addNotify();
            requestFocus();
        }
    };

    public Test() {
        setLayout(null);
        setPreferredSize(new Dimension(200, 100));
        txt1.setBounds(20, 20, 220, 20);
        txt2.setBounds(20, 45, 220, 20);
        txt1.setText("Text Field #1");
        txt2.setText("Text Field #2");
        add(txt1);
        add(txt2);
    }

    private void display() {
        Object[] options = { this };
        JOptionPane pane = new JOptionPane();
        pane.showOptionDialog(null, null, "Title", JOptionPane.DEFAULT_OPTION,
                JOptionPane.PLAIN_MESSAGE, null, options, txt2);
    }

    public static void main(String[] args) {
        new Test().display();
    }
}