0

I'm using a class which extends a JDialog.In the constuctor i'm adding two text fields whose value is read from a properties file and a login button .But the problem is when i run the application the JDialog should automatically setFocus() on the first text field but its not happening until i manually click on the box which is appearing.How can i achieve that .I've searched through many links and tried many things like "setFocus()","requestFocusInWindow()",etc but nothing is working out.

public FormDetails() {

    container = getContentPane();
    layout = new GridBagLayout();
    container.setLayout(layout);
    cons = new GridBagConstraints();
    cons.fill = GridBagConstraints.VERTICAL;
    final ImageIcon imageIcon = new ImageIcon("images/logo.png");
    JLabel pnLabel = new JLabel(imageIcon);
    pnLabel.setPreferredSize(new Dimension(150, 90));

    final JPanel logoPanel = new JPanel() {

        private static final long serialVersionUID = 1L;

        @Override
        public void paintComponent(final Graphics _graphics) {
            super.paintComponent(_graphics);
            Toolkit.getDefaultToolkit().getImage("images/bg_color.jpg");
            setBackground(new Color(7, 164, 217));
        }
    };
    final Box horiz = Box.createHorizontalBox();
    horiz.add(Box.createHorizontalStrut(60));
    horiz.add(pnLabel);
    horiz.add(Box.createHorizontalStrut(61));
    horiz.add(new JLabel());
    logoPanel.add(horiz);
    cons.gridx = 0;
    cons.gridy = 0;
    cons.gridwidth = 5;
    cons.gridheight = 1;
    logoPanel.setBorder(BorderFactory.createMatteBorder(2, 2, 0, 2,Color.BLACK));
    layout.setConstraints(logoPanel, cons);
    container.add(logoPanel);

    final JPanel hPanel = new JPanel() {
        private static final long serialVersionUID = 1L;
        @Override
        public void paintComponent(final Graphics _graphics) {
            super.paintComponent(_graphics);
            final Image backgroundImage = Toolkit.getDefaultToolkit().getImage("images/c_top.gif");
            _graphics.drawImage(backgroundImage, 0, 0, this.getWidth(), this.getHeight(), this);
        }
    };
    heading = new JLabel("                            ");
    heading.setFont(new Font("Times New Roman", Font.BOLD, 14));
    heading.setForeground(Color.RED);
    heading.setPreferredSize(new Dimension(271, 10));
    hPanel.add(heading);
    cons.gridx = 0;
    cons.gridy = 1;
    cons.gridwidth = 5;
    cons.gridheight = 1;
    hPanel.setBorder(BorderFactory.createMatteBorder(0, 2, 0, 2,Color.BLACK));
    layout.setConstraints(hPanel, cons);
    container.add(hPanel);

    final JPanel blPanel = new JPanel() {
        @Override
        public void paintComponent(final Graphics _graphics) {
            super.paintComponent(_graphics);
            final Image backgroundImage = Toolkit.getDefaultToolkit().getImage(
                    "images/below_heading.jpg");
            _graphics.drawImage(backgroundImage, 0, 0, this.getWidth(), this.getHeight(), this);
        }
    };
    final Box horiz5 = Box.createHorizontalBox();
    horiz5.add(Box.createHorizontalStrut(135));
    horiz5.add(new JLabel());
    horiz5.add(Box.createHorizontalStrut(136));
    horiz5.add(new JLabel());
    blPanel.add(horiz5);
    cons.gridx = 0;
    cons.gridy = 2;
    cons.gridwidth = 5;
    cons.gridheight = 2;
    blPanel.setBorder(BorderFactory.createMatteBorder(0, 2, 0, 2,Color.BLACK));
    layout.setConstraints(blPanel, cons);
    container.add(blPanel);

    final JPanel aPanel = new JPanel() {

        @Override
        public void paintComponent(final Graphics _graphics) {
            super.paintComponent(_graphics);
            final Image backgroundImage = Toolkit.getDefaultToolkit().getImage(
                    "images/c_top1.gif");
            _graphics.drawImage(backgroundImage, 0, 0, this.getWidth(), this
                    .getHeight(), this);
        }
    };
    agentId = new JLabel("<html><span style='font-size:10px'>"+"SIP Extension:"+"</span></html>");
    agentId.setFont(new Font("Verdana", Font.PLAIN, 12));
    agentId.setLayout(new FlowLayout(FlowLayout.LEFT));
    agentId.setForeground(Color.DARK_GRAY);
    extText = new JTextField(sipExtension,10);
    extText.setCaretPosition(sipExtension.length());
    extText.requestFocus();
    if(extText.getActionListeners().length < 1){
        extText.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(final ActionEvent _actionEvent) {
                if (_actionEvent.getSource() == extText){
                        button.doClick();
                    else{
                        pwdText.requestFocusInWindow();
                    }
                }
            }
        });
    }

    final Box horiz1 = Box.createHorizontalBox();
    horiz1.add(Box.createHorizontalStrut(18));
    horiz1.add(agentId);
    horiz1.add(Box.createHorizontalStrut(7));
    horiz1.add(extText);
    horiz1.add(Box.createHorizontalStrut(36));
    horiz1.add(new JLabel());
    aPanel.add(horiz1);
    cons.gridx = 0;
    cons.gridy = 4;
    cons.gridwidth = 5;
    cons.gridheight = 1;

    aPanel.setBorder(BorderFactory.createMatteBorder(0, 2, 0, 2,
            Color.BLACK));

    layout.setConstraints(aPanel, cons);
    container.add(aPanel);

    if(sipEnable){
        final JPanel pwdPanel = new JPanel() {

            private static final long serialVersionUID = 1L;
            @Override
            public void paintComponent(final Graphics _graphics) {
                super.paintComponent(_graphics);
                final Image backgroundImage = Toolkit.getDefaultToolkit().getImage(
                        "images/c_middle.gif");
                _graphics.drawImage(backgroundImage, 0, 0, this.getWidth(), this
                        .getHeight(), this);
                super.repaint();
            }
        };
        agentPassword = new JLabel();
        agentPassword.setText("Password:");
        agentPassword.setFont(new Font("Verdana", Font.PLAIN, 12));
        agentPassword.setLayout(new FlowLayout(FlowLayout.LEFT));
        agentPassword.setForeground(Color.DARK_GRAY);
        pwdText = new JPasswordField(10);

        if(pwdText.getActionListeners().length < 1){

            pwdText.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(final ActionEvent _actionEvent) {
                    if (_actionEvent.getSource() == pwdText) {
                        button.doClick();
                    }
                }
            });
        }

        final Box horiz8 = Box.createHorizontalBox();
        horiz8.add(Box.createHorizontalStrut(18));
        horiz8.add(agentPassword);
        horiz8.add(Box.createHorizontalStrut(35));
        horiz8.add(pwdText);
        horiz8.add(Box.createHorizontalStrut(37));
        horiz8.add(new JLabel());
        pwdPanel.add(horiz8);

        cons.gridx = 0;
        cons.gridy = 5;
        cons.gridwidth = 10;
        cons.gridheight = 1;

        pwdPanel.setBorder(BorderFactory.createMatteBorder(0, 2, 0, 2,
                Color.BLACK));

        layout.setConstraints(pwdPanel, cons);
        container.add(pwdPanel);
        super.repaint();
    }

    JPanel bPanel = new JPanel() {

        private static final long serialVersionUID = 1L;

        @Override
        public void paintComponent(final Graphics _graphics) {
            super.paintComponent(_graphics);
            final Image backgroundImage = Toolkit.getDefaultToolkit().getImage(
                    "images/c_middle.gif");
            _graphics.drawImage(backgroundImage, 0, 0, this.getWidth(), this
                    .getHeight(), this);
            super.repaint();
        }
    };

    agentName = new JLabel("<html><span style='font-size:10px'>"+"CRM ID:"+"</span></html>");
    agentName.setFont(new Font("Verdana", Font.PLAIN, 12));
    agentName.setForeground(Color.DARK_GRAY);
    idText = new JTextField(10);
    idText.setText(crmId);
    idText.setEditable(false);
    if(idText.getActionListeners().length < 1){
        idText.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (e.getSource() == idText) {
                    button.doClick();
                }
            }
        });
    }
    final Box horiz2 = Box.createHorizontalBox();
    horiz2.add(Box.createHorizontalStrut(24));
    horiz2.add(agentName);
    horiz2.add(Box.createHorizontalStrut(43));
    horiz2.add(idText);
    horiz2.add(Box.createHorizontalStrut(37));
    horiz2.add(new JLabel(""));
    horiz2.add(new JLabel(""));
    bPanel.add(horiz2);
    cons.gridx = 0;
    cons.gridy = 6;
    cons.gridwidth = 7;
    cons.gridheight = 1;
    bPanel.setBorder(BorderFactory.createMatteBorder(0, 2, 0, 2,Color.BLACK));
    layout.setConstraints(bPanel, cons);
    container.add(bPanel);

    final JPanel blPanel1 = new JPanel() {
        private static final long serialVersionUID = 1L;

        @Override
        public void paintComponent(final Graphics _graphics) {
            super.paintComponent(_graphics);
            final Image backgroundImage = Toolkit.getDefaultToolkit().getImage(
                    "images/up_button.jpg");
            _graphics.drawImage(backgroundImage, 0, 0, this.getWidth(), this
                    .getHeight(), this);
        }
    };
    final Box horiz6 = Box.createHorizontalBox();
    horiz6.add(Box.createHorizontalStrut(135));
    horiz6.add(new JLabel());
    horiz6.add(Box.createHorizontalStrut(136));
    horiz6.add(new JLabel());
    blPanel1.add(horiz6);
    cons.gridx = 0;
    cons.gridy = 6;
    cons.gridwidth = 5;
    cons.gridheight = 2;
    blPanel1.setBorder(BorderFactory.createMatteBorder(0, 2, 0, 2,Color.BLACK));
    layout.setConstraints(blPanel1, cons);
    container.add(blPanel1);

    final JPanel cPanel = new JPanel() {
        @Override
        public void paintComponent(final Graphics _graphics) {
            super.paintComponent(_graphics);
            final Image backgroundImage = Toolkit.getDefaultToolkit().getImage(
                    "images/c_middle.gif");

            LOG.debug("::: Drawing backgound ");
            _graphics.drawImage(backgroundImage, 0, 0, this.getWidth(), this
                    .getHeight(), this);
        }
    };
    button = new JButton();
    final ImageIcon buttonLogin = new ImageIcon("images/Login.png");
    button.setIcon(buttonLogin);
    button.setRolloverIcon(new ImageIcon("images/LoginMouseOver.png"));
    button.setToolTipText("Connect");
    button.setBorderPainted(false);
    button.setContentAreaFilled(false);
    button.setPreferredSize(new Dimension(100, 30));
    if(button.getActionListeners().length < 1){
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(final ActionEvent _actionEvent) {

                String extension = extText.getText();
                String sipId = idText.getText();
                if(sipEnable){
                    String agentPwd = String.valueOf(pwdText.getPassword());
                    LogInForm.agentPwd = agentPwd;
                }
                LogInForm.crmId=sipId;
                sipExtension = extension;
                String url = "readAgentname_IP.jsp?agentname=" + sipId
                        + "&extension=" + extension + "&action=login";
            }
        });
    }
    final Box horiz3 = Box.createHorizontalBox();
    horiz3.add(Box.createHorizontalStrut(100));
    horiz3.add(button);
    horiz3.add(Box.createHorizontalStrut(71));
    cPanel.add(horiz3);
    cons.gridx = 0;
    cons.gridy = 8;
    cons.gridwidth = 5;
    cons.gridheight = 1;
    cPanel.setBorder(BorderFactory.createMatteBorder(0, 2, 0, 2,Color.BLACK)); //changed 31-03-2015

    layout.setConstraints(cPanel, cons);
    container.add(cPanel);

    final JPanel linkPanel = new JPanel() {
        @Override
        public void paintComponent(final Graphics _graphics) {
            super.paintComponent(_graphics);
            final Image backgroundImage = Toolkit.getDefaultToolkit().getImage(
                    "images/c_bott.gif");
            _graphics.drawImage(backgroundImage, 0, 0, this.getWidth(), this
                    .getHeight(), this);
            super.repaint();
        }
    };
    tncLink = new JButton();
    tncLink.setText("<HTML><FONT size=2><FONT color=\"#666666\">Terms and conditions</FONT></FONT></HTML>");
    tncLink.addActionListener(new ActionListener() {


        @Override
        public void actionPerformed(final ActionEvent _actionEvent) {
        //performing some action
            }
    });
    tncLink.setBorderPainted(false);
    tncLink.setOpaque(false);
    tncLink.setBackground(Color.WHITE);


    settingButton = new JButton(new ImageIcon("images/setting_icon.png"));
    settingButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(final ActionEvent _actionEvent) {
            //performing some action
        }
    });
    settingButton.setBorderPainted(false);
    settingButton.setOpaque(false);
    settingButton.setBackground(Color.WHITE);
    settingButton.setToolTipText("Settings");

    final Box horiz7 = Box.createHorizontalBox();
    horiz7.add(Box.createHorizontalStrut(78));
    horiz7.add(tncLink);
    horiz7.add(settingButton);

    linkPanel.add(horiz7);
    cons.gridx = 0;
    cons.gridy = 9;//changed 31-03-2015

    cons.gridwidth = 5;
    cons.gridheight = 1;
    linkPanel.setBorder(BorderFactory.createMatteBorder(0, 2, 2, 2,Color.BLACK));
    layout.setConstraints(linkPanel, cons);
    container.add(linkPanel);
    super.repaint();

    setTitle("Agent Connect");
    final ImageIcon icon = new ImageIcon(ApplicationConstants.tEnableIcon);
    setIconImage(icon.getImage());
    setResizable(false);

    final Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();

    setBounds((screensize.width - 300) / 2, (screensize.height - 300) / 2,
                302, 345);
    pack();
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            extText.requestFocusInWindow();
        }
    });
    setResizable(false);
    setVisible(true);
    setAlwaysOnTop(true);
    getRootPane().setDefaultButton(button);
}

Here i ve tried the extText..requestFocusInWindow(); but its not working

Ruchika
  • 29
  • 1
  • 4
  • thanks for the reply,but i have already gone through this link still its not working for me in my application and i don't know why. I'm posting a part of my project code here. – Ruchika Oct 12 '15 at 08:19

1 Answers1

1

Without any code it's difficult to find out what's the exact problem. But I'll give it a try.

You need to call requestFocusInWindow between your pack() and setVisible(true) in order to get the focus on the right element when it is getting displayed. Doing it in the constructor might be too early.

Here a short example:

JDialog dialog = new JDialog();
dialog.add(textField1);
dialog.add(textField2);
dialog.pack();
textField1.requestFocusInWindow();
dialog.setVisible(true);

Another way to defer the focus request is to add a window listener to the text field which should get the focus (this can be done in the constructor of dialog):

myDialog.addWindowListener(new WindowAdapter() {
    public void windowOpened(WindowEvent e){
        textField1.requestFocusInWindow();
    }
}); 

Of course if you use this in the constructor you don't need the "myDialog.".

Here an example with a call to requestFocusInWindow between pack and setVisible:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class JDialogFocusDemo extends JFrame {
    JDesktopPane desktop;
    InternalFrameAdapter adapter;
    int frameCount = 0;

    public JDialogFocusDemo() {
        super("JDialogFocusDemo");

        JButton button = new JButton("Open Dialog");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JDialog dialog = new JDialog(JDialogFocusDemo.this, "Dialog", true);
                JPanel panel = new JPanel();
                JTextField textField1 = new JTextField(20);
                JTextField textField2 = new JTextField(20);
                panel.add(textField1);
                panel.add(textField2);
                dialog.add(panel);
                dialog.pack();
                textField2.requestFocusInWindow();
                dialog.setVisible(true);
            }
        });
        add(button);
        setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH);
    }

    private static void createAndShowGUI() {
        JDialogFocusDemo frame = new JDialogFocusDemo();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } 
        catch (UnsupportedLookAndFeelException e) {
           // handle exception
        }
        catch (ClassNotFoundException e) {
           // handle exception
        }
        catch (InstantiationException e) {
           // handle exception
        }
        catch (IllegalAccessException e) {
           // handle exception
        }
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

The main frame only contains a button. When you click on it a dialog is displayed with two text fields and the focus is set in the second text field.

And here's an example using a Window listener:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class JDialogFocusDemo extends JFrame {
    JDesktopPane desktop;
    InternalFrameAdapter adapter;
    int frameCount = 0;

    public JDialogFocusDemo() {
        super("JDialogFocusDemo");

        JButton button = new JButton("Open Dialog");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JDialog dialog = new JDialog(JDialogFocusDemo.this, "Dialog", true);
                JPanel panel = new JPanel();
                final JTextField textField1 = new JTextField(20);
                final JTextField textField2 = new JTextField(20);
                panel.add(textField1);
                panel.add(textField2);
                dialog.add(panel);
                dialog.pack();
                dialog.addWindowListener(new WindowAdapter() {
                    public void windowOpened(WindowEvent e){
                        textField2.requestFocusInWindow();
                    }
                });
                dialog.setVisible(true);
            }
        });
        add(button);
        setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH);
    }

    private static void createAndShowGUI() {
        JDialogFocusDemo frame = new JDialogFocusDemo();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } 
        catch (UnsupportedLookAndFeelException e) {
           // handle exception
        }
        catch (ClassNotFoundException e) {
           // handle exception
        }
        catch (InstantiationException e) {
           // handle exception
        }
        catch (IllegalAccessException e) {
           // handle exception
        }
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

I'd probably rather go for the Window listener even though both work in my example.

Henri Benoit
  • 705
  • 3
  • 10
  • As per the [JavaDocs](https://docs.oracle.com/javase/8/docs/api/javax/swing/JComponent.html#requestFocus--), you should not use `requestFocus`, but instead use `requestFocusInWindow`. *"Note that the use of this method is discouraged because its behavior is platform dependent. Instead we recommend the use of requestFocusInWindow(). If you would like more information on focus, see How to Use the Focus Subsystem, a section in The Java Tutorial."* – MadProgrammer Sep 23 '15 at 07:00
  • 1
    Damn it ! I just wrote the code in my notepad and got the first requestFocusInWindow right but just wrote requestFocus in the second one... – Henri Benoit Sep 23 '15 at 07:01
  • *"You need to call requestFocusInWindow between your pack() and setVisible(true)"* One of the times that requesting focus will fail is 'before the component is visible on screen'.. – Andrew Thompson Sep 23 '15 at 08:07
  • I agree that it might fail when the dialog is not yet visible but obviously the example above shows that it will not 100% fail just because setVisible has not been yet called. In any case, it's safer to work with a Window listener. – Henri Benoit Sep 23 '15 at 08:38