Java学习笔记(GUI)

本文介绍了Java中图形用户界面(GUI)的事件监听机制,通过四个示例详细展示了如何使用AWT和Swing组件实现事件监听,包括窗口操作、鼠标键盘事件及菜单功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

18 GUI

18.1 事件监听机制

特点:

  1. 事件源:awt包或者swing包中的图形界面组件;
  2. 事件:每一个事件源都有自己特有的对应事件的共性事件;
  3. 监听器:将可以触发某一个事件的动作(不止一个)都已经封装到了监听器中;
    Ps:以上三点都已在java中定义好
  4. 事件处理:

例1:

import java.awt.*;
import java.awt.event.*;

public class AwtDemo {

    public static void main(String[] args) {
        Frame f = new Frame("my awt");
        f.setSize(400,300);
        f.setLocation(300,200);
        f.setLayout(new  FlowLayout());

        f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                f.dispose();
            }

            public void windowActivated(WindowEvent e){
                System.out.println("active");
            }

            public void windowOpened(WindowEvent e){
                System.out.println("opened");
            }
        });//窗口关闭的匿名类

        Button b = new Button("按钮");

        f.add(b);
        f.setVisible(true);
    }
}

运行结果:
窗口可关闭

例2:

import java.awt.*;
import java.awt.event.*;

public class MouseAndKeyEvent {
    private Frame f;
    private Button but;

    MouseAndKeyEvent(){
        init();
    }

    public void init(){
        //frame基本设置
        f = new Frame("my frame");
        f.setBounds(400,300,600, 500);
        f.setLayout(new  FlowLayout());

        but = new Button("按钮");

        f.add(but);
        //加载窗口事件
        myEvent();
        //显示窗口
        f.setVisible(true);
    }
    private void myEvent(){
        f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                f.dispose();
            }
        });

        but.addMouseListener(new MouseAdapter(){
            int count =1;
            int clickCount=1;
            public void mouseEntered(MouseEvent e){
                System.out.println("鼠标进入"+count++);
            }
            public void mouseClicked(MouseEvent e) {
                if(e.getClickCount()==2)
                System.out.println("鼠标点击"+clickCount++);
            }
        });
    }

    public static void main(String[] args){
        new MouseAndKeyEvent();
    }
}

运行结果:鼠标双击按钮后显示

例3:

import java.awt.*;

import java.awt.event.*;

public class MouseAndKeyEvent {
    private Frame f;
    private Button but;
    private TextField tf;

    MouseAndKeyEvent(){
        init();
    }

    public void init(){
        //frame基本设置
        f = new Frame("my frame");
        f.setBounds(400,300,600, 500);
        f.setLayout(new  FlowLayout());

        tf=  new TextField(20);

        but = new Button("按钮");
        f.add(tf);
        f.add(but);
        //加载窗口事件
        myEvent();
        //显示窗口
        f.setVisible(true);
    }
    private void myEvent(){
        f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                f.dispose();
            }
        });

        but.addKeyListener(new KeyAdapter(){
            public void keyPressed(KeyEvent e){
                if(e.isControlDown()&&e.getKeyCode()==KeyEvent.VK_ENTER )
                    f.dispose();
                System.out.println(KeyEvent.getKeyText(e.getKeyCode())+":"+e.getKeyCode());
            }
        });

        tf.addKeyListener(new KeyAdapter(){
            public void keyPressed(KeyEvent e){
                int code = e.getKeyCode();
                if(!(code>=KeyEvent.VK_0&&code<=KeyEvent.VK_9)){
                    System.out.println(code+"非法");
                    e.consume();
                }
            }
        });
    }

    public static void main(String[] args){
        new MouseAndKeyEvent();
    }
}

运行结果:按下1231adsf显示

例4:

import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class MyMenuDemo {
    private Frame f;
    private MenuBar bar;
    private Menu m;
    private MenuItem closeItem,openItem,saveItem;
    private FileDialog openDia,saveDia;
    private TextArea ta;
    private File file;
    MyMenuDemo(){
        init();
    }
    public void init(){
        f = new Frame("my frame");
        f.setBounds(400,300,600, 500);

        bar=new MenuBar();
        m= new Menu("文件");
        ta=new TextArea();

        closeItem = new MenuItem("退出");
        openItem = new MenuItem("打开");
        saveItem = new MenuItem("保存");

        m.add(openItem);
        m.add(saveItem);
        m.add(closeItem);

        bar.add(m);
        f.add(ta);

        f.setMenuBar(bar);

        openDia = new FileDialog(f,"打开",FileDialog.LOAD);
        saveDia = new FileDialog(f,"保存",FileDialog.SAVE);

        myEvent();
        f.setVisible(true);

    }
    private void myEvent(){
        f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                f.dispose();
            }
        });
        closeItem.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                f.dispose();
            }
        });
        openItem.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                openDia.setVisible(true);
                String dirPath=openDia.getDirectory();
                String fileName = openDia.getFile();
                if(dirPath==null||fileName==null)
                    return;
                ta.setText("");
                File file=new File(dirPath,fileName);
                try {
                    BufferedReader bufr = new BufferedReader(new FileReader(file));
                    String line =null;
                    while((line=bufr.readLine())!=null){
                        ta.append(line+"\r\n");
                    }
                    bufr.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });

        saveItem.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                if(file==null){
                    saveDia.setVisible(true);
                    String dirPath=saveDia.getDirectory();
                    String fileName = saveDia.getFile();
                    if(dirPath==null||fileName==null)
                        return;
                    file=new File(dirPath,fileName);
                }
                BufferedWriter bufw;
                try {
                    bufw = new BufferedWriter(new FileWriter(file));
                    String text = ta.getText();
                    bufw.write(text);
                    bufw.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }   
            }
        });
    }

    public static void main(String[] args) {
        new MyMenuDemo();
    }
}

运行结果:可进行文件的打开并显示在TextArea中,也可保存TextArea中的内容

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值