我在网上找到了这样一个信息:
“当 JDialog(或 JFrame)可见时,默认情况下焦点放在第一个可聚焦组件上。”
让我们考虑这样的代码:
public class MyDialog extends JDialog{
// Dialog's 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();
}
}
输出是:运行:
null.glassPane | true | false
null.layeredPane | true | false
null.contentPane | true | false
Label1 | true | false
Button | true | true
Label2 | true | false
为什么焦点设置在 JButton 上?它不是第一个可聚焦的组件!当我删除 JButton 时,任何组件都没有获得焦点。为什么?默认情况下,所有组合都是可聚焦的...