Ⅰ java中JTextField如何强制失去焦点或者赋予焦点
让JTextField文本框响应焦点事件 即可.
核心代码
JTextFieldjtf=newJTextField(10);jtf.addFocusListener(newFocusListener(){publicvoidfocusLost(FocusEvente){//失去焦点时System.out.println("失去了焦点");jtf.setBackground(Color.WHITE);}publicvoidfocusGained(FocusEvente){//获得焦点时System.out.println("获得了焦点");tf.setBackground(Color.PINK);}});效果图
参考代码
importjava.awt.*;importjava.awt.event.*;importjavax.swing.*;{JTextFieldjtf;publicTextFrame(){JPaneljp=newJPanel();jtf=newJTextField(10);jtf.addFocusListener(newFocusListener(){@OverridepublicvoidfocusLost(FocusEvente){//失去焦点时System.out.println("失去了焦点");jtf.setBackground(Color.WHITE);}@OverridepublicvoidfocusGained(FocusEvente){//获得焦点时System.out.println("获得了焦点");jtf.setBackground(Color.PINK);}});jp.add(jtf);JButtonjb=newJButton("点击按钮,文本框会失去焦点");add(jb,BorderLayout.NORTH);add(jp,BorderLayout.SOUTH);setTitle("DEMO");setSize(300,220);//窗口大小setLocationRelativeTo(null);//窗口居中setDefaultCloseOperation(EXIT_ON_CLOSE);//窗口点击关闭时,退出程序setVisible(true);}publicstaticvoidmain(String[]args){newTextFrame();}}