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

Eng*_*uad 4 java swing jtextfield setfocus

我想将焦点放在一个特定的JTextField上,它作为对象消息传递给JOptionPane.这是我的代码(我希望专注于txt2,但焦点始终在于txt1):

import java.awt.*;
import java.util.*;
import javax.swing.*;
public class TextArea extends JPanel
{
    private JTextArea txt1 = new JTextArea();
    private JTextArea txt2 = new JTextArea();
    public TextArea()
    {
        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);
        txt2.requestFocus();
    }
    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 TextArea().display();
    }
}
Run Code Online (Sandbox Code Playgroud)

aio*_*obe 6

txt2通过覆盖添加组件后,您可以让组件请求焦点addNotify.像这样:

private JTextArea txt2 = new JTextArea() {
    public void addNotify() {
        super.addNotify();
        requestFocus();
    }
};
Run Code Online (Sandbox Code Playgroud)

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

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();
    }
}
Run Code Online (Sandbox Code Playgroud)