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();
}
}
Why not use a JDialog or JFrame for this purpose?
I gave you the answer in your last question (http://stackoverflow.com/questions/6475320/how-to-set-the-orientation-of-jtextarea-from-right-to-left-inside-joptionpane). The concept is the same. Think about the solution given and understand how it works so you can apply it in different situations.
If you still don't understand the suggestion then see DialogFocus for reusable code.
You could let the
txt2
component request focus once it is added by overridingaddNotify
. Like this:Here's a fully functional / tested version of your program: