java isfocusowner_java-在JFileChooser中获得JTextField的焦点(NimbusLookAndFeel)

这里的事情是在调用grabFocusForTextField()时,JTextField无法显示,因此您无法获得JTextField的焦点.为了使组件获得焦点,该组件必须首先存在,可见且可显示,启用且可聚焦.有关更多信息,请参见Focus subsystem in docs.

您必须在JFileChooser上注册自己的HierarchyListener才能侦听HierarchyEvent.在NimbusLookAndFeel中,这可能无法正确完成,或者JComboBox被选择为焦点所有者.只要组件是可显示的,只要JFileChooser的层次结构发生更改,就会触发此事件,并且此时JTextField是可显示的.

我已经重写了代码以使其正常工作.

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

class GetFocusForJTextField extends JFrame

{

JButton jb;

JFileChooser jf;

public GetFocusForJTextField()

{

createAndShowGUI();

}

private void createAndShowGUI()

{

// For NimbusLookAndFeel, JTextField is not

// the default focus owner in JFileChooser

try

{

UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");

}catch(Exception e){}

setTitle("Get Focus for JTextField");

setLayout(new FlowLayout());

setSize(400,400);

setVisible(true);

setDefaultCloseOperation(EXIT_ON_CLOSE);

jb=new JButton("Open JFileChooser");

jb.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae)

{

showDialog();

}

});

jf=new JFileChooser();

// Even if you add some other JTextField

// as accessory to JFileChooser

jf.setAccessory(new JTextField(20));

jf.addHierarchyListener(new HierarchyListener(){

public void hierarchyChanged(HierarchyEvent he)

{

grabFocusForTextField(jf.getComponents());

}

});

add(jb);

}

// Loop to find the JTextField, the first

// JTextField in JFileChooser

// Even if you setAccessory which contains a JTextField

// or which is JTextField itself, it will not get focus

private void grabFocusForTextField(Component[] c)

{

for(Component k:c)

{

if(k instanceof JTextField)

{

JTextField jt=(JTextField)k;

jt.grabFocus();

break;

}

else if(k instanceof JPanel)

{

JPanel jp=(JPanel)k;

grabFocusForTextField(jp.getComponents());

}

}

}

private void showDialog()

{

jf.showOpenDialog(this);

}

public static void main(String args[])

{

SwingUtilities.invokeLater(new Runnable(){

public void run()

{

new GetFocusForJTextField();

}

});

}

}

您也可以使用requestFocusInWindow()代替grabFocus()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值