I found the following information on the Internet :
"When the JDialog (or JFrame, for that matter) becomes visible, focus is placed on the first custom component by default."
Consider the following code:
public class MyDialog extends JDialog{ // Dialog components: private JLabel dialogLabel1 = new JLabel("Hello"); private JLabel dialogLabel2 = new JLabel("Message"); private JButton dialogBtn = new JButton("Sample Btn text"); public MyDialog(JFrame parent, String title, ModalityType modality){ super(parent, title, modality); dialogBtn.setName("Button"); // dialogLabel1.setName("Label1"); // - setting names dialogLabel2.setName("Label2"); // setTitle(title); setModalityType(modality); setSize(300, 100); setLocation(200, 200); // adding comps to contentPane getContentPane().add(dialogLabel1, BorderLayout.PAGE_START); getContentPane().add(dialogBtn, BorderLayout.CENTER); getContentPane().add(dialogLabel2, BorderLayout.PAGE_END); pack(); } public void showDialog(){ setVisible(true); listComps(rootPane.getComponents()); setDefaultCloseOperation(DISPOSE_ON_CLOSE); } /* * Itereates through all subcomps recursively and displays some relevant info * OUTPUT FORM: ComponentName | isFocusable | hasFocus */ private void listComps(Component[] comps){ if(comps.length == 0) return; for(Component c : comps){ JComponent jC = (JComponent)c; System.out.println(jC.getName() + " | " + jC.isFocusable() +" | " + jC.hasFocus()); listComps(jC.getComponents()); } } public static void main(String[] args) { final JFrame frame = new JFrame(); frame.setPreferredSize(new Dimension(300, 400)); frame.setVisible(true); JButton btn = new JButton("Show dialog"); btn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { MyDialog dialog = new MyDialog(frame, "Sample title", ModalityType.APPLICATION_MODAL); dialog.showDialog(); } }); frame.add(btn, BorderLayout.CENTER); frame.pack(); } }
Output: run:
null.glassPane | true | false null.layeredPane | true | false null.contentPane | true | false Label1 | true | false Button | true | true Label2 | true | false
Why is the focus set to JButton? This is not the first custom component! When I removed JButton, focus was not obtained to any component. What for? By default, all songs are tuned ...
source share