【发布时间】:2013-07-24 07:58:32
【问题描述】:
我找到了in the Internet这样的信息:
“当 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 时,任何组件都没有获得焦点。为什么?默认情况下,所有组合都是可聚焦的......
【问题讨论】:
-
将焦点放在标签上意味着什么?似乎按钮是唯一有意义的焦点组件。
-
好问题,创建一个新的顶级容器(基于 Native OS 的 pers)是相当困难和漫长的操作,1. 需要包装到 invokeLater == Oracle 教程 Concurency in Swing - Initial Tread, 2.或者打包并setVisible(true), 3.使用代码标签
-
只需在
MyDialog()构造函数的末尾写上dialogLabel1.requestFocusInWindow();,然后JLabel将获得焦点而不是JButton... -
@Heuster 我问是因为当我在 rootPane 的 inputMap 中使用 WHEN_ANCESTOR_OF_FOCUSED_COMPONENT 注册一些 keyStrokeEvents 时,当我的对话框里面只有 JLabels 时我遇到了问题。在这种情况下,KeyStroke 将不会进动,而它没有焦点。这种情况下必须人为设置label.setFocusable(true)。但可能这是唯一的方法
-
@guitar_freak : 其实
JLabel基本上是用来显示Text or Images的。正如 Heuster 已经评论的那样,它实际上不用于执行某种操作。仍然很难说,在不知道究竟是什么要求的情况下,为什么你需要JLabel来获得焦点。可能有一种方法,你没有考虑过 :-) 其余的你最欢迎并保持微笑:-)