Ⅰ 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();}}