Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
722 views
in Technique[技术] by (71.8m points)

java - How to set focus on specific JTextfield inside JOptionPane when created?

I want to set the focus on a specific JTextField which is passed to the JOptionPane as Object Message. Here is my code (I want the focus on txt2 but the focus always is on 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();
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...