Setting component focus in JOptionPane.showOptionDialog()

前端 未结 8 1508
广开言路
广开言路 2020-12-10 13:59

In order to have custom button captions in an input dialog, I created the following code:

String key = null;
JTextField txtKey = new JTextField();        
in         


        
8条回答
  •  遥遥无期
    2020-12-10 14:01

    I found a solution ! Very primitive, but works.

    Just jump to the field by java.awt.Robot using key "Tab".
    I've created utils method calls "pressTab(..)" For example:

    GuiUtils.pressTab(1);   <------------- // add this method before popup show
    
    int result = JOptionPane.showConfirmDialog(this, inputs, "Text search window", JOptionPane.PLAIN_MESSAGE);
    if (result == JOptionPane.OK_OPTION)
    {
        
    }
    

    If you should press multiple times on "Tab" to get your Component you can use below method:

    GUIUtils.pressTab(3);
    

    Definition:

    public static void pressTab(int amountOfClickes)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                try
                {
                    Robot robot = new Robot();
                    int i = amountOfClickes;
                    while (i-- > 0)
                    {
                        robot.keyPress(KeyEvent.VK_TAB);
                        robot.delay(100);
                        robot.keyRelease(KeyEvent.VK_TAB);
                    }
                }
                catch (AWTException e)
                {
                    System.out.println("Failed to use Robot, got exception: " + e.getMessage());
                }
            }
        });
    }
    

    If your Component location is dynamic, you can run over the while loop without limitation, but add some focus listener on the component, to stop the loop once arrived to it.

提交回复
热议问题