第十八章,Swing窗体

概述


String包的层次结构和继承关系如下 

常用的Swing组件如下表

Swing常用窗体 


JFrame 窗体

JFrame 类的常用构造方法包括以下两种形式:
public JFrame():创建一个初始不可见、没有标题的窗体。
public JFrame(String title):创建一个不可见、具有标题的窗体。
例如,创建一个不可见、具有标题的窗体,关键代码如下:

JFrame jf = new JFrame(“登录系统”);

Container container = jf.getContentPane();

在创建窗体后,先调用getContentPaneO方法将窗体转换为容器,再调用addO方法或者removeO方法向容器中添加组件或者删除容器中的组件。向容器中添加按钮,关键代码如下:

JButton okBtn= new JButton(“确定“)

container.add(okBtn);

删除容器中的按钮,关键代码如下:

container.remove(okBtn);

创建窗体后,要对窗体进行设置,如设置窗体的位置、大小、是否可见等。JFrame 类提供的相应方法可实现上述设置操作,具体如下:

setBounds(int x, int y, int width, int leight):设置窗体左上角在屏幕中的坐标为(x,y),窗体的宽度为width,窗体的高度为height。
setLocation(int x,int y):设置窗体左上角在屏幕中的坐标为(x,y)。
setSize(int width, int height):设置窗体的宽度为width,高度为height。
setVisibale(boolean b):设置窗体是否可见。b为true时,表示可见;b为false时,表示不可见。setDefaultCloseOperation(int operation):设置窗体的关闭方式,默认值为DISPOSE_ON_CLOSE 

Java 语言提供了多种窗体的关闭方式,常用的有4种,如表18.2所示。

JDialog 对话框 

JDialog 类常用的构造方法如下:

public JDialogO:创建一个没有标题和父窗体的对话框。
public JDialog(Frame f):创建一个没有标题,但指定父窗体的对话框。
public JDialog(Frame f, boolean model):创建一个没有标题,但指定父窗体和模式的对话框。如果model为true,那么弹出对话框后,用户无法操作父窗体。
public JDialog(Frame f, String title):创建一个指定标题和父窗体的对话框.。
public JDialog(Frame f, String title, boolean model):创建一个指定标题、父窗体和模式的对话框。

JOptionPane 小型对话框 

JOptionPane提供了4种创建对话框的方法,如下:

下面分别介绍这4种对话框的外观样式和使用方法

1.自定义对话框

参数说明如下:

parentComponent:指明对话框在哪个窗体上显示,如果传入具体的窗体对象,对话框会在该窗体居中位置显示,如果传入null则在屏幕中间弹出对话框。
message:提示的信息。
title:对话框的标题。
optionType:指定可用于对话框的选项的整数:DEFAULT_OPTION、YES NO_OPTION.YES NO_CANCEL_OPTION 或 OK_CANCEL_OPTION。
messageType:指定消息种类的整数,主要用于确定来自可插入外观的图标ERRORMESSAGE、INFORMATION_MESSAGE、WARNING_MESSAGE、QUESTION_MESSAGE 或 PLAIN_MESSAGE。
icon:在对话框中显示的图标。
options:指示用户可能选择的对象组成的数组。如果对象是组件,则可以正确呈现,非String对象使用其toString方法呈现;如果此参数为null,则由外观确定选项。
initialValue:表示对话框的默认选择的对象,只有在使用options 时才有意义,可以为null。

2.确认框 

调出带有选项 Yes、No 和Cancel的对话框;标题为 Select an Option。
 

static int showConfirmDialog(Component parentComponent, Object message)

调出一个由optionType参数确定其中选项数的对话框。
 

static int showConfirmDialog
(Component parentComponent, Object message, String title, int optionType)

调用一个由optionType参数确定其中选项数的对话框,messageType参数确定要显示的图标。

static int showConfirmDialog(Component parentComponent,
        Object message,

        String title,

        int optionType,

        int messageType)

调出一个带有指定图标的对话框,其中的选项数由optionType 参数确定。
 

static int showConfirmDialog(Component parentComponent,

        Object message,

        String title,

        int optionType,

        int messageType,

        Icon icon)
3.输入框 

输入框已经封装好了一套外观样式,弹出后要求用户在文本框中输入文本,用户完成输入操作后,输入框可以返回用户输入的结果。创建输入框的方法有以下几种重载形式:

显示请求用户输入内容的问题消息对话框,它以parentComponent为父级。

static String showlnputDialog(Component parentComponent, Object message)

显示请求用户输入内容的问题消息对话框,它以parentComponent为父级。

static String showlnputDialog
(Component parentComponent, Object message, Object initialSelectionValue)

显示请求用户输入内容的对话框,它以parentComponent为父级,该对话框的标题为title,消息类型为messageType。

static String showlnputDialog
(Component parentComponent, Object message, String title, int messageType)

提示用户在可以指定初始选择、可能选择及其他所有选项的模块化的对话框中输入内容。

static Object showInputDialog(Component parentComponent,

                Object message,

                String title,

                int messageType,

                Icon icon,

                Objectü selectionValues,

                Object initialSelectionValue)

显示请求用户输入的问题消息对话框。

static String showInputDialog(Object message)

显示请求用户输入的问题消息对话框,它带有已初始化为initialSelectionValue的输入值。

static String showInputDialog(Object message, Object initialSelectionValue)
4.通知框 

创建通知框方法有以下几种重载形式:

调出标题为Message的信息消息对话框。

static void showMessageDialog(Component parentComponent, Object message)

调出对话框,它显示使用由messageType 参数确定的默认图标的message。

static void showMessageDialog(Component parentComponent,

                Object message,

                String title,

                int messageType)

调出一个显示信息的对话框,为其指定了所有参数。

static void showMessageDialog(Component parentComponent,

                Object message,

                String title,

                int messageType,

                Icon icon)

常用布局管理器 

null绝对布局

例题18.7

import java.awt.*;
import javax.swing.*;
public class AbsolutePosition extends JFrame{//例题18.7
    public AbsolutePosition(){
        setTitle("本窗体使用绝对布局");        //窗体标题
        setLayout(null);                //使用null布局
        setBounds(0, 0, 300, 150);        //设置窗体的坐标与宽高
        Container c = getContentPane(); //获取主容器
        JButton b1=new JButton("按钮1");  //创建按钮
        JButton b2= new JButton("按钮2");
        b1.setBounds(10, 30, 80, 30);        //设置按钮的位置与大小
        b2.setBounds(60, 70, 100, 20);
        c.add(b1);                            //将按钮添加到容器中
        c.add(b2);
        setVisible(true);                    //使窗体可见
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//关闭窗体则停止程序
    }
    public static void main(String[] args) {
        new AbsolutePosition();
    }
}

运行结果如下:

 FlowLayout 流布局管理器

FlowLayout类具有以下常用的构造方法:

  • public FlowLayout()。
  • public FlowLayout(int alignment)。
  • public FlowLayout(int alignment,int horizGap,int vertGap)。

例题18.8

import java.awt.*;
import javax.swing.*;
public class FlowLayoutPosition extends JFrame {
    public FlowLayoutPosition(){
        setTitle("本窗体使用流布局管理器");        //设置窗体标题
        Container c = getContentPane();
        //窗体使用流布局,组件右对齐,组件之间的水平间隔为 10 像素,垂直间隔为 10像素
        setLayout(new FlowLayout(FlowLayout.RIGHT,10, 10));
        for (int i= 0;i< 10; i++){        //在容器中循环添加10个按钮
            c.add(new JButton("button" + i));
        }
            setSize(300,200);            //设置窗体大小
            setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); //关闭窗体则停止程序
            setVisible(true);            //设置窗体可见
    }
    public static void main(String[] args){
        new FlowLayoutPosition();
    }
}

运行结果如下:

BorderLayout 边界布局管理器 

addo方法被用于实现向容器中添加组件的功能,它可以设置组件的摆放位置。addO方法常用的语

法格式如下:

public void add(Component comp, Object constraints)
  • comp:被添加的组件。
  • constraints:被添加组件的布局约束对象。

例题18.9

import java.awt.*;
import javax.swing.*;
public class BorderLayoutPosition extends JFrame{
    public BorderLayoutPosition(){
        setTitle("这个窗体使用边界布局管理器");
        Container c = getContentPane();        //获取主容器
        setLayout(new BorderLayout());        //容器使用边界布局
        JButton centerBtn = new JButton("中");
        JButton northBtn = new JButton("北");
        JButton southBtn= new JButton("南");
        JButton westBtn = new JButton("西");
        JButton eastBtn = new JButton("东");
        c.add(centerBtn, BorderLayout.CENTER);        //中部添加按钮
        c.add(northBtn, BorderLayout.NORTH);        //北部添加按钮
        c.add(southBtn, BorderLayout.SOUTH);        //南部添加按钮
        c.add(westBtn, BorderLayout.WEST);            //西部添加按钮
        c.add(eastBtn, BorderLayout.EAST);            //东部添加按钮
        setSize(350, 200);                            //设置窗体大小
        setVisible(true);                            //设置窗体可见
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);            //关闭窗体则停止程序
    }
        public static void main(String[] args){
                new BorderLayoutPosition();
        }
}

 运行及如果如下:

GridLayout 网络布局管理器

网格布局管理器主要有以下两个常用的构造方法:

public GridLayout(int rows, int columns)
public GridLayout(int rows, int columns, int horizGap, int vertGap)


其中,参数rows 和columns分别代表网格的行数和列数,这两个参数只允许有一个参数可以为0,被用于表示一行或一列可以排列任意多个组件;参数horizGap和vertGap分别代表网格之间的水平间距和垂直间距。

例题18.10

import java.awt.*;
import javax.swing.*;
public class GridLayoutPosition extends JFrame{
    public GridLayoutPosition(){
            Container c = getContentPane();
            //设置容器使用网格布局管理器,设置7行3列的网格。组件间水平间距为5像素,垂直间距为5像素
            setLayout(new GridLayout(7, 3, 5, 5));
            for (int i=0;i<20; i++){
                c.add(new JButton("button"+i));            //循环添加按钮
            }
            setSize(300, 300);
            setTitle("这是一个使用网格布局管理器的窗体");
            setVisible(true);
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        }
            public static void main(String[] args){
                new GridLayoutPosition();
            }
        }

运行结果如下:

        

常用面板 

JPanel  面板
JPanel面板必须在窗体容器中使用,无法脱离窗体显示

JScrollPane 滚动面板 
JScrollPane 滚动面板 不能使用布局管理器,且只能容纳一个组件

JLable 标签

JLabel类常用的构造方法如下:

  • public JLabel0:创建一个不带图标或文本的标签。
  • public JLabel(Icon icon):创建一个带图标的标签。
  • public JLabel(Icon icon, int aligment):创建一个带图标的标签,并设置图标的水平对齐方式。
  • public JLabel(String text, int aligment):创建一个带文本的标签,并设置文本的水平对齐方式。
  • public JLabel(String text, Icon icon, int aligment):创建一个带文本和图标的JLabel对象,并设置文本和图标的水平对齐方式。

图标的使用

在Swing 程序设计中,图标经常被添加到标签、按钮等组件,使用javax.swing.Imagelcon类可以依据现有的图片创建图标。ImageIcon类实现了Icon接口,它有多个构造方法,常用的如下:

  • public ImagelconO:创建一个 Imagelcon 对象,创建 ImageIcon对象后,使用其调用 setImage(Image image)方法设置图片。
  • public Imagelcon(Image image):依据现有的图片创建图标。
  • public ImageIcon(URL url):依据现有图片的路径创建图标。

按钮组件 

JButton 按钮

Swing 按钮由JButton对象表示,JButton常用的构造方法如下:

  • public JButtonO:创建一个不带文本或图标的按钮。
  • public JButton(String text):创建一个带文本的按钮。
  • public JButton(Icon icon):创建一个带图标的按钮。
  • public JButton(String text, Icon icon):创建一个带文本和图标的按钮。
  • 创建JButon 对象后,如果要对JButton 对象进行设置,那么可以使用JButton类提供的方法。

JButton 类的常用方法及其说明如表18.6所示:

JRadinButton 单选按钮 
1.单选按钮

创建JRadioButton 对象需要使用JRadioButton 类的构造方法。JRadioButton类常用的构造方法如下:

  • public JRadioButton():创建一个未被选中、文本未被设定的单选按钮。
  • public JRadioButton(Icon icon):创建一个未被选中、文本未被设定,但具有指定图标的单选按钮。
  • public JRadioButton(Icon icon, boolean selected):创建一个具有指定图标、选择状态,但文本区未被设定的单选按钮。
  • public JRadioButton(String text):创建一个具有指定文本,但未被选中的单选按钮。
  • public JRadioButton(String text, Icon icon):创建一个具有指定文本、指定图标,但未被选中的单选按钮。
  • public JRadioButton(String text, Icon icon, boolean selected):创建一个具有指定的文本、指定图标和选择状态的单选按钮。

根据上述构造方法的相关介绍,不难发现,单选按钮的图标、文本和选择状态等属性能够被同时设定。例如,使用JRadioButton 类的构造方法创建一个文本为“选项 A”的单选按钮,关键代码如下:

JRadioButton rbtn = new JRadioButton("选项 A");
2.按钮组

Swing 按钮组由 ButtonGroup对象表示,多个单选按钮被添加到按钮组后,能够实现“选项有多个,

但只能选中一个”的效果。ButtonGroup 对象被创建后,可以使用addO方法把多个单选按钮添加到

ButtonGroup对象中。

JCheckBox 复选框 

JCheckBox的常用构造方法如下:

  • public JCheckBox():创建一个文本、图标未被设定且默认未被选中的复选框。
  • public JCheckBox(Icon icon, Boolean checked):创建一个具有指定图标、指定初始时是否被选中,但文本未被设定的复选框。
  • public JCheckBox(String text, Boolean checked):创建一个具有指定文本、指定初始时是否被选中,但图标未被设定的复选框。

列表组件 

JComboBox 下拉列表框

JComboBox 类的常用构造方法如下:

  • public JComboBox(ComboBoxModeldataModel):创建一个 JComboBox对象,下拉列表中的列表项使用ComboBoxModel中的列表项,ComboBoxModel 是一个用于组合框的数据模型。
  • public JComboBox(Object[]arrayData):创建一个包含指定数组中的元素的JComboBox对象。
  • public JComboBox(Vector vector):创建一个包含指定 Vector 对象中的元素的JComboBox 对象.Voetor对象中的元素可以通过整数索引进行访问,而且 Vector 对象中的元素可以根据需求被添加或者移除。

JComboBox类的常用方法及其说明如表18.7所示。

JList 列表框 

JList类的常用构造方法如下:

  • public void JList():创建一个空的JList对象。
  • public void JList(Object[] listData):创建一个显示指定数组中的元素的JList对象。
  • public void JList(Vector listData):创建一个显示指定 Vector 中的元素的JList对象。
  • public void JList(ListModel dataModel):创建一个显示指定的非 null模型的元素的JList对象。

文本组件 

JTextField文本框

文本框组件由JTextField对象表示。JTextField类的常用构造方法如下:

  • public JTextFieldO:创建一个文本未被指定的文本框。
  • public JTextField(String text):创建一个指定文本的文本框。
  • public JTextField(int fieldwidth):创建一个指定列宽的文本框。
  • public JTextField(String text, int fieldwidth):创建一个指定文本和列宽的文本框。
  • public JTextField(Document docModel, String text, int fieldWidth):创建一个指定文本模型、本内容和列宽的文本框。

如果要为一个文本未被指定的文本框设置文本内容,那么需要使用 setTextO方法。setText0方法的语法如下:

public void setText(String t)

其中,t表示文本框要显示的文本内容。

JPasswordField 密码框

密码框组件由JPasswordField对象表示,其作用是把用户输入的字符串以某种符号进行加密。JPasswordField类的常用构造方法如下

  • public JPasswordFieldO:创建一个文本未被指定的密码框。
  • public JPasswordFiled(String text):创建一个指定文本的密码框。
  • public JPasswordField(int fieldwidth):创建一个指定列宽的密码框。
  • public JPasswordField(String text, int fieldwidth):创建一个指定文本和列宽的密码框。
  • public JPasswordField(Document docModel, String text, int fieldWidth):创建一个指定文本模型和列宽的密码框。

JPasswordField 类提供了setEchoCharO方法,这个方法被用于改变密码框的回显字符。setEchoCharO方法的语法如下:

public void setEchoChar(char c)

其中,c表示密码框要显示的回显字符

JTextArea 文本域

文本城组件曲 JTextArea 对象表示,其作用是接受用户的多行文本输入。JTextArea类的常用构造方法如下:

  •  patie TextArea0:创建一个文本未被指定的文本域。
  • publie NTtextArea(String text):创建一个指定文本的文本域。
  • pabic leatAesfint rows,int columns):创建一个指定行高和列宽,但文本未被指定的文本域。
  • public JTextArea(Document doc): 创建一个指定文档模型的文本域。
  • public JTextArea(Document doc,String Text,int rows,int columns):创建内容以及行高和列宽的文本域。

表格组件

创建表格

JTable 类除提供了默认的构造方法外,还提供了被用于显示二维数组中的元素的构造方法,这个

构造方法的语法如下:

JTable(Object[][] rowData, Objectl columnNames)
  • rowData:存储表格数据的二维数组。
  • columnNames:存储表格列名的一维数组。
DefaultTableModel 表格数据模型

Swing 使用 TableModel 接口定义了一个表格模型,AbstractTableModel 抽象类实现了 TableModel接口的大部分方法,只有以下3个抽象方法没有实现:

  • public int getRowCountO);
  • public int getColumnCountO);
  • public Object getValueAt(int rowIndex, int columnIndex);
  • 为了实现使用表格模型创建表格的功能,Swing 提供了表格模型类,即DefaultTableModel类。DefaultTableModel 类继承了 AbstractTableModel 抽象类且实现了上述3个抽象方法。

DefaultTableModel类提供的常用构造方法如表18.8所示 

维护表格模型 

例题18.24

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;//例题18.24
public class AddAndDeleteDemo extends JFrame{
 
    private DefaultTableModel tableModel;
    private JTable table;
    private JTextField aTextField;
    private JTextField bTextField;
    public static void main(String args[]){
        AddAndDeleteDemo frame = new AddAndDeleteDemo();
        frame.setVisible(true);
    }
    public AddAndDeleteDemo(){
        setTitle("维护表格模型");
        setBounds(100, 100, 520, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JScrollPane scrollPane = new JScrollPane();
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        String[] columnNames = {"A","B"};        //定义表格列名数组
        //定义表格数据数组
        String[][] tableValues = {{"A1","B1"}, {"A2","B2"},{"A3","B3"}};
        //创建指定表格列名和表格数据的表格模型
        tableModel = new DefaultTableModel(tableValues,columnNames);
        table = new JTable(tableModel);        //创建指定表格模型的表格
        table.setRowSorter(new TableRowSorter<>(tableModel));    //设置表格的排序器
        //设置表格的选择模式为单选
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        //为表格添加鼠标事件监听器
        table.addMouseListener(new MouseAdapter(){
        public void mouseClicked(MouseEvent e) {    //发生了单击事件
        int selectedRow = table.getSelectedRow();    //获得被选中行的索引
        //从表格模型中获得指定单元格的值
        Object oa = tableModel.getValueAt(selectedRow, 0);
        //从表格模型中获得指定单元格的值
        Object ob = tableModel.getValueAt(selectedRow, 1);
        aTextField.setText(oa.toString());        //将值赋值给文本框
        bTextField.setText(ob.toString());        //将值赋值给文本框
        }
        });
        scrollPane.setViewportView(table);
        JPanel panel = new JPanel();
        getContentPane().add(panel, BorderLayout.SOUTH);
        panel.add(new JLabel("A:"));
        aTextField = new JTextField("A4", 10);
        panel.add(aTextField);
        panel.add(new JLabel("B:"));
        bTextField = new JTextField("B4", 10);
        panel.add(bTextField);
        JButton addButton = new JButton("添加");
        addButton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            String[] rowValues = {aTextField.getText(),
                bTextField.getText()};        //创建表格行数组
            tableModel.addRow(rowValues);    //向表格模型中添加一行
            int rowCount = table.getRowCount()+ 1;
            aTextField.setText("A"+ rowCount);
            bTextField.setText("B"+ rowCount);
            }
        });
        panel.add(addButton);
        JButton updButton = new JButton("修改");
        updButton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                int selectedRow = table.getSelectedRow();        //获得被选中行的索引
                if (selectedRow !=-1){                            //判断是否存在被选中行
                    //修改表格模型中的指定值
                    tableModel.setValueAt(aTextField.getText(), selectedRow, 0);
                    //修改表格模型中的指定值
                    tableModel.setValueAt(bTextField.getText(), selectedRow, 1);
                }
            }
        });                
        panel.add(updButton);
        JButton delButton = new JButton("删除");
        delButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e){
                int selectedRow = table.getSelectedRow();        //获得被选中行的索引
                if (selectedRow !=-1);                            //判断是否存在被选中行
                    tableModel.removeRow(selectedRow);            //从表格模型中删除指定行
                }
        });
        panel.add(delButton);
    }
}

运行结果如下:

事件监听器 

ActionEvent 动作事件

动作时间()ActionEvent监听器是Swing中比较常用的事件监听器,很多组件的动作都会使用它监听,例如按钮被单击等。

例题18.25

package 例题;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.WindowConstants;

public class 例题25 extends JFrame{
	private JButton jb = new JButton("我是按钮,点击我");
	
	public 例题25() {
		setLayout(null);
		setSize(200, 100);
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		Container c = getContentPane();
		c.add(jb);
		jb.setBounds(10, 10, 150, 30);
		jb.addActionListener(new jbAction());
		setVisible(true);
		setLocation(500, 350);
	}
	class jbAction implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			jb.setText("我被点击了");
			
		}
		
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new 例题25();
	}

}

运行结果如下:

KeyEvent 键盘事件 

当向文本框中输入内容时,将发生键盘事件。KeyEvent类负责捕获键盘事件,可以通过为组件添加实现了KeyListener接口的监听器类来处理相应的键盘事件。

KeyListener接口共有三个抽象方法,分别在发生击键事件(按下并释放键)、按键被按下(手指按下键但不松开)和按键被释放(手指从按下的键松开)时被触发,具体如下:

public interface KeyListener extends EventListener {

        public void keyTyped(KeyEvent e);                //发生击键事件时被触发

        public void keyPressed(KeyEvent e);              //按键被按下时被触发

        public void keyReleased(KeyEvent e);                //按键被释放时被触发

 KeyEvent常用方法如下:


例题18.26

import java.awt.BorderLayout;
import java.awt.EventQueue;
 
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.Color;
import java.awt.Component;
 
import javax.swing.JButton;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
 
import javax.swing.JTextField;
 
// 虚拟键盘(键盘的按下与释放)
 
public class KeyBoard extends JFrame { // 创建“键盘”类继承JFrame
    // 声明窗体中的成员组件
    private JPanel contentPane;
    private JTextField textField;
    private JButton btnQ;
    private JButton btnW;
    private JButton btnE;
    private JButton btnR;
    private JButton btnT;
    private JButton btnY;
    private JButton btnU;
    private JButton btnI;
    private JButton btnO;
    private JButton btnP;
    private JButton btnA;
    private JButton btnS;
    private JButton btnD;
    private JButton btnF;
    private JButton btnG;
    private JButton btnH;
    private JButton btnJ;
    private JButton btnK;
    private JButton btnL;
    private JButton btnZ;
    private JButton btnX;
    private JButton btnC;
    private JButton btnV;
    private JButton btnB;
    private JButton btnN;
    private JButton btnM;
    Color green = Color.GREEN;// 定义Color对象,用来表示按下键的颜色
    Color white = Color.WHITE;// 定义Color对象,用来表示释放键的颜色
 
    ArrayList<JButton> btns = new ArrayList<JButton>();// 定义一个集合,用来存储所有的按键ID
    // 自定义一个方法,用来将容器中的所有JButton组件添加到集合中
 
    private void addButtons() {
        for (Component cmp : contentPane.getComponents()) {// 遍历面板中的所有组件
            if (cmp instanceof JButton) {// 判断组件的类型是否为JButton类型
                btns.add((JButton) cmp);// 将JButton组件添加到集合中
            }
        }
    }
 
    //主方法
     
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() { // 使得Runnable中的的run()方法在the system EventQueue的指派线程中被调用
            public void run() {
                try {
                    KeyBoard frame = new KeyBoard(); // 创建KeyBoard对象
                    frame.setVisible(true); // 使frame可视
                    frame.addButtons();// 初始化存储所有按键的集合
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
 
    // 创建JFrame窗体
     
    public KeyBoard() { // KeyBoard的构造方法
        setTitle("\u865A\u62DF\u952E\u76D8\uFF08\u6A21\u62DF\u952E\u76D8\u7684\u6309\u4E0B\u4E0E\u91CA\u653E\uFF09"); // 设置窗体题目
        setResizable(false); // 不可改变窗体宽高
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设置窗体关闭的方式
        setBounds(100, 100, 560, 280); // 设置窗体的位置和宽高
        //创建JPanel面板contentPane置于JFrame窗体中,并设置面板的背景色、边距和布局
         
        contentPane = new JPanel();
        contentPane.setBackground(Color.WHITE);
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
        //创建按钮button置于面板contentPane中,设置按钮的背景色、位置、宽高以及按钮中的字体位置、内容、样式
        btnQ = new JButton("Q");
        btnQ.setBackground(white);
        btnQ.setVerticalAlignment(SwingConstants.TOP);
        btnQ.setHorizontalAlignment(SwingConstants.LEADING);
        btnQ.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        btnQ.setBounds(0, 60, 47, 45);
        contentPane.add(btnQ);
        // 创建按钮button_2置于面板contentPane中,设置按钮的背景色、位置、宽高以及按钮中的字体位置、内容、样式
         
        btnW = new JButton("W");
        btnW.setBackground(white);
        btnW.setVerticalAlignment(SwingConstants.TOP);
        btnW.setHorizontalAlignment(SwingConstants.LEADING);
        btnW.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        btnW.setBounds(55, 60, 49, 45);
        contentPane.add(btnW);
        // 创建按钮button_3置于面板contentPane中,设置按钮的背景色、位置、宽高以及按钮中的字体位置、内容、样式
         
        btnE = new JButton("E");
        btnE.setBackground(white);
        btnE.setVerticalAlignment(SwingConstants.TOP);
        btnE.setHorizontalAlignment(SwingConstants.LEADING);
        btnE.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        btnE.setBounds(110, 60, 45, 45);
        contentPane.add(btnE);
        // 创建按钮button_4置于面板contentPane中,设置按钮的背景色、位置、宽高以及按钮中的字体位置、内容、样式
        
        btnR = new JButton("R");
        btnR.setBackground(white);
        btnR.setVerticalAlignment(SwingConstants.TOP);
        btnR.setHorizontalAlignment(SwingConstants.LEADING);
        btnR.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        btnR.setBounds(165, 60, 45, 45);
        contentPane.add(btnR);
        // 创建按钮button_5置于面板contentPane中,设置按钮的背景色、位置、宽高以及按钮中的字体位置、内容、样式
         
        btnF = new JButton("F");
        btnF.setBackground(white);
        btnF.setVerticalAlignment(SwingConstants.TOP);
        btnF.setHorizontalAlignment(SwingConstants.LEADING);
        btnF.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        btnF.setBounds(195, 125, 45, 45);
        contentPane.add(btnF);
        //创建按钮button_6置于面板contentPane中,设置按钮的背景色、位置、宽高以及按钮中的字体位置、内容、样式
         
        btnD = new JButton("D");
        btnD.setBackground(white);
        btnD.setVerticalAlignment(SwingConstants.TOP);
        btnD.setHorizontalAlignment(SwingConstants.LEADING);
        btnD.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        btnD.setBounds(137, 125, 45, 45);
        contentPane.add(btnD);
 
        btnT = new JButton("T");
        btnT.setVerticalAlignment(SwingConstants.TOP);
        btnT.setHorizontalAlignment(SwingConstants.LEADING);
        btnT.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        btnT.setBackground(white);
        btnT.setBounds(220, 60, 45, 45);
        contentPane.add(btnT);
 
        btnY = new JButton("Y");
        btnY.setVerticalAlignment(SwingConstants.TOP);
        btnY.setHorizontalAlignment(SwingConstants.LEADING);
        btnY.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        btnY.setBackground(white);
        btnY.setBounds(275, 60, 45, 45);
        contentPane.add(btnY);
 
        btnU = new JButton("U");
        btnU.setVerticalAlignment(SwingConstants.TOP);
        btnU.setHorizontalAlignment(SwingConstants.LEADING);
        btnU.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        btnU.setBackground(white);
        btnU.setBounds(330, 60, 45, 45);
        contentPane.add(btnU);
 
        btnI = new JButton("I");
        btnI.setVerticalAlignment(SwingConstants.TOP);
        btnI.setHorizontalAlignment(SwingConstants.LEADING);
        btnI.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        btnI.setBackground(white);
        btnI.setBounds(385, 60, 45, 45);
        contentPane.add(btnI);
 
        btnO = new JButton("O");
        btnO.setVerticalAlignment(SwingConstants.TOP);
        btnO.setHorizontalAlignment(SwingConstants.LEADING);
        btnO.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        btnO.setBackground(white);
        btnO.setBounds(440, 60, 46, 45);
        contentPane.add(btnO);
 
        btnP = new JButton("P");
        btnP.setVerticalAlignment(SwingConstants.TOP);
        btnP.setHorizontalAlignment(SwingConstants.LEADING);
        btnP.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        btnP.setBackground(white);
        btnP.setBounds(495, 60, 45, 45);
        contentPane.add(btnP);
 
        btnA = new JButton("A");
        btnA.setVerticalAlignment(SwingConstants.TOP);
        btnA.setHorizontalAlignment(SwingConstants.LEADING);
        btnA.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        btnA.setBackground(white);
        btnA.setBounds(23, 125, 45, 45);
        contentPane.add(btnA);
 
        btnS = new JButton("S");
        btnS.setVerticalAlignment(SwingConstants.TOP);
        btnS.setHorizontalAlignment(SwingConstants.LEADING);
        btnS.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        btnS.setBackground(white);
        btnS.setBounds(82, 125, 45, 45);
        contentPane.add(btnS);
 
        btnG = new JButton("G");
        btnG.setVerticalAlignment(SwingConstants.TOP);
        btnG.setHorizontalAlignment(SwingConstants.LEADING);
        btnG.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        btnG.setBackground(white);
        btnG.setBounds(251, 125, 45, 45);
        contentPane.add(btnG);
 
        btnH = new JButton("H");
        btnH.setVerticalAlignment(SwingConstants.TOP);
        btnH.setHorizontalAlignment(SwingConstants.LEADING);
        btnH.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        btnH.setBackground(white);
        btnH.setBounds(306, 125, 45, 45);
        contentPane.add(btnH);
 
        btnJ = new JButton("J");
        btnJ.setVerticalAlignment(SwingConstants.TOP);
        btnJ.setHorizontalAlignment(SwingConstants.LEADING);
        btnJ.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        btnJ.setBackground(white);
        btnJ.setBounds(361, 125, 45, 45);
        contentPane.add(btnJ);
 
        btnK = new JButton("K");
        btnK.setVerticalAlignment(SwingConstants.TOP);
        btnK.setHorizontalAlignment(SwingConstants.LEADING);
        btnK.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        btnK.setBackground(white);
        btnK.setBounds(416, 125, 47, 45);
        contentPane.add(btnK);
 
        btnL = new JButton("L");
        btnL.setVerticalAlignment(SwingConstants.TOP);
        btnL.setHorizontalAlignment(SwingConstants.LEADING);
        btnL.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        btnL.setBackground(white);
        btnL.setBounds(471, 125, 45, 45);
        contentPane.add(btnL);
 
        btnZ = new JButton("Z");
        btnZ.setVerticalAlignment(SwingConstants.TOP);
        btnZ.setHorizontalAlignment(SwingConstants.LEADING);
        btnZ.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        btnZ.setBackground(white);
        btnZ.setBounds(39, 190, 45, 45);
        contentPane.add(btnZ);
 
        btnX = new JButton("X");
        btnX.setVerticalAlignment(SwingConstants.TOP);
        btnX.setHorizontalAlignment(SwingConstants.LEADING);
        btnX.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        btnX.setBackground(white);
        btnX.setBounds(107, 190, 45, 45);
        contentPane.add(btnX);
 
        btnC = new JButton("C");
        btnC.setVerticalAlignment(SwingConstants.TOP);
        btnC.setHorizontalAlignment(SwingConstants.LEADING);
        btnC.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        btnC.setBackground(white);
        btnC.setBounds(178, 190, 45, 45);
        contentPane.add(btnC);
 
        btnV = new JButton("V");
        btnV.setVerticalAlignment(SwingConstants.TOP);
        btnV.setHorizontalAlignment(SwingConstants.LEADING);
        btnV.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        btnV.setBackground(white);
        btnV.setBounds(250, 190, 45, 45);
        contentPane.add(btnV);
 
        btnB = new JButton("B");
        btnB.setVerticalAlignment(SwingConstants.TOP);
        btnB.setHorizontalAlignment(SwingConstants.LEADING);
        btnB.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        btnB.setBackground(white);
        btnB.setBounds(315, 190, 45, 45);
        contentPane.add(btnB);
 
        btnN = new JButton("N");
        btnN.setVerticalAlignment(SwingConstants.TOP);
        btnN.setHorizontalAlignment(SwingConstants.LEADING);
        btnN.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        btnN.setBackground(white);
        btnN.setBounds(382, 190, 47, 45);
        contentPane.add(btnN);
 
        btnM = new JButton("M");
        btnM.setVerticalAlignment(SwingConstants.TOP);
        btnM.setHorizontalAlignment(SwingConstants.LEADING);
        btnM.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        btnM.setBackground(white);
        btnM.setBounds(449, 190, 48, 45);
        contentPane.add(btnM);
        // 创建面板panel置于面板contentPane中,设置面板panel的位置、宽高、TitledBorder、背景色以及布局方式(边界布局)
         
        JPanel panel = new JPanel();
        panel.setBorder(new TitledBorder(null, "文本显示区", TitledBorder.LEADING, TitledBorder.TOP, null, null));
        panel.setBackground(Color.WHITE);
        panel.setBounds(0, 0, 540, 45);
        contentPane.add(panel);
        panel.setLayout(new BorderLayout(0, 0));
 
        // 创建文本框textField置于面板panel的中间
         
        textField = new JTextField();
        textField.addKeyListener(new KeyAdapter() { // 文本框添加键盘事件的监听
            char word;
 
            @Override
            public void keyPressed(KeyEvent e) { // 按键被按下时被触发
                word = e.getKeyChar();// 获取按下键表示的字符
                for (int i = 0; i < btns.size(); i++) {// 遍历存储按键ID的ArrayList集合
                    // 判断按键是否与遍历到的按键的文本相同
                    if (String.valueOf(word).equalsIgnoreCase(btns.get(i).getText())) {
                        btns.get(i).setBackground(green);// 将指定按键颜色设置为绿色
                    }
                }
            }
 
            @Override
            public void keyReleased(KeyEvent e) { // 按键被释放时被触发
                word = e.getKeyChar();// 获取释放键表示的字符
                for (int i = 0; i < btns.size(); i++) {// 遍历存储按键ID的ArrayList集合
                    // 判断按键是否与遍历到的按键的文本相同
                    if (String.valueOf(word).equalsIgnoreCase(btns.get(i).getText())) {
                        btns.get(i).setBackground(white);// 将指定按键颜色设置为白色
                    }
                }
            }
        });
        panel.add(textField, BorderLayout.CENTER);
        textField.setColumns(10);
    }
}

运行结果如下 :

MouseEvent 鼠标事件 

所有组件都能发生鼠标事件,MouseEvent类负责捕获鼠标事件,可以通过为组件添加实现MouseListener接口的监听器来处理相应的鼠标事件。

MouseListener接口的监听器来处理相应的鼠标事件。
MouseListener接口共有5个抽象方法,分别在光标移入或者移出组件、鼠标按键被按下或释放和发生单击事件时被触发。所谓单击事件,就是按键被按下并释放。需要注意的是,如果按键是在移出组件之后才被释放,则不会触发单击事件。MouseListener接口的具体定义如下:

public interface MouseListener extends EventListener {

        public void mouseEntered(MouseEvent e);        //光标移入组件时被触发

        public void mousePressed(MouseEvent e);        //鼠标按键被按下时被触发

        public void mouseReleased(MouseEvent e);      //鼠标按键被释放时被触发

        public void mouseClicked(MouseEvent e);        //发生单击事件时被触发

        public void mouseExited(MouseEvent e);        //光标移出组件时被触发

在上述每个抽象方法中,均传入了MouseEvent类的对象。MouseEvent类中比较常用的方法如表18.11: 


当 需要判断触发此次事件的按键时,可以通过表18.12中的静态常量判断由getButton()方法返回的int型值代表的键。

例题18.27

import java.awt.BorderLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
 
import javax.swing.JFrame;
import javax.swing.JLabel;
 
public class MouseEventDemo extends JFrame { // 继承窗体类JFrame
 
    public static void main(String args[]) {
        MouseEventDemo frame = new MouseEventDemo();
        frame.setVisible(true); // 设置窗体可见,默认为不可见
    }
 
    /**
     * 判断按下的鼠标键,并输出相应提示
     * 
     * @param e 鼠标事件
     */
    private void mouseOper(MouseEvent e) {
        int i = e.getButton();
        if(i==MouseEvent.BUTTON1)
            System.out.println("按下的是鼠标左键");
        else if(i==MouseEvent.BUTTON2)
            System.out.println("按下的是鼠标滚轮");
        else if(i==MouseEvent.BUTTON3)
            System.out.println("按下的是鼠标右键");
    }
 
    public MouseEventDemo() {
        super(); // 继承父类的构造方法
        setTitle("鼠标事件示例"); // 设置窗体的标题
        setBounds(100, 100, 500, 375); // 设置窗体的显示位置及大小
        // 设置窗体关闭按钮的动作为退出
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        final JLabel label = new JLabel();
        label.addMouseListener(new MouseListener() {
            public void mouseEntered(MouseEvent e) {
                System.out.println("光标移入组件");
            }
            public void mousePressed(MouseEvent e) {
                System.out.print("鼠标按键被按下,");
                mouseOper(e);
            }
            public void mouseReleased(MouseEvent e) {
                System.out.print("鼠标按键被释放,");
                mouseOper(e);
            }
            public void mouseClicked(MouseEvent e) {
                System.out.print("单击了鼠标按键,");
                mouseOper(e);
                int clickCount = e.getClickCount();
                System.out.println("单击次数为"+clickCount+"下");
            }
            public void mouseExited(MouseEvent e) {
                System.out.println("光标移出组件");
            }
        });
        getContentPane().add(label, BorderLayout.CENTER);
    }
 
}

运行结果如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值