java swing开发窗体程序开发(三)事件(Mouse,Foucs,Key,Window)

接着刚刚的事件讲
补充一点:事件的触发前提,添加了这个监听器的组件必须是处于激活状态的才可行

(一)MouseEvent事件

该事件的触发是由鼠标的动作引起的,引起的情况可以是下面5种,按下鼠标,释放鼠标,单击鼠标,进入区域,退出区域。其监视器要求实现的接口是MouseListener,其需要实现的函数有很多,分别是
void mousePressed(MouseEvent e);//鼠标处于按下时调用,一直按下不抬起将一直调用
void mouseReleased(MouseEvent e);//鼠标抬起时调用
void mouseEntered(MouseEvent e);//鼠标进入时调用
void mouseExited(MouseEvent e);//鼠标移出时调用
void mouseClicked(MouseEvent e);//鼠标点击时调用

通过addMouseListener()函数进行监听器的添加
[需注意]
该事件的触发也可以是另外一类型的情况,即拖动鼠标和移动鼠标。其要求监视器要实现的接口是MouseMotionListener,其需要实现的函数只有两个
void mouseDragged(MouseEvent e);//拖动鼠标时调用,即鼠标按下后移动
void mouseMoved(MouseEvent e);//鼠标在事件源中移动时调用

通过addMouseMotionListener()函数进行监听器的添加
需要注意的是,这里有一个MouseEvent类型的对象e,这个对象e中包含了本次触发该事件时鼠标的信息。信息包含
getX():鼠标点击的x坐标
getY():鼠标点击的y坐标
getModifiers();//获取是左键还是右键
getClickCount();//获得被点击的次数
getSource();//获得事件源,什么组件被点击了

以下是两个案例来获取鼠标事件
案例一:MouseListener

public class MousePushListener implements MouseListener {
    private JTextArea outPut;

    public void setOutPut(JTextArea outPut) {
        this.outPut = outPut;
    }

    public void mouseClicked(MouseEvent e){
        if(e.getClickCount()>=2)
        {
            outPut.append("鼠标连击,位置"+e.getX()+","+e.getY()+"\n");
        }
    }

    /**
     * Invoked when a mouse button has been pressed on a component.
     */
    public void mousePressed(MouseEvent e){
        outPut.append("鼠标按下:位置"+e.getX()+","+e.getY()+"\n");
    }

    /**
     * Invoked when a mouse button has been released on a component.
     */
    public void mouseReleased(MouseEvent e){
        outPut.append("鼠标释放:位置"+e.getX()+","+e.getY()+"\n");
    }

    /**
     * Invoked when the mouse enters a component.
     */
    public void mouseEntered(MouseEvent e){
        if(e.getSource() instanceof JButton)
        {
            outPut.append("鼠标进入按钮,位置"+e.getX()+","+e.getY()+"\n");
        }
        if(e.getSource() instanceof JTextField)
        {
            outPut.append("鼠标进入文本框,位置"+e.getX()+","+e.getY()+"\n");
        }
        if(e.getSource() instanceof JFrame)
        {
            outPut.append("鼠标进入窗口,位置"+e.getX()+","+e.getY()+"\n");
        }
    }

    /**
     * Invoked when the mouse exits a component.
     */
    public void mouseExited(MouseEvent e){
        outPut.append("鼠标退出,位置"+e.getX()+","+e.getY()+"\n");
    }

}

public class SimpleForm extends JFrame {
    private JTextField textField;
    private JButton button;
    private JTextArea textArea;

    private MousePushListener listener;
    public SimpleForm()
    {
        //GUI部分
        setLayout(new FlowLayout());
        textField=new JTextField(8);
        button=new JButton("按钮");
        textArea=new JTextArea(5,28);
        add(textField);
        add(button);
        add(new JScrollPane(textArea));
        setVisible(true);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setBounds(10,10,460,360);
        //设置监听器
        listener=new MousePushListener();
        listener.setOutPut(textArea);
        //添加监听器
        addMouseListener(listener);//为窗体本身添加
        button.addMouseListener(listener);
        textField.addMouseListener(listener);
    }
}
public class Main {
    public static void main(String[] args)
    {
        SimpleForm form=new SimpleForm();
    }
}

效果
在这里插入图片描述
案例二:MouseMotionListener

public class SimpleForm extends JFrame {

    private JTextArea outPut;
    private MouseDragListener listener;
    public SimpleForm()
    {
        //GUI部分
        setLayout(new FlowLayout());
        outPut=new JTextArea(9,15);
        add(outPut);
        setVisible(true);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setBounds(10,10,460,360);

        //设置监听器
        listener=new MouseDragListener();
        listener.setOutPut(outPut);
        //添加监听器
        addMouseMotionListener(listener);//本窗口添加监听器
        outPut.addMouseMotionListener(listener);
    }
}
public class MouseDragListener implements MouseMotionListener {
    private JTextArea outPut;

    public void setOutPut(JTextArea outPut) {
        this.outPut = outPut;
    }

    /**
     * 需实现的函数:鼠标拖拽时调用
     * @param e
     */

    public void mouseDragged(MouseEvent e)
   {
        outPut.setText("鼠标处于拖动状态,位置:"+e.getX()+","+e.getY());
   }

    /**
     * 需实现的函数:鼠标移动时调用
     * @param e
     */
   public void mouseMoved(MouseEvent e)
   {
       outPut.setText("鼠标处于移动状态,位置:"+e.getX()+","+e.getY());
   }


}
public class Main {
    public static void main(String []args)
    {
        SimpleForm form=new SimpleForm();
    }
}

效果
在这里插入图片描述

(二)FoucsEvent事件

即焦点事件,其主要是输入组件才有的事件,比如文本输入框JTextFIeld 和 JTextArea,点击后光标闪烁(获焦),和点其他位置(失焦)就这两个时期触发。
其要求实现的接口是FoucsListener接口,其中有两个需要实现的核心函数
void foucsGained(FoucsEvent e);//获焦时调用
void foucsLost(FoucsEvent);//失焦时调用

组件通过addFoucsListener(FocusListener listener)函数来添加监听器
add补充,一个组件想要获得自己是否是焦点状态,可以调用自己的 boolean requestFocusInWindow()方法来查看
由于该事件较为简单,所以没有写案例。
但以下是他的常见用法
1:获焦时:可用于给用户提示信息,用户一点输入框,就弹出一个提示信息这种情景
2:失焦时:可用于前段校验,比如校验用户输入的内容是否符合格式,就不用在点击按钮在校验,直接失去焦点时校验,让用户更早改正

(三)KeyEvent事件

当在箭盘山按下,释放,敲击一个按键时,就已经触发了键盘事件。其要求实现的接口是KeyListener,其中有3个需要实现的核心函数
void keyPressed(KeyEvent e);//键按下时调用,一直按下不抬起将一直调用
void keyRelease(KetEvent e);//键抬起时调用
void keyTyped(KeyEvent e);//点击后调用,相当于就是前两者执行一次完整后调用

组件通过addKeyListener来添加监听器
需要注意的是,这里有一个KeyEvent e的对象,该对象中包含了一些对本次触发时的信息
可以通过e.getKeyCode()和e.getKeyChar()来知道是哪个键的事件
前者返回int类型的数,这个数就是这个按键的代码,可以通过查看KeyEvent这个类的静态常量知道这些代码代表什么按键
后者返回char类型,得到的就是该按键上的字符

以下是一个案例,模拟输入序列号,到指定位数后转到下一个输入框

public class SimpleListener implements KeyListener, FocusListener {
    public void focusGained(FocusEvent e){
        JTextField textField=(JTextField) e.getSource();
        textField.setText(null);
    }
    public void focusLost(FocusEvent e){}

    public void keyTyped(KeyEvent e){}
    public void keyPressed(KeyEvent e){
        JTextField t=(JTextField) e.getSource();
        if(t.getCaretPosition()>=5)
        {
            t.transferFocus();//每一个小栏只能输入6个,超过6个就换下一个
        }
    }
    public void keyReleased(KeyEvent e){

    }

}
public class SimpleForm extends JFrame {
    private JTextField [] textFields=new JTextField[3];
    private SimpleListener listener;

    public SimpleForm()
    {
        //GUI部分
        setLayout(new FlowLayout());
        textFields[0]=new JTextField(6);
        textFields[1]=new JTextField(6);
        textFields[2]=new JTextField(6);
        add(textFields[0]);
        add(textFields[1]);
        add(textFields[2]);
        setVisible(true);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setBounds(10,10,460,360);
        setTitle("模拟序列号");
        //设置监听器
        listener=new SimpleListener();
        for(JTextField textField:textFields)
        {

            textField.addKeyListener(listener);
            textField.addFocusListener(listener);
        }
    }
}
public class Main {
    public static void main(String[] args)
    {
        SimpleForm form=new SimpleForm();
    }
}

效果如下

在这里插入图片描述

(四)WindowEvent事件

窗口事件,即对窗口进行操作时触发,触发的情况可以是:窗口打开,窗口被激活,窗口取消激活,窗口正在被关闭,窗口关闭后,窗口图标化(即最小化变为图标),窗口撤销图标化。这么多情况,且有些情况一个动作可以同时触发。例如我图标化一个窗口,如果此时该窗口未被激活,它将会先后触发:窗口被激活-窗口图标化
其要求实现的接口为WindowListener,其中需要实现7个核心函数
void windowActivated(WIndowEvent e);//窗口激活时调用
void windowDeactivated(WindowEvent e);//窗口取消激活时调用
void windowClosing(WindosEvent e);//窗口关闭中调用
void windowClosed(WindowEvent e);//窗口关闭后调用
void windowIconified(WindowEvent e);//窗口图标化时调用
void windowDeiconifed(WindowEvent e);//窗口取消图标化时调用
void windowOpened(WIndowEvent e);//窗口开启时调用

窗口对象通过addWindowListener()来添加监听器
这里涉及到一个WindowEvent对象e,这个对象可以通过e.getWindow()获得是哪个窗口触发的
需要注意的是
每个窗口都设置过一个叫做setDefaultCloseOperation()的函数,这是代表当关闭窗口后执行的操作,其一共有4种类型
DO_NOTHING_ON_CLOSE(什么也不做)【未设置时默认这种情况】
HIDE_ON_CLOSE(隐藏当前窗口)
DISPOSE_ON_CLOSE(隐藏当前窗口,并释放该窗口所占的其他资源)
EXIT_ON_CLOSE(直接关闭整个应用程序)

要想使用到前面所提到有关关闭操作所触发的函数时,就必须保证程序不能关闭,所以此时就必须保证其setDefaultCloseOperation是DO_NOTHING_ON_CLOSE
实际使用上,我们不会使用WIndowListener
原因:因为实现这个接口必须需要7个函数,不管你用不用。
解决方案
java提供了另一个抽象类,也能起到相同的作用,这个抽象类叫WindowAdaptor,其也实现了WindowListener,并实现了其所有的函数【即不再是抽象函数】,方法体为空。需要监听WIndowEvent相关的Listener,只需要继承这个抽象类,按需重写要用到的函数即可。

以下是一个小案例,猜数字

public class SimpleListener extends WindowAdapter implements ActionListener {

    private JLabel tipLabel;//提示框
    private JTextField input;//输入数字的框
    private int randomNum=0;

    public void setTipLabel(JLabel tipLabel) {
        this.tipLabel = tipLabel;
    }

    public void setInput(JTextField input) {
        this.input = input;
    }

    /**
     * 实现ActionListener接口的函数,其监听两个按钮的点击,通过actionCommand来判断不同的按钮【需在GUI代码时设置actionCommand且设置相同的Listener,即这个】
     * @param e
     */
    public void actionPerformed(ActionEvent e)
    {

        if(e.getActionCommand().equals("spawnButton"))
        {
            randomNum=(int)(Math.random()*100+1);
            tipLabel.setText("请输入");
            System.out.println("随机生成的数是"+randomNum);

        }else if(e.getActionCommand().equals("enterButton"))
        {
            int guess=0;
            try {
                guess=Integer.parseInt(input.getText());
                System.out.println("输入的数是"+guess);
                if(guess==randomNum)
                {
                    tipLabel.setText("猜对了");
                }else if(guess>randomNum)
                {
                    tipLabel.setText("猜大了");
                }else if(guess<randomNum)
                {
                    tipLabel.setText("猜小了");
                }
            }catch (Exception e1){
                System.out.println("发生解析异常,异常信息为:"+e1);
            }

        }
    }

    /**
     * 重写WIndowAdpater中的函数,关闭时调用
     * @param event
     */
    @Override
    public void windowClosing(WindowEvent event)
    {
        System.out.println("窗口关闭中");
    }

}
public class SimpleForm extends JFrame {
    private JButton spawnBtn;
    private JButton enterBtn;
    private JLabel tipLabel;
    private JTextField input;
    //Listener
    private SimpleListener listener;

    public SimpleForm()
    {
        //GUI部分
        setLayout(new FlowLayout());
        spawnBtn=new JButton("生成数");
        enterBtn=new JButton("确定");
        spawnBtn.setActionCommand("spawnButton");//注意。十分重要,ActionEvent区分按钮的根据
        enterBtn.setActionCommand("enterButton");//注意。十分重要,ActionEvent区分按钮的根据
        tipLabel=new JLabel("猜数字",JLabel.CENTER);
        input=new JTextField("0",10);
        add(spawnBtn);
        add(tipLabel);
        add(input);
        add(enterBtn);
        setVisible(true);
        setTitle("猜数字");
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);//默认就是这个,可以不写
        setBounds(100,100,150,150);

        //设置监听器
        listener=new SimpleListener();
        listener.setInput(input);
        listener.setTipLabel(tipLabel);
        //添加监听器
        addWindowListener(listener);//本窗口添加
        //为两个按钮添加
        spawnBtn.addActionListener(listener);
        enterBtn.addActionListener(listener);
    }
}

public class Main  {
    public static void main(String []args)
    {
        SimpleForm form=new SimpleForm();

    }


}

效果如下

在这里插入图片描述
上一篇java swing开发窗体程序开发(二)事件(Action,Item,Document)
https://blog.csdn.net/tanyu159/article/details/89082367
下一篇java swing开发窗体程序开发(四)MVC结构
https://blog.csdn.net/tanyu159/article/details/89137484

【!!!】欢迎关注我的个人线上课堂https://www.zuikakuedu.cn,内含JavaWeb与Unity游戏开发实战教程,完全免费!,Csdn博客涉及的课程资料也在该网站上

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

最咔酷学院

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值