创建时如何在JOptionPane中将焦点设置在特定的JTextfield上? [英] How to set focus on specific JTextfield inside JOptionPane when created?

查看:121
本文介绍了创建时如何在JOptionPane中将焦点设置在特定的JTextfield上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

这篇关于创建时如何在JOptionPane中将焦点设置在特定的JTextfield上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆