Swing 中 JTextField事件 与 鼠标事件整合

时间:2023-01-28 15:00:40

当操作文本框时,一些文本框事件,和一些对文本框的鼠标事件
 
 
//新建文本框JTextField text = new JTextField(10);
 
//(1)创建文本框触发事件text.getDocument().addDocumentListener(new TextHandle());/** * 文本框触发事件 * @author wangjian * */public class TextHandle implements DocumentListener {//这是更改操作的处理public void changedUpdate(DocumentEvent e) {String aaa =p1_bipolarText.getText().trim();//trim()方法用于去掉你可能误输入的空格号              System.out.println("1->"+aaa);}//这是插入操作的处理public void insertUpdate(DocumentEvent e) {String aaa = p1_bipolarText.getText().trim();              System.out.println("2->"+aaa);}//这是删除操作的处理public void removeUpdate(DocumentEvent e) {String aaa = p1_bipolarText.getText().trim();              System.out.println("3->"+aaa);}}//(2)监听鼠标是否进入或退出文本框,监听鼠标左键右键事件p1_bipolarText.addMouseListener(new MouseListener() {@Overridepublic void mouseReleased(MouseEvent e) {// 鼠标松开System.out.println("鼠标松开");}@Overridepublic void mousePressed(MouseEvent e) {// 鼠标按下System.out.println("鼠标按下");}@Overridepublic void mouseExited(MouseEvent e) {// 鼠标退出组件System.out.println("鼠标退出组件");}@Overridepublic void mouseEntered(MouseEvent e) {// 鼠标进入组件System.out.println("鼠标进入组件");}@Overridepublic void mouseClicked(MouseEvent e) {// 鼠标单击事件int c = e.getButton();// 得到按下的鼠标键    String mouseInfo = null;// 接收信息    if (c == MouseEvent.BUTTON1)// 判断是鼠标左键按下    {      mouseInfo = "左键";    } else if (c == MouseEvent.BUTTON3) {// 判断是鼠标右键按下      mouseInfo = "右键";    } else {      mouseInfo = "滚轴";    }    System.out.println("鼠标单击事件");}});//(3)监听鼠标焦点事件,失去获得焦点事件p1_bipolarText.addFocusListener(new TextFocusHandle());/** * 文本框焦点失去、获取事件 * @author wangjian * */public class TextFocusHandle implements FocusListener {public void focusGained(FocusEvent e) {//获得焦点}public void focusLost(FocusEvent e) {//失去焦点JTextField source = (JTextField) e.getSource();String text = source.getText();System.out.println("***************************************"+text);}}