Java-Swing程序设计

太平_十九 2024-06-20 12:05:03 阅读 68

文章目录

Swing概述Swing常用窗体1、JFrame窗体2、JDialog对话框3、JOptionPane小型对话框 常用布局管理器1、null绝对布局2、FlowLayout流 布局管理器3、BorderLayout 边界 布局管理器4、GridLayout 网格布局管理器 常用面板JScrollPane滚动面板 文字标签组件与图标1、JLabrl标签2、图标的使用 按钮组件1、JButto按钮2、JRadioButton单选按钮2、JCheckBox复选框 列表组件1、JComboBox下拉列表框2、JList列表框 文本组件1、JTextField文本框2、JPasswordField密码框3、 JTextArea文本域 表格组件1、创建表格2、DefaultTableModel表格数据模型3、维护表格模型 事件监听器1、ActionEvent动作事件2、KeyEvent键盘事件监听器3、MouseEvent鼠标事件

Swing概述

Swing是Java平台的一部分,它是一个用于开发Java应用程序用户界面的开发工具包。

Swing的主要目的是提供一个跨平台的用户界面工具包,让开发人员能够轻松地创建具有丰富用户界面的应用程序,并且这些应用程序可以在不同的操作系统上运行。Swing是基于Java AWT(抽象窗口工具包)构建的,通过提供一组跨平台的GUI组件和布局管理器来解决AWT主要问题的不跨平台

Swing开发人员只用很少的代码就可以利用Swing丰富、灵活的功能和模块化组件来创建优雅的用户界面。


Swing常用窗体

Swing是Java的一个图形用户界面(GUI)工具包,它提供了创建窗口、对话框、按钮等图形元素所需要的类。

以下时Swing中的常用窗体简介:

JFrame:这是Swing中一个顶层窗口容器,可以用来创建窗口、对话框等。它包含了窗口的一些基本属性,如标题、大小、位置等。JDialog:这是Swing中的一个对话框容器,通常用于在用户需要输入一些信息或者做出一些选择时弹出。它也包含了对话框的一些属性,如标题、内容、大小等。JWindow:这是Swing中的一个无标题的顶级窗口容器,通常用于创建一些不需要标题的窗口。JInternalFrame:这是Swing中的一个内部窗口容器,通常用于在桌面应用程序中创建多个窗口,这些窗口可以像浏览器标签一样堆叠在一起。JFrame.JContentPane:这是Swing中的一个内容面板,它可以将组件放置在其上,并且可以包含滚动条、边框等。它通常用于创建一些需要放置多个组件的窗口。JScrollPane:这是Swing中的一个滚动面板,它可以包含另一个面板或者组件,并且可以在需要时显示滚动条。它通常用于创建一些需要显示大量内容的窗口。


1、JFrame窗体

JFrame是Java Swing库中的一个顶层窗口容器,它提供了创建窗口的基本功能,是Swing应用程序中创建窗口的基类。

JFrame具有以下特点

JFrame是一个顶级窗口,必须添加内容才能显示窗口。JFrame可以添加各种组件,如按钮、文本框、标签等。JFrame具有默认的关闭操作,可以关闭窗口。JFrame可以设置窗口大小、标题等属性。


JFrame的主要方法包括:

setTitle(String title):设置窗口标题。setDefaultCloseOperation(int operation):设置窗口关闭操作,例如JFrame.EXIT_ON_CLOSE(关闭时退出程序)、JFrame.DISPOSE_ON_CLOSE(关闭时结束程序并释放窗口)等。setBounds(int x, int y, int width, int height):设置窗口大小和位置。add(Component component):添加组件到窗口中。remove(Component component):从窗口中移除组件。setLayout(LayoutManager manager):设置窗口的布局管理器。getContentPane():获取内容窗格。getRootPane():获取根窗格。getWindowDecorationStyle():获取窗口装饰样式。setWindowDecorationStyle(int style):设置窗口装饰样式。


示例

public class Main { public static void main(String[] args) { JFrame jf = new JFrame("第一个窗体"); jf.setSize(500,500); // 设置大小 jf.setAlwaysOnTop(true); // 顶层显示方法 jf.setLocationRelativeTo(null); // 将窗口位置设置为屏幕中心 jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE); //设置关闭模式,关闭模式设置为关闭窗体时释放窗体资源并结束程序 jf.setVisible(true); //设置为显示 }}


2、JDialog对话框

JDialog是Java Swing库中的一个对话框窗体,它继承了AWT组件中的java.awt.Dialog类。JDialog窗体的功能是从一个窗体中弹出另一个窗体,类似于在使用IE浏览器时弹出的确定对话框。

JDialog窗体与JFrame窗体类似,它们都是顶层窗口容器,但是JDialog窗体通常用于创建模态对话框,可以与用户进行交互并获取用户输入。


JDialog窗体具有以下特点:

可以创建模式对话框和非模式对话框。模式对话框会阻塞用户对其他窗口的访问,直到用户关闭该对话框或通过操作按钮取消对话框。非模式对话框不会阻塞用户对其他窗口的访问。可以添加各种组件,如按钮、文本框、标签等。可以设置对话框的标题、大小、位置等属性。对话框默认情况下没有关闭操作,需要手动添加关闭操作。


JDialog的主要方法包括:

setTitle(String title):设置对话框标题。setModal(boolean modal):设置对话框是否为模式对话框。setBounds(int x, int y, int width, int height):设置对话框大小和位置。add(Component component):添加组件到对话框中。remove(Component component):从对话框中移除组件setLayout(LayoutManager manager):设置对话框的布局管理器。getContentPane():获取内容窗格。getRootPane():获取根窗格。getWindowDecorationStyle():获取窗口装饰样式。setWindowDecorationStyle(int style):设置窗口装饰样式。


示例

import javax.swing.*; import java.awt.*; import java.awt.event.*; public class DialogExample { private JFrame frame; private JButton button; private JDialog dialog; private JTextField textField; public DialogExample() { // 创建主窗口 frame = new JFrame("Dialog Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设置关闭模式 frame.setSize(300, 200); // 设置大小 frame.setLayout(new BorderLayout()); // 创建按钮并添加到主窗口中 button = new JButton("Show Dialog"); frame.add(button, BorderLayout.NORTH); // 创建对话框 dialog = new JDialog(); dialog.setTitle("Input Dialog"); dialog.setModal(true); // 设置为模式对话框 dialog.setSize(300, 200); dialog.setLayout(new BorderLayout()); // 创建文本框并添加到对话框中 textField = new JTextField(20); dialog.add(textField, BorderLayout.CENTER); // 显示主窗口 frame.setVisible(true); } public static void main(String[] args) { // 创建示例对象 DialogExample example = new DialogExample(); } }


在以上示例中,我们创建了一个主窗口(JFrame),并在其中添加了一个按钮(JButton)。当用户点击按钮时,会弹出一个模态对话框(JDialog),其中包含一个文本框(JTextField)。用户可以在文本框中输入内容,然后关闭对话框。在关闭对话框后,用户可以继续操作主窗口。


3、JOptionPane小型对话框

JOptionPane是Java Swing库中的一个用于显示对话框的类。它提供了一些方便的方法来创建各种类型的对话框,例如确认对话框、输入对话框、消息对话框等。

JOptionPane的主要方法包括:

showMessageDialog(Component parentComponent, String message):显示一个包含指定消息的对话框。showInputDialog(Component parentComponent, String prompt, String title, int messageType):显示一个包含输入框的对话框,用于获取用户输入。showConfirmDialog(Component parentComponent, String message, String title, int optionType):显示一个确认对话框,用于让用户选择是否继续操作。


示例:

import javax.swing.*; import java.awt.*; public class OptionPaneExample { public static void main(String[] args) { // 创建JFrame窗口 JFrame frame = new JFrame("OptionPane Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); frame.setLayout(new BorderLayout()); // 添加按钮并添加事件监听器 JButton button = new JButton("Show Message Dialog"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // 显示消息对话框 JOptionPane.showMessageDialog(frame, "Hello World!"); } }); frame.add(button, BorderLayout.NORTH); // 显示窗口 frame.setVisible(true); } }


在以上示例中,我们创建了一个JFrame窗口,并在其中添加了一个按钮。当用户点击按钮时,会弹出一个包含"Hello World!"消息的消息对话框。


常用布局管理器

在Java的Swing库中,布局管理器是一种用于自动调整组件位置和大小的机制。它们使得开发人员可以创建复杂的用户界面,而无需手动计算每个组件的位置和大小。

以下是Java中常用的几种布局管理器:

BorderLayout:这是默认的布局管理器,它将容器分为5个区域:北(NORTH)、南(SOUTH)、东(EAST)、西(WEST)和中(CENTER。你可以将组件添加到这些区域中。注意,每个区域只能包含一个组件。FlowLayout:此布局管理器将组件按照水平或垂直方向排列。如果容器宽度或高度不足以容纳所有的组件,那么会换行或换列。GridLayout:此布局管理器将容器分为行和列,形成网格。你可以指定行数和列数,然后添加组件到网格的特定位置。CardLayout:此布局管理器用于显示一个组件集合中的某一个组件。当用户切换卡时,显示不同的组件。例如,你可以使用它来在多个用户界面之间切GridBagLayout:这是一个更复杂的布局管理器,允许组件占据多个行或列的空间。你可以设置组件的位置、大小、填充方式、对齐方式等。BoxLayout:此布局管理器将组件在一行或一列中布局,可以指定组件的对齐方式。SpringLayout:此布局管理器允许组件在网格中的位置和大小由周围的组件决定,就像弹簧一样。通常与其他布局管理器(如GridLayout)结合使用。BorderLayoutManager:这是Java 11中新增的布局管理器,它实现了BorderLayout,但添加了一些额外的功能。例如,它可以处理组件的溢出,当组件的大小超过其容器的大小时,会显示一个滚动条。


以上布局管理器各有优缺点,使用哪个取决于你的具体需求。


1、null绝对布局

Java中的null绝对布局是一种特殊的布局方式,它没有特定的布局管理器类来表示,而是通过设置组件的坐标和宽高来布置组件。

在这种布局方式下,开发人员需要明确指定每个组件的坐标和宽高,否则组件将无法显示。使用其他布局时,如果在窗口显示之后添加新组件,该组件也需要手动指定坐标和宽高。同样,如果在窗口显示之后修改之前添加的组件的坐标和宽高,该组件也会被当做绝对布局对待,此时修改坐标和宽高会生效。

在进行null绝对布局时,setBounds方法是关键。setBounds方法的函数为public void setBounds(int x,int y,int width,int height),其中x、y表示组件右上角坐标,width、height分别表示组件的宽和高,单位为像素。

总的来说,null绝对布局是一种基于坐标和尺寸的布局方式,需要手动指定每个组件的位置和大小。


示例:

import javax.swing.*;import java.awt.*;import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class Main { public static void main(String[] args) { JFrame frame = new JFrame("Null Layout Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 300); frame.setLayout(null); // 设置布局为null绝对布局 // 添加组件并设置位置和大小 JButton button1 = new JButton("按钮 1"); button1.setBounds(10, 10, 80, 30); frame.add(button1); JButton button2 = new JButton("按钮 2"); button2.setBounds(100, 10, 80, 30); frame.add(button2); JButton button3 = new JButton("按钮 3"); button3.setBounds(190, 10, 80, 30); frame.add(button3); // 显示窗口 frame.setVisible(true); }}


效果:

在这里插入图片描述


2、FlowLayout流 布局管理器

Java中的FlowLayout流布局管理器是一种简单的布局管理器,它将组件按照水平或垂直方向排列。在FlowLayout中,组件的排列顺序取决于容器的组件添加顺序。

FlowLayout有两个主要的属性:hgap和vgaphgap属性用于设置水平方向上两个组件之间的间距vgap属性用于设置垂直方向上两个组件之间的间距

在FlowLayout中,每个组件的位置是由其添加的顺序决定的。如果容器宽度不足以容纳所有组件,那么会换行或换列,以便容纳所有的组件。

如果容器高度不足以容纳所有组件,那么会根据组件的尺寸和排列顺序来决定是否换行或换列。


示例:

import javax.swing.*;import java.awt.*;import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class Main { public static void main(String[] args) { JFrame frame = new JFrame("FlowLayout Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); // 创建FlowLayout布局管理器并设置间距 FlowLayout layout = new FlowLayout(); layout.setHgap(10); layout.setVgap(10); frame.setLayout(layout); // 添加组件并设置位置和大小 JButton button1 = new JButton("Button 1"); frame.add(button1); // 直接添加到frame中,布局管理器会根据组件的尺寸和排列顺序自动调整位置和大小 JButton button2 = new JButton("Button 2"); frame.add(button2); // 直接添加到frame中,布局管理器会根据组件的尺寸和排列顺序自动调整位置和大小 JButton button3 = new JButton("Button 3"); frame.add(button3); // 直接添加到frame中,布局管理器会根据组件的尺寸和排列顺序自动调整位置和大小 // 显示窗口 frame.setVisible(true); }}

效果:

在这里插入图片描述


3、BorderLayout 边界 布局管理器

Java中的BorderLayout边界布局管理器是一种常见的布局管理器,它将容器分为5个区域:北(NORTH)、南(SOUTH)、东(EAST)、西(WEST)和中(CENTER)。 你可以将组件添加到这些区域中。

使用BorderLayout布局管理器时,每个区域只能包含一个组件。如果尝试将多个组件添加到同一个区域,则只有最后一个组件会显示在该区域中。


以下是BorderLayout布局管理器的特点:

每个区域只能包含一个组件。组件不能覆盖多个区域。组件的添加顺序不重要。组件的尺寸由其自身的大小和容器的大小决定。可以使用组件的setBounds方法设置组件的位置和大小。


示例:

import javax.swing.*;import java.awt.*;public class Main { public static void main(String[] args) { JFrame frame = new JFrame("BorderLayout Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 300); frame.setLayout(new BorderLayout()); // 设置布局为BorderLayout // 添加组件并设置位置和大小 JButton button1 = new JButton("北"); button1.setBounds(10, 10, 80, 30); // 设置位置和大小 frame.add(button1, BorderLayout.NORTH); // 将按钮添加到NORTH区域 JButton button2 = new JButton("中"); button2.setBounds(10, 50, 80, 30); // 设置位置和大小 frame.add(button2, BorderLayout.CENTER); // 将按钮添加到CENTER区域 JButton button3 = new JButton("南"); button3.setBounds(10, 90, 80, 30); // 设置位置和大小 frame.add(button3, BorderLayout.SOUTH); // 将按钮添加到SOUTH区域 JButton button4 = new JButton("东"); button4.setBounds(100, 10, 80, 30); // 设置位置和大小 frame.add(button4, BorderLayout.EAST); // 将按钮添加到EAST区域 JButton button5 = new JButton("西"); button5.setBounds(190, 10, 80, 30); // 设置位置和大小 frame.add(button5, BorderLayout.WEST); // 将按钮添加到WEST区域 // 显示窗口 frame.setVisible(true); }}


效果:


4、GridLayout 网格布局管理器

GridLayout 网格布局管理器能够把容器划分为网格,组件可以按行列进行排列。

在网格布局管理器中,网格的个数由行数和列数决定,且每个网格的大小都相同。从网格的左上角开始,按照从左到右,从上到下的顺序被添加到网格中,且每个组件都会填满整个网格。改变窗口大小的同时,组件的大小也会随之改变

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

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

rows和columns这两个参数只允许有一个参数可以为零,被用于表示一行或一列可以排列任意多个组件

import javax.swing.*;import java.awt.*;import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class Main extends JFrame { public Main(){ 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 Main(); }}


效果图

在这里插入图片描述


常用面板

在Swing程序设计中,面板是一个容器,被用于容纳其他组件,

但面板必须被添加到其他容器中。Swing中常用的面板包括JPanel面板和JScrollpane面板

JPanel面板继承Java.awt.Container类,JPanel面板必须在窗体容器中使用,无法脱离窗体显示


示例:

import javax.swing.*;import java.awt.*;import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class Main extends JFrame { public Main(){ Container c=getContentPane();//获取窗体主容器 //将整个容器设置为2行2列的网格布局,组件水平间隔10像素,垂直间隔10像素 c.setLayout(new GridLayout(2,2,10,10)); //初始化一个面板,此面板使用1行4列的网格布局,组件水平间隔10像素,垂直间隔10像素 JPanel p1=new JPanel(new GridLayout(1,4,10,10)); //初始化一个面板,此面板使用边界布局 JPanel p2=new JPanel(new BorderLayout()); JPanel p3=new JPanel(new GridLayout(1,2,10,10)); JPanel p4=new JPanel(new GridLayout(2,1,10,10)); //给每个面板都添加边框和标题,使用 BorderFactory 工厂类生成带标题的边框对象 p1.setBorder(BorderFactory.createTitledBorder("面板1")); p2.setBorder(BorderFactory.createTitledBorder("面板2")); p3.setBorder(BorderFactory.createTitledBorder("面板3")); p4.setBorder(BorderFactory.createTitledBorder("面板4")); //向面板1中添加按钮 p1.add(new JButton("b1")); p1.add(new JButton("b1")); p1.add(new JButton("b1")); p1.add(new JButton("b1")); //向面板2中添加按钮 p2.add(new JButton("b2"),BorderLayout.WEST); p2.add(new JButton("b2"),BorderLayout.EAST); p2.add(new JButton("b2"),BorderLayout.NORTH); p2.add(new JButton("b2"),BorderLayout.SOUTH); p2.add(new JButton("b2"),BorderLayout.CENTER); //向面板3中添加按钮 p3.add(new JButton("b3")); p3.add(new JButton("b3")); //向面板4中添加按钮 p4.add(new JButton("b4")); p4.add(new JButton("b4")); //向容器中添加面板 c.add(p1); c.add(p2); c.add(p3); c.add(p4); setTitle("这个窗体中使用了面板"); setSize(500,300);//窗体宽高 setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);//关闭动作 } public static void main(String[] args) { Main p = new Main(); p.setVisible(true); }}

运行效果:

在这里插入图片描述


JScrollPane滚动面板

JScrollPane面板,是带滚动条的面板,被用于在较小的窗体中显示较大篇幅的内容,要注意的是,不能使用布局管理器,只能容纳一个组件,如果添加多个组件,那么需要先将多个组件添加到JPanel面板,再将JPanel面板添加到滚动面板


示例:

import javax.swing.*;import java.awt.*;import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class Main extends JFrame { public Main(){ Container c = getContentPane();//获取主容器 //创建文本区域组件,文本域默认大小为 20 行、50 列 JTextArea ta = new JTextArea(20,50); //创建 JScrollPane 滚动面板,并将文本域放到滚动面板中 JScrollPane sp = new JScrollPane(ta); c.add(sp);//将该面板添加到主容器中 setTitle("带滚动条的文字编译器"); setSize(400,200); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); } public static void main(String[] args) { Main p = new Main(); p.setVisible(true); }}


运行结果:

在这里插入图片描述


文字标签组件与图标

标签被用于显示文本,图标等内容。用户能够通过标签上的文本图标等内容获取相应的提示信息。


1、JLabrl标签

JLabrl标签的父类是JComponent类,标签不能被添加监听器,但是标签显示的文本,图标等内容可以指定对齐方式,通过JLabrl类的构造方法可以创建多种标签,

常用的构造方法如下:

在这里插入图片描述


示例:

import javax.swing.*;import java.awt.*;import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class Main extends JFrame { public Main(){ Container container=getContentPane();//获取主容器 JLabel jl=new JLabel("这是一个 JFrame 窗体");//创建标签 container.add(jl); setSize(200,100);//设置窗体大小 setVisible(true);//设置窗体可见 setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//关闭窗体则停止程序 } public static void main(String[] args) { Main p = new Main(); }}

运行结果:

在这里插入图片描述


2、图标的使用

在swing程序设计中,图标经常被添加到标签,按钮等组件

它有多个常用方法如下:

在这里插入图片描述


示例:

import javax.swing.*;import java.awt.*;import java.net.URL;import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class Main extends JFrame { public Main(){ Container container=getContentPane(); JLabel jl=new JLabel("这是一个JFrame窗体");//创建标签 URL url=Main.class.getResource("img\cell.png");//获取图片所在的URL Icon icon =new ImageIcon(url);//获取图片的icon对象 jl.setIcon(icon);//为标签设置图片 jl.setHorizontalAlignment(SwingConstants.CENTER);//设置文字放置在标签中间 jl.setOpaque(true);//设置标签为不透明状态 container.add(jl);//将标签添加到容器中 setSize(300,200);//设置窗体大小 setVisible(true);//使窗体可见 setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//关闭窗体则停止程序 } public static void main(String[] args) { Main p = new Main(); }}


按钮组件

在Swing程序设计中,按钮是较为常见的组件,被用于触发特定的动作提供了多种按钮,组件按钮,单选按钮,复选框等


1、JButto按钮

Swing按钮由JButto对象表示。

JButto常用的构造方法如下:

在这里插入图片描述


创建JButto对象后如果要JButto对象进行设置,那么可以使用JButto提供的方法,提供的方法如下表所示:

setText(String text):设置按钮上显示的文本。setMnemonic(char mnemonic):设置按钮的快捷键。setActionListener(ActionListener listener):设置按钮的监听器,当按钮被点击时触发。setBackground(Color color):设置按钮的背景色。setForeground(Color color):设置按钮上显示的文本的颜色。setFont(Font font):设置按钮上显示的文本的字体。setBorder(Border border):设置按钮的边框。setRolloverIcon(Icon icon):设置按钮在鼠标指针滑过时显示的图标。setDisabledIcon(Icon icon):设置按钮被禁用时显示的图标。setDisabledSelectedIcon(Icon icon):设置按钮被禁用且被选中时显示的图标。


import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.net.URL;public class Main extends JFrame { public Main(){ Icon icon=new ImageIcon("");//获取图片文件 setLayout(new GridLayout(3,2,5,5));//设置网格布局管理器 Container c=getContentPane();//获取主容器 JButton btn[]=new JButton[6];//创建按钮数组 for(int i=0;i<btn.length;i++) { btn[i]=new JButton();//实例化数组中的对象 c.add(btn[i]);//将按钮添加到容器中 } btn[0].setText("不可用"); btn[0].setEnabled(false);//设置按钮不可用 btn[1].setText("有背景色"); btn[1].setBackground(Color.YELLOW); btn[2].setText("无边框"); btn[2].setBorderPainted(false);//设置按钮边框不显示 btn[3].setText("有边框"); btn[3].setBorder(BorderFactory.createLineBorder(Color.RED));//添加红色线性边框 btn[4].setIcon(icon);//为按钮设置图标 btn[4].setToolTipText("图片按钮");//设置鼠标悬停时提示的文字 btn[5].setText("可点击"); btn[5].addActionListener(new ActionListener() { //为按钮添加监听事件 public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(Main.this,"点击按钮");//弹出确认对话框 } }); setTitle("创建不同样式的按钮"); setBounds(100,100,400,200);//设置窗体大小 setVisible(true);//设置窗体可见 setDefaultCloseOperation(EXIT_ON_CLOSE);//关闭窗体则停止程序 } public static void main(String[] args) { new Main(); }}


运行结果:

在这里插入图片描述


2、JRadioButton单选按钮

Swing单选按钮由JRadioButton对象表示,在swing程序设计中,需要把多个单选按钮添加到按钮组,当用户选中某个单选按钮时,按钮组中的其他单选按钮将不能被同时选中

在这里插入图片描述


示例:

import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.net.URL;public class Main extends JFrame { public Main(){ setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setTitle("单选按钮的使用"); setBounds(100,100,240,120); getContentPane().setLayout(null);//设置绝对布局 JLabel lbINewLabel = new JLabel("请选择性别:"); //设置绝对布局 lbINewLabel.setBounds(5, 5,120,15); getContentPane().add(lbINewLabel); JRadioButton rbtnNormal =new JRadioButton("男"); rbtnNormal.setSelected(true); rbtnNormal.setBounds(40, 30, 75,22); getContentPane().add(rbtnNormal); JRadioButton rbtnPwd = new JRadioButton("女"); rbtnPwd.setBounds(120,30,75,22); getContentPane().add(rbtnPwd); ButtonGroup group = new ButtonGroup(); //创建按钮组,把交互面板中的单选按钮添加到按钮组中 group.add(rbtnNormal); group.add(rbtnPwd); } public static void main(String[] args) { Main p = new Main(); p.setVisible(true); }}

运行结果:

在这里插入图片描述


2、JCheckBox复选框

复选框组件由JCheckBox对象表示,以单选按钮不同的是,窗体中的复选框可以被选中多个,这是因为每一个复选框都提供了被选中和不被选中两种状态。

常用构造方法如下:

在这里插入图片描述


示例:

import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.net.URL;public class Main extends JFrame { public Main(){ setBounds(100,100,170,110);//窗口坐标和大小 setDefaultCloseOperation(EXIT_ON_CLOSE); Container c=getContentPane();//获取主容器 c.setLayout(new FlowLayout());//容器使用流布局 JCheckBox c1=new JCheckBox("1");//创建复选框 JCheckBox c2=new JCheckBox("2"); JCheckBox c3=new JCheckBox("3"); c.add(c1);//容器添加复选框 c.add(c2); c.add(c3); JButton btn=new JButton("打印");//创建打印按钮 btn.addActionListener(new ActionListener(){ //打印按钮动作事件 public void actionPerformed(ActionEvent e) { //在控制台分别输出三个复选框的选中状态 System.out.println(c1.getText()+"按钮选中状态:"+c1.isSelected()); System.out.println(c2.getText()+"按钮选中状态:"+c2.isSelected()); System.out.println(c3.getText()+"按钮选中状态:"+c3.isSelected()); } }); c.add(btn);//容器添加打印按钮 setVisible(true); } public static void main(String[] args) { new Main(); }}

运行结果:

在这里插入图片描述


列表组件

Swing中提供两种列表组件,分别为下拉列表框(JComboBox)和列表框(JList),下拉列表框与列表框都是带有一系列列表选项的组件,用户可以从中选择需要的列表项,列表框较下拉列表框更直观,他们将所有的列表项罗列在列表框,但是下拉列表这个表框更为便捷美观,它将所有的列表项隐藏起来,当用户用其中的列表项时才会显示出来


1、JComboBox下拉列表框

初次使用下拉列表框时,会感觉swing中的下拉列表框以WINDOWS操作系统中的下拉列表框有一些相似,实质上两者并不完全相同,因为swing中的下拉列表框不仅可以供用户从中选择,列表项也提供编辑列表项的功能。

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

在这里插入图片描述

常用方法:

在这里插入图片描述


示例:

import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.net.URL;public class Main extends JFrame { public Main(){ setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setTitle("下拉列表框的使用"); setBounds(100,100,317,147); getContentPane().setLayout(null);//设置绝对布局 JLabel lblNewLabel = new JLabel("请选择证件:"); lblNewLabel.setBounds(28,14,80,15); getContentPane().add(lblNewLabel); JComboBox<String>comboBox = new JComboBox<String>();//创建一个下拉列表框 comboBox.setBounds(110,11,80,21);//设置坐标 comboBox.addItem("身份证");//为下拉列表中添加项 comboBox.addItem("军人证"); comboBox.addItem("学生证"); comboBox.addItem("工作证"); comboBox.setEditable(true);//将下拉列表添加到容器中 getContentPane().add(comboBox); JButton btnNewButton= new JButton("确定"); btnNewButton.setBounds(200,10,67,23); getContentPane().add(btnNewButton); btnNewButton.addActionListener(new ActionListener() { //为按钮添加监听事件 @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub lblNewLabel.setText("你的选择的是:"+ comboBox.getSelectedItem()); } }); setVisible(true); } public static void main(String[] args) { new Main(); }}


运行结果:

在这里插入图片描述


2、JList列表框

列表框组件被添加到窗体中后,就会被指定长和宽。如果列表框的大小不足以容纳列表项的个数,那么需要设置列表框具有滚动效果,即把列表框添加到滚动面板

列表框组件由j list对象表示常用构造方法如下:

在这里插入图片描述

常用方法:

在这里插入图片描述


示例:

import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.net.URL;public class Main extends JFrame { public Main(){ Container cp=getContentPane();//获取窗体主容器 cp.setLayout(null);//容器使用绝对布局 //创建字符串数组保存列表中的数据 String[]contents= { "列表1","列表2","列表3","列表4","列表5","列表6"}; JList<String> jl=new JList<>(contents);//创建列表框并将字符串数组作为构造参数 JScrollPane js=new JScrollPane(jl);//将列表框放入滚动面板 js.setBounds(10, 10, 100, 109);//设定滚动面板的坐标和大小 cp.add(js); JTextArea area=new JTextArea();//创建文本域 JScrollPane scrollPane=new JScrollPane(area);//将文本域放入滚动面板 scrollPane.setBounds(118,10,73,80);//设定滚动面板的坐标和大小 cp.add(scrollPane); JButton bthNewButton=new JButton("确认");//创建确定按钮 bthNewButton.setBounds(120,96,71,23);//设定按钮的坐标和大小 cp.add(bthNewButton); bthNewButton.addActionListener(new ActionListener() { //添加按钮事件 public void actionPerformed(ActionEvent e) { //获取列表中选中的元素返回JAVA.util.list类型 java.util.List<String> values=jl.getSelectedValuesList(); area.setText("");//清空文本域 for(String value : values) { area.append(value+"\n");//在文本域循环追加列表框中选中的值 } } }); setTitle("在这个窗口中使用了列表框"); setSize(300,200); setVisible(true); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public static void main(String[] args) { new Main(); }}


运行结果:

在这里插入图片描述


文本组件

文本组件在开发swing程序过程中经常被用到,尤其是文本框组件和密码框组件。


1、JTextField文本框

文本框组件由JTextField对象表示。

JTextField常用构造方法如下:

在这里插入图片描述


示例:

import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.net.URL;public class Main extends JFrame { public Main() { Container c = getContentPane();//获取窗体主容器 c.setLayout(new FlowLayout()); JTextField jt = new JTextField("请点击清除按钮");//设定文本框初始值 jt.setColumns(20);//设置文本框长度 jt.setFont(new Font("宋体", Font.PLAIN, 20));//设置字体 JButton jb = new JButton("清除"); jt.addActionListener(new ActionListener() { //为文本框添加回车事件 public void actionPerformed(ActionEvent arf0) { jt.setText("触发事件");//设置文本框中的值 } }); jt.addActionListener(new ActionListener() { // 为按钮添加事件 public void actionPerformed(ActionEvent arf0) { System.out.println(jt.getText());//输出当前文本框的值 jt.setText("");//将文本框置空 jt.requestFocus();// 焦点回到文本框 } }); c.add(jt);//窗体容器添加文本框 c.add(jb);//窗体添加按钮 setBounds(100, 100, 250, 110); setVisible(true); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public static void main(String[] args) { new Main(); }}


运行结果:

在这里插入图片描述


2、JPasswordField密码框

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

常用构造方法如下:

在这里插入图片描述


3、 JTextArea文本域

文本域组件由JTextArea对象表示,其作用是接受用户的多行文本输入。

常用构造方法如下:

在这里插入图片描述


JTrxtArea类提供了一个setLineWrap(boolean wrap)方法,这个方法被用于设置文本域中的文本内容,是否可以自动换行。如果参数为true,那么会自动换行,否则不会自动换行

此外,还提供了一个append(String str)方法,这个方法被用于向文本域中添加文本内容。

示例:

import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.net.URL;public class Main extends JFrame { public Main() { setSize(200,100); setTitle("定义自动换行的文本域"); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); Container cp = getContentPane();//获取窗体主容器 //创建一个文本内容为“文本域”、行高和列宽均为 6 的文本域 JTextArea jt = new JTextArea("文本域",6,6); jt.setLineWrap(true);//可以自动换行 cp.add(jt); setVisible(true); } public static void main(String[] args) { new Main(); }}

运行结果:

在这里插入图片描述


表格组件

Swing表格由JTable表示其作用是把数据以表格的形式显示给用户。


1、创建表格

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

JTanle(Object[][]rowDate,Object[]columnNames)rowDate存储表格数据的二维数组columnNames,存储表格列明的一维数组

**在使用表格时,要先把表格添加到滚动面板,再把滚动面板添加到窗体的相应位置 **

示例:

import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.net.URL;public class Main extends JFrame { public Main() { setTitle("创建可以滚动的表格"); setBounds(100,100,240,150); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); String[] columnNames = { "A","B"};//定义表格列名数 //定义表格数据数组 String[][] tableValues ={ { "A1","B1"},{ "A2","B2"},{ "A3","B3"}, { "A4","B4"},{ "A5","B5"}}; //创建指定列名和数据的表格 JTable table = new JTable(tableValues, columnNames); //创建显示表格的滚动面板 JScrollPane scrollPane = new JScrollPane(table); //将滚动面板添加到边界布局的中间 getContentPane().add(scrollPane, BorderLayout.CENTER); setVisible(true); } public static void main(String[] args) { new Main(); }}


运行结果:

在这里插入图片描述


2、DefaultTableModel表格数据模型

Swing使用TableModel接口定义了一个表格模型,AbstractDefaultTableModel抽象类实现了TableModel接口的大部分方法。

只有以下三个抽象方法没有实现:

在这里插入图片描述


为了实现使用表格模型,创建表格的功能swing提供了表格模型类,DefaultTableModel,DefaultTableModel常用构造方法如下:

在这里插入图片描述


示例:

import javax.swing.*;import javax.swing.table.DefaultTableModel;import javax.swing.table.TableRowSorter;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.net.URL;public class Main extends JFrame { public Main() { setTitle ("表演模型与表格"); setBounds(100,100,240,150);//窗体宽高 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JScrollPane scrollPane=new JScrollPane(); getContentPane().add(scrollPane,BorderLayout.CENTER); String[] columnNames= { "A","B"};//定义表格列名数组 //定义表格数据数组 String[][] tableValues= { { "A1","B1"},{ "A2","B2"},{ "A3","B3"}}; //创建指定表格列名和表格数据的表格模型 DefaultTableModel tableModel=new DefaultTableModel(tableValues,columnNames); JTable table=new JTable(tableModel);//创建指定表格模型的表格 table.setRowSorter(new TableRowSorter<>(tableModel)); scrollPane.setViewportView(table); setVisible(true); } public static void main(String[] args) { new Main(); }}


运行结果:

在这里插入图片描述


3、维护表格模型

表格中的数据内容需要用于维护。

使用getValueAt()方法获得表格中某一个单元格的值,使用addRow()方法向表格中添加新的行使用setValueAt方法修改表格中某一个单元格的值使用removeRow方法从表格中删除指定行等

当删除表格模型中的指定行时,每删除一行,其后所有行的索引值将相应的减一,所以当连续删除多行时,需要注意对删除行索引的处理。


示例:

import javax.swing.*;import javax.swing.table.DefaultTableModel;import javax.swing.table.TableRowSorter;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.net.URL;public class Main extends JFrame { private DefaultTableModel tableModel;//定义表格模型对象 private JTable table;//定义表格对象 private JTextField aTextFied; private JTextField bTextFied; public Main() { 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_INTERVAL_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); aTextFied.setText(oa.toString());//将值赋值给文本框 bTextFied.setText(ob.toString());//将值赋值给文本框 } }); scrollPane.setViewportView(table); JPanel panel = new JPanel(); getContentPane().add(panel, BorderLayout.SOUTH); panel.add(new JLabel("A:")); aTextFied = new JTextField("A4", 10); panel.add(aTextFied); panel.add(new JLabel("B:")); bTextFied = new JTextField("B4", 10); panel.add(bTextFied); JButton addButton = new JButton("添加"); addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String[] rowValues = { aTextFied.getText(), bTextFied.getText()};//创建表格行数组 tableModel.addRow(rowValues);//向表格模型中添加一行 int rowCount = table.getRowCount() + 1; aTextFied.setText("A" + rowCount); bTextFied.setText("B" + rowCount); } }); panel.add(addButton); JButton updButton = new JButton("修改"); updButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int selectdRow = table.getSelectedRow();//获得被选中行的索引 if (selectdRow != 1) { //判断是否存在被选中行 //修改表格模型中的指定值 tableModel.setValueAt(aTextFied.getText(), selectdRow, 0); //修改表格模型中的指定 tableModel.setValueAt(bTextFied.getText(), selectdRow, 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); } public static void main(String[] args) { Main frame = new Main(); frame.setVisible(true); }}


运行结果:

在这里插入图片描述


事件监听器

Java中的事件监听器是一种用于监听特定事件并对其做出响应的机制。它由事件类和监听接口组成,当特定事件发生时,事件源会调用相应的监听器接口的方法,并在调用时将事件对象传递进去。

事件类是继承自java.util.EventObject的类 用于表示事件本身的属性和状态。例如,ActionEvent类表示用户界面组件的动作事件。

监听接口是继承自java.util.EventListener的类,它定义了事件发生时应执行的操作。例如,ActionListener接口定义了actionPerformed方法,当按钮被点击时,该方法会被调用。

使用事件监听器可以方便地实现对特定事件的管理和响应。

在Java中,事件监听器是通过将事件对象传递给监听器接口的方法来实现的。通过在方法中访问事件对象,可以获取有关事件的信息,例如事件源和事件类型,从而对事件进行适当的处理。


1、ActionEvent动作事件

在Java中,ActionEvent是用于监听用户界面(UI)组件(如按钮点击,菜单项选择等)的动作事件的一种事件。ActionEvent类是java.awt.event包的一部分,它包含有关发生的事件的信息,例如事件源,发生事件的时间以及事件的类型。

当用户执行某种动作(如点击按钮)时,相应的组件会生成一个ActionEvent对象,然后调用其监听器的actionPerformed方法。这个方法是在ActionListener接口中定义的。


示例:

import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;public class Main extends JFrame { private JButton jb=new JButton("我是按钮,点击我"); public Main() { setLayout(null); setSize(200,100); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); Container cp=getContentPane(); cp.add(jb); jb.setBounds(10,10,150,30); jb.addActionListener(new jbAction()); setVisible(true); } class jbAction implements ActionListener{ public void actionPerformed(ActionEvent arg0) { jb.setText("我被点击了"); } } public static void main(String[] args) { new Main(); }}


运行结果:

在这里插入图片描述


2、KeyEvent键盘事件监听器

在Java中,KeyEvent是用于捕获键盘事件的一个类。

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

KeyListener接口定义了三个抽象方法,它们分别在发生击键事件、按键被按下和释放时被触发。具体地,当按下一个键时会调用KeyPressed处理器,当松开一个键时会调用KeyReleased处理器,当输入一个统一编码时会调用KeyTyped处理器。

public void keyTyped(KeyEvent e):发生击键事件时被触发public void keyPressed(KeyEvent e):按键被按下时被触发public void keyReleased(KeyEvent e):按键被释放时被触发


KeyListener接口的这些方法可以在用户执行键盘操作时被调用,从而实现对键盘事件的处理。例如,当用户按下键盘上的一个键时,相应的KeyPressed方法就会被调用,这个方法中可以编写处理按键按下的代码。

在Java的Swing库中,很多组件(如JTextField等)都提供了添加KeyListener的方法,使得这些组件在用户执行键盘操作时能够触发事件。例如,JTextField提供了addKeyListener方法来添加一个KeyListener。


KeyListener常用方法:

在这里插入图片描述


示例:

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 Main 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对象,用来表示释放键的颜色 Color red=Color.RED; 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 { Main frame = new Main(); // 创建KeyBoard对象 frame.setVisible(true); // 使frame可视 frame.addButtons();// 初始化存储所有按键的集合 } catch (Exception e) { e.printStackTrace(); } } }); } /** * 创建JFrame窗体 */ public Main() { // 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(red);// 将指定按键颜色设置为白色 } } } }); panel.add(textField, BorderLayout.CENTER); textField.setColumns(10); }}


运行结果:

在这里插入图片描述


3、MouseEvent鼠标事件

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

MouseListener接口有5个抽象方法:

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):光标移出组件时被触发


常用方法:

在这里插入图片描述


静态常量:

分别代表:左键、滚轮和右键。

在这里插入图片描述


示例:

import javax.swing.*;import java.awt.*;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;public class Main extends JFrame { public static void main(String args[]) { Main frame = new Main(); 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 Main() { 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.println("鼠标按键被按下"); mouseOper(e); } public void mouseReleased (MouseEvent e) { System.out.println("鼠标按键被释放"); mouseOper(e); } public void mouseClicked (MouseEvent e) { System.out.println("单击了鼠标按键"); mouseOper(e); int clickCount=e.getClickCount(); System.out.println("单击次数为"+clickCount+"下"); } public void mouseExited(MouseEvent e) { System.out.println("光标移出组件"); } }); getContentPane().add(label, BorderLayout.CENTER); }}


运行结果:

在这里插入图片描述


END



声明

本文内容仅代表作者观点,或转载于其他网站,本站不以此文作为商业用途
如有涉及侵权,请联系本站进行删除
转载本站原创文章,请注明来源及作者。