Java实验5 GUI编程

实验5 GUI编程

一、实验目的

掌握Java Swing 组件的使用方法,理解委托事件处理模型,掌握多种布局方式,掌握窗口菜单和快捷菜单设计方式,设计出具有图形用户界面、能够响应事件的Java应用程序。

二、实验内容

1.程序理解:

事件处理三个步骤

(1)搭建界面
(2)为相应控件定义事件处理类实现相应的事件处理接口并实现相应的事件处理接口函数
(3)注册事件监听器类对象


例: Unicode 字符查询器

这里写图片描述

(1)搭建界面
public class QueryFrame extends Frame //框架窗口响应单击事件
{
    private TextField text_char, text_uni;                 //两个文本行
    private Button button_char, button_uni;                //两个按钮

    public QueryFrame()
    {
        super("Unicode字符查询器");                       //窗口标题
        this.setBounds(300,240,300,100);         //设置框架的位置和尺寸
        this.setBackground(Color.lightGray);       //设置框架的背景颜色
        this.setLayout(new FlowLayout(FlowLayout.RIGHT));   //框架流布局且左对齐
        this.add(new Label("字符"));
        text_char = new TextField("汉",10);
        this.add(text_char);
        button_char = new Button("查询Unicode码");
        this.add(button_char);
        this.add(new Label("Unicode码"));
        text_uni = new TextField(10);
        this.add(text_uni);        
        button_uni = new Button("     查询字符      ");
        this.add(button_uni);
        this.setVisible(true);                             //显示框架

    public static void main(String arg[])
    {
        new QueryFrame();
    }
}
(2)为相应控件设置事件处理类
public class QueryFrame extends Frame //框架窗口响应单击事件
{
    private TextField text_char, text_uni;                 //两个文本行
    private Button button_char, button_uni;                //两个按钮

    public QueryFrame()
    {
        super("Unicode字符查询器");                //窗口标题
        this.setBounds(300,240,300,100);        //设置框架的位置和尺寸
        this.setBackground(Color.lightGray);      //设置框架的背景颜色
        this.setLayout(new FlowLayout(FlowLayout.RIGHT));   //框架流布局且左对齐
        this.add(new Label("字符"));
        text_char = new TextField("汉字",10);
        this.add(text_char);
        button_char = new Button("查询Unicode码");
        this.add(button_char);

        this.add(new Label("Unicode码"));
        text_uni = new TextField(10);
        this.add(text_uni);        
        button_uni = new Button("     查询字符      ");
        this.add(button_uni);
        this.setVisible(true);                             //显示框架
         }
    class QueryHandler implements ActionListener
    {
    public void actionPerformed(ActionEvent e)  //单击事件处理方法,实现ActionListener接口
    {
        if (e.getSource()==button_char)  //e.getSource()获得当前事件源组件,比较引用
        {
            String str = text_char.getText();        //获得文本行的字符串
            char ch=str.charAt(0);             //获得首字符
            text_char.setText(""+ch);          //重新设置文本,显示字符
            text_uni.setText(""+(int)ch);    //显示ch的Unicode码
        }
        if (e.getSource()==button_uni)
        {
            int uni=Integer.parseInt(text_uni.getText());  //将文本行字符串转换成整数,未捕获NumberFormatException异常
            text_char.setText(""+(char)uni);               //显示uni中Unicode码对应的字符
        }
    }   
    }

    class WinClose implements WindowListener   //实现窗口事件监听器接口
    {
        public void windowClosing(WindowEvent e) //窗口关闭事件处理方法
        {
        System.exit(0);                          //结束程序运行
         }

        public void windowOpened(WindowEvent e)         {  }
        public void windowActivated(WindowEvent e)      {  }
        public void windowDeactivated(WindowEvent e)    {  }
        public void windowClosed(WindowEvent e)         {  }
        public void windowIconified(WindowEvent e)      {  }
        public void windowDeiconified(WindowEvent e)    {  }
    }


    public static void main(String arg[])
    {
        new QueryFrame();
    }
}
(3)注册事件监听器类对象
public class QueryFrame extends Frame //框架窗口响应单击事件
{
    private TextField text_char, text_uni;                 //两个文本行
    private Button button_char, button_uni;                //两个按钮

    public QueryFrame()
    {
        super("Unicode字符查询器");                      //窗口标题
        this.setBounds(300,240,300,100);        //设置框架的位置和尺寸
        this.setBackground(Color.lightGray);        //设置框架的背景颜色
        this.setLayout(new FlowLayout(FlowLayout.RIGHT));   //框架流布局且左对齐
        QueryHandler q= new QueryHandler();   //生成监听器对象
        this.add(new Label("字符"));
        text_char = new TextField("汉字",10);
        this.add(text_char);
        button_char = new Button("查询Unicode码");
        this.add(button_char);
        button_char.addActionListener(q);  //为按钮注册单击事件监听器
        this.add(new Label("Unicode码"));
        text_uni = new TextField(10);
        this.add(text_uni);        
        button_uni = new Button("     查询字符      ");
        this.add(button_uni);
        button_uni.addActionListener(q);   //为按钮注册单击事件监听器
        this.setVisible(true);                             //显示框架
        this.addWindowListener(new WinClose());            //为框架注册窗口事件监听器,委托WinClose类的对象处理事件
    }
    class QueryHandler implements ActionListener
    {
    public void actionPerformed(ActionEvent e)             //单击事件处理方法,实现ActionListener接口
    {
        if (e.getSource()==button_char)         //e.getSource()获得当前事件源组件,比较引用
        {
            String str = text_char.getText();        //获得文本行的字符串
            char ch=str.charAt(0);                  //获得首字符
            text_char.setText(""+ch);           //重新设置文本,显示字符
            text_uni.setText(""+(int)ch);          //显示ch的Unicode码
        }
        if (e.getSource()==button_uni)
        {
            int uni=Integer.parseInt(text_uni.getText());  //将文本行字符串转换成整数,未捕获NumberFormatException异常
            text_char.setText(""+(char)uni);  //显示uni中Unicode码对应的字符
        }
    }   
    }

    class WinClose implements WindowListener   //实现窗口事件监听器接口
        {
        public void windowClosing(WindowEvent e) //窗口关闭事件处理方法
        {
        System.exit(0);                          //结束程序运行
         }

        public void windowOpened(WindowEvent e)         {  }
        public void windowActivated(WindowEvent e)      {  }
        public void windowDeactivated(WindowEvent e)    {  }
        public void windowClosed(WindowEvent e)         {  }
        public void windowIconified(WindowEvent e)      {  }
        public void windowDeiconified(WindowEvent e)    {  }
        }


    public static void main(String arg[])
    {
        new QueryFrame();
    }
}
改进版:
package test5;

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

public class QueryFramer extends Frame //框架窗口响应单击事件
{
    private TextField text_char, text_uni;                 //两个文本行
    private Button button_char, button_uni;                //两个按钮

    public QueryFramer()
    {
        super("Unicode字符查询器");                      //窗口标题
        this.setBounds(300,240,300,100);        //设置框架的位置和尺寸
        this.setBackground(Color.lightGray);        //设置框架的背景颜色
        this.setLayout(new FlowLayout(FlowLayout.RIGHT));   //框架流布局且左对齐
        QueryHandler q= new QueryHandler();   //生成监听器对象
        this.add(new Label("字符"));
        //TextField是允许编辑的单行文本
        text_char = new TextField(10);
        this.add(text_char);
        button_char = new Button("查询Unicode码");
        this.add(button_char);
        button_char.addActionListener(q);  //为按钮注册单击事件监听器
        this.add(new Label("Unicode码"));
        text_uni = new TextField(10);
        this.add(text_uni);        
        button_uni = new Button("     查询字符      ");
        this.add(button_uni);
        button_uni.addActionListener(q);   //为按钮注册单击事件监听器
        this.setVisible(true);                             //显示框架
        this.addWindowListener(new WinClose());            //为框架注册窗口事件监听器,委托WinClose类的对象处理事件
    }
    class QueryHandler implements ActionListener
    {
    public void actionPerformed(ActionEvent e)             //单击事件处理方法,实现ActionListener接口
    {
        if (e.getSource()==button_char)         //e.getSource()获得当前事件源组件,比较引用
        {
            String str = text_char.getText();        //获得文本行的字符串
            char ch=str.charAt(0);                  //获得首字符
            text_char.setText(""+ch);           //重新设置文本,显示字符
            text_uni.setEditable(false);        //设置Unicode码文本行不可编辑
            text_uni.setText(""+(int)ch);          //显示ch的Unicode码

        }
        if (e.getSource()==button_uni)
        { 
            text_char.setEditable(false);       //设置字符文本行不可编辑
            int uni=Integer.parseInt(text_uni.getText());  //将文本行字符串转换成整数,未捕获NumberFormatException异常
            text_char.setText(""+(char)uni);  //显示uni中Unicode码对应的字符
        }
    }   
    }

    class WinClose implements WindowListener   //实现窗口事件监听器接口
        {
        public void windowClosing(WindowEvent e) //窗口关闭事件处理方法
        {
        System.exit(0);                          //结束程序运行
         }

        public void windowOpened(WindowEvent e)         {  }
        public void windowActivated(WindowEvent e)      {  }
        public void windowDeactivated(WindowEvent e)    {  }
        public void windowClosed(WindowEvent e)         {  }
        public void windowIconified(WindowEvent e)      {  }
        public void windowDeiconified(WindowEvent e)    {  }
        }


    public static void main(String arg[])
    {
        new QueryFramer();
    }
}

运行结果:

这里写图片描述

2.编程题:

(1)教材381页编程题第1题;

编写一个JFrame窗口,要求如下:
①在窗口的最上方放置一个JLabel标签,标签中默认文本是“此处显示鼠标右键点击的坐标”。
②为JFrame窗口添加一个鼠标事件,当鼠标右键点击窗口时,鼠标的坐标在JLabel中显示


(2)教材381页编程题第2题;

编写一个JFrame窗口,要求如下:
①在窗口的NORTH区域放置一个JPanel面板。
②JPanel面板中从左到右依次放置如下组件:
JLabel标签,标签的文本为“兴趣”。
三个JCheckBox多选按钮,文本分别为“羽毛球”、“乒乓球”、“唱歌”。
JLabel标签,标签的文本为“性别”。
两个JRadioButton按钮,文本分别为“男”、“女”
③窗口的CENTER区域放置一个JScrollPane容器,容器中放置一个JTextArea文本域
④当点击多选按钮和单选按钮时,会把选中按钮的文本显示在JTextArea文本域中


(3)教材381页编程题第3题。

编写一个JFrame窗口,要求如下:
①窗口包含一个菜单栏和一个JLabel标签。
②菜单栏中有两个菜单,第一个菜单有两个菜单项,它们之间用分隔符分开,第二个菜单有一个菜单项
③JLabel标签放置在窗口的中间(即BorderLayout.CENTER),当点击菜单项时,菜单中的文本显示在JLabel标签中


三、实验结果

(1)程序1运行结果

这里写图片描述

这里写图片描述

(2)程序2运行结果

这里写图片描述

(3)程序3运行结果

这里写图片描述

这里写图片描述

四、实验源代码

(1)程序1源代码

package test5;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Example1 extends JFrame {
    public Example1() {
        //设置窗体的名字
        this.setTitle("Example1");
        //设置窗体的大小
        this.setSize(300, 200);
        //定义一个标签组件
        final JLabel label = new JLabel("此处显示鼠标右键点击的坐标");
        //设置流式布局管理器
        this.setLayout(new FlowLayout());
        //添加标签组件
        this.add(label);    
        //设置点击关闭按钮时的默认操作
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //为窗口添加鼠标事件监听器
        this.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                //当鼠标右键点击窗口时,鼠标的坐标在JLable标签中显示
                if (e.getButton() == e.BUTTON3) {
                    int x = e.getX();
                    int y = e.getY();
                    String str = "鼠标当前点击位置的坐标是" + x + "," + y;
                    label.setText(str);
                }
            }
        });
        this.setVisible(true);
    }
    public static void main(String[] args) {
        new Example1();
    }
}

(2)程序2源代码

package test5;

import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
public class Example2 extends JFrame {
    // 窗口NORTH部的JPanel面板 
    private JPanel panel = new JPanel();
    private JLabel l1 = new JLabel("兴趣");
    private JCheckBox c1 = new JCheckBox("羽毛球");
    private JCheckBox c2 = new JCheckBox("乒乓球");
    private JCheckBox c3 = new JCheckBox("唱歌");
    // 添加标签
    private JLabel l2 = new JLabel("性别");
    // 添加JRadioButton单选框
    private JRadioButton r1 = new JRadioButton("男");
    private JRadioButton r2 = new JRadioButton("女");
    // ButtonGroup添加JRadioButton,实现单选功能
    private ButtonGroup bg = new ButtonGroup();
    // 文本域组件
    private JTextArea area = new JTextArea();
    // 添加JScrollPane面板,其中放置area文本域 
    private JScrollPane pane = new JScrollPane(area);
    // Set集合存放选中的兴趣
    private Set<String> hobbies = new HashSet<String>();
    //sex选中的性别
    private String sex = "";
    // JCheckBox复选框的事件监听器
    private ActionListener listener1 = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JCheckBox cb = (JCheckBox) e.getSource();
            // 选中的复选框把文本添加到Set集合中
            if (cb.isSelected()) {
                hobbies.add(cb.getText());
            //  反之从集合中移除
            } else {
                hobbies.remove(cb.getText());
            }
            print();
        }
    };
    // JRadioButton单选框的事件监听器
    private ActionListener listener2 = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JRadioButton jb = (JRadioButton) e.getSource();
            sex = jb.getText();
            print();
        }
    };
    // 打印方法
    private void print() {
        // 清空文本域
        area.setText("");
        // 如果Set集合中有元素,打印兴趣
        if (hobbies.size() > 0)
            area.append("兴趣: ");
        Iterator<String> it = hobbies.iterator();
        while (it.hasNext()) {
            area.append(it.next() + "  ");
        }
        area.append("\n");
        // 如果gender不为空字符串,打印性别
        if (!"".equals(sex))
            area.append("性别: " + sex);
    }
    public Example2() {
        //
        this.setTitle("Example2");
        //添加标签、单选和复选按钮
        panel.add(l1);
        panel.add(c1);
        panel.add(c2);
        panel.add(c3);
        panel.add(l2);
        panel.add(r1);
        panel.add(r2);
        bg.add(r1);
        bg.add(r2);
        // 为单选和复选按钮添加事件监听器
        c1.addActionListener(listener1);
        c2.addActionListener(listener1);
        c3.addActionListener(listener1);
        r1.addActionListener(listener2);
        r2.addActionListener(listener2);
        // 将JPanel面板和JScrollPane面板添加到JFrame容器中 
        Container container = this.getContentPane();
        container.add(panel, BorderLayout.NORTH);
        container.add(pane, BorderLayout.CENTER);
        this.setSize(400, 300);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
        area.setLineWrap(true);
        area.setEditable(false);
        area.setFont(new Font("宋体",Font.BOLD,16));
        //area.setBackground(Color.GREEN);

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

(3)程序3源代码

package test5;

import javax.swing.*;

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

public class Example3 extends JFrame  {
    //创建一个JLabel标签,标签文本居中对齐
    private JLabel label = new JLabel("请选择菜单", JLabel.CENTER);
    //创建一个事件监听器,当点击菜单项时菜单项的
    private ActionListener listener1 = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JMenuItem source = (JMenuItem) (e.getSource());
            label.setText( source.getText());
            label.setHorizontalAlignment(JLabel.CENTER);
        }
    };
    Example3() {
        //添加JLabel标签,放置在窗口中间
        this.add(label, BorderLayout.CENTER);
        // 创建菜单栏
        JMenuBar menuBar = new JMenuBar();
        // 将菜单栏添加到JFrame窗口中
        this.setJMenuBar(menuBar);
        // 创建菜单
        JMenu Menu1 = new JMenu("菜单1");
        JMenu Menu2 = new JMenu("菜单2");
        // 添加菜单
        menuBar.add(Menu1);
        menuBar.add(Menu2);
        // 创建菜单项
        JMenuItem MenuItem11 = new JMenuItem("菜单项 11");
        JMenuItem MenuItem12 = new JMenuItem("菜单项12");
        JMenuItem MenuItem21 = new JMenuItem("菜单项21");
        // 添加菜单项
        Menu1.add(MenuItem11);
        // 添加分隔符
        Menu1.addSeparator();
        Menu1.add(MenuItem12);
        Menu2.add(MenuItem21);
        //为菜单项添加事件监听器
        MenuItem11.addActionListener(listener1);
        MenuItem12.addActionListener(listener1);
        MenuItem21.addActionListener(listener1);
        //设置窗口名字
        this.setTitle("Example3");
        //设置窗口大小
        this.setSize(400, 300);
        this.setVisible(true);
        //设置点击关闭按钮时的默认操作
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String args[]) {
        JFrame frame = new Example3();

    }
}

五、参考答案

1、参考答案

import java.awt.*;
import java.awt.event.*;import javax.swing.*;
public class MyMouseHandler extends JFrame {
    public MyMouseHandler() {
        final JLabel label = new JLabel("此处显示鼠标右键点击的坐标");
        label.setOpaque(true);
        label.setBackground(Color.PINK);
        this.add(label, BorderLayout.NORTH);
        this.setSize(300, 200);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == e.BUTTON1) {
                    int x = e.getX();
                    int y = e.getY();
                    String banner = "鼠标当前点击位置的坐标是" + x + "," + y;
                    label.setText(banner);
                }
            }
        });
        this.setVisible(true);
    }
    public static void main(String[] args) {
        new MyMouseHandler();
    }
}

2、参考答案

import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
public class Information extends JFrame {
    // 窗口NORTH部的JPanel面板 
    private JPanel panel = new JPanel();
    // 爱好标签
    private JLabel lb1 = new JLabel("爱好");
    // 三个表示爱好的JCheckBox复选框
    private JCheckBox cb1 = new JCheckBox("羽毛球");
    private JCheckBox cb2 = new JCheckBox("乒乓球");
    private JCheckBox cb3 = new JCheckBox("唱歌");
    // 性别标签
    private JLabel lb2 = new JLabel("性别");
    // 表示性别的JRadioButton单选框
    private JRadioButton rb1 = new JRadioButton("男");
    private JRadioButton rb2 = new JRadioButton("女");
    // ButtonGroup添加JRadioButton,实现单选功能
    private ButtonGroup bg = new ButtonGroup();
    // 文本域组件
    private JTextArea area = new JTextArea();
    // 窗口CENTER部的JScrollPane面板,其中放置area文本域 
    private JScrollPane pane = new JScrollPane(area);
    // Set集合存放选中的兴趣
    private Set<String> hobbies = new HashSet<String>();
    // gender选中的性别
    private String gender = "";
    // JCheckBox复选框的事件监听器
    private ActionListener listener1 = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JCheckBox cb = (JCheckBox) e.getSource();
            // 选中的复选框把文本添加到Set集合中
            if (cb.isSelected()) {
                hobbies.add(cb.getText());
            //  反之从集合中移除
            } else {
                hobbies.remove(cb.getText());
            }
            print();
        }
    };
    // JRadioButton单选框的事件监听器
    private ActionListener listener2 = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JRadioButton jb = (JRadioButton) e.getSource();
            gender = jb.getText();
            print();
        }
    };
    // 打印方法
    private void print() {
        // 清空文本域
        area.setText("");
        // 如果Set集合中有元素,打印兴趣
        if (hobbies.size() > 0)
            area.append("你的兴趣爱好有: ");
        Iterator<String> it = hobbies.iterator();
        while (it.hasNext()) {
            area.append(it.next() + " ");
        }
        // 如果gender不为空字符串,打印性别
        if (!"".equals(gender))
            area.append("你的性别为: " + gender);
    }
    public Information() {
        //添加标签、单选和复选按钮
        panel.add(lb1);
        panel.add(cb1);
        panel.add(cb2);
        panel.add(cb3);
        panel.add(lb2);
        panel.add(rb1);
        panel.add(rb2);
        bg.add(rb1);
        bg.add(rb2);
        // 为单选和复选按钮添加事件监听器
        cb1.addActionListener(listener1);
        cb2.addActionListener(listener1);
        cb3.addActionListener(listener1);
        rb1.addActionListener(listener2);
        rb2.addActionListener(listener2);
        // 将JPanel面板和JScrollPane面板添加到JFrame容器中 
        Container container = this.getContentPane();
        container.add(panel, BorderLayout.NORTH);
        container.add(pane, BorderLayout.CENTER);
        this.pack();
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }
    public static void main(String[] args) {
        new Information();
    }
}

3、参考答案

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyMenu extends JFrame implements ActionListener {
    JLabel label = new JLabel("请选择菜单", JLabel.CENTER);
    JMenuItem aaMenuItem, baMenuItem;
    MyMenu() {
        JMenuBar menuBar = new JMenuBar();
        JMenu aMenu = new JMenu("菜单A");
        JMenu bMenu = new JMenu("菜单B");
        JMenuItem aaMenuItem = new JMenuItem("菜单项 AA");
        JMenuItem abMenuItem = new JMenuItem("菜单项AB");
        JMenuItem baMenuItem = new JMenuItem("菜单项 BA");
        menuBar.add(aMenu);
        menuBar.add(bMenu);
        aMenu.add(aaMenuItem);
        aMenu.addSeparator();
        aMenu.add(abMenuItem);
        bMenu.add(baMenuItem);
        aaMenuItem.addActionListener(this);
        abMenuItem.addActionListener(this);
        baMenuItem.addActionListener(this);
        setJMenuBar(menuBar);
        getContentPane().add(label, BorderLayout.CENTER);
    }
    public void actionPerformed(ActionEvent e) {
        JMenuItem source = (JMenuItem) (e.getSource());
        label.setText("选择了菜单:" + source.getText());
        label.setHorizontalAlignment(JLabel.CENTER);
    }
    public static void main(String args[]) {
        JFrame frame = new MyMenu();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setVisible(true);
    }
}
  • 0
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值