Java第十八章总结

Swing 概述

Swing 主要用来开发 GUI 程序,GUI 是应用程序提供给用户操作的图形界面,包括窗口、菜单、按钮等图形界面元素。Java语言为 Swing 程序的开发提供了丰富的类库,这些类分别被存储在 java.awt 和 javax.swing 包中。

   Swing 组件是完全由Java语言编写的组件。因为Java语言不依赖于本地平台(即操作系统),所以 Swing 组件可以被应用于任何平台。

Swing 常用窗体

JFrame 窗体

JFrame 类的常用构造方法包括以下两种形式:

public JFrame(): 创建一个初始不可见、没有标题的窗体。
public JFrame(String title): 创建一个不可见、具体标题的窗体。

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

JButton okButn=new JButton("确定 ")

container.add(okButn);

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

container.remove(okButn);

  在创建窗体后,要对窗体进行设置,如设置窗体的位置、大小、是否可见等。具体如下:

setBounds(int x , int y , int width , int length):  设置窗体左上角在屏幕中坐标为(x , y),窗体的宽度为 width,窗体的高度为height。
setLocation(int x , int y):  设置窗体左上角在屏幕中的坐标为(x , y)。

setSize(int width , int height): 设置窗体的宽度为 width,高度为 height。

setVisible(boolean b): 设置窗体是否可见。b 为 true 时,表示可加;b 为 false 时,表示不可见。

setDefaultCloseOperation(int operation):  设置窗体的关闭方式,默认值DISPOSE_NO_CLOSE。

ackage eighteenth;
 
import java.awt.Container;
 
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
 
public class JFrameTest {
    public static void main(String[] args) {//主方法
    JFrame jf=new JFrame();//创建窗体对象
    jf.setTitle("创建一个JFrame 窗体");//设置窗体标题
    Container container=jf.getContentPane();//获取主容器
    JLabel jl=new JLabel("这是一个 JFrame 窗体");//一个文本标签
    jl.setHorizontalAlignment(SwingConstants.CENTER);//使用标签上的文字居中
    container.add(jl);//将标签添加到主容器中
    jf.setSize(300,150);//设置窗体宽高
    jf.setLocation(320,240);//设置窗体在屏幕中出现的位置
    jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//关闭窗体则停止程序
    jf.setVisible(true);//让窗体展示出来
    }
}

运行结果如下:

JDialog 对话框 

JDialog 对话框继承了 java.awt.Dialog 类,其功能是从一个窗体中弹出另一个窗体,如使用 IE 浏览器时弹出的确定对话框。JDialog 对话框与JFrame 窗体类似,被使用时也需 getContentPane() 方法把 JDialog 对话框转换为容器,再对 JDialog 对话框进行设置。

package eighteenth;
 
import java.awt.Container;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
 
class MyJDialog extends JDialog{//自定义对话框类,继承 JDialog
    public MyJDialog (MyFrame frame) {
    //调用父类构造方法,第一个参数是父窗体,第二个参数是窗体标题,第三个参数表示堵塞父窗体
        super(frame,"第一个 JDialog 窗体",true);
        Container container=getContentPane();//获取主容器
        container.add(new JLabel("这是一个对话框"));//在容器中添加标题
        setBounds(120,120,100,100);//设置对话框窗体在桌面显示的坐标和大小
    }    
 
public static void main(String[] args) {
    new MyFrame ();
}
}
 
class MyFrame extends JFrame {//自定义窗体,继承 JFrame
    public MyFrame() {//窗体的构造方法
        Container container=getContentPane();//获得窗体主容器
        container.setLayout(null);//容器使用绝对布局
        JButton bl=new JButton("弹出对话框");//创建一个按钮
        bl.setBounds(10,10,100,21);//定义按钮在容器中的坐标和大小
        bl.addActionListener(new ActionListener() {//为按钮添加单击事件
            public void actionPerformed(ActionEvent e) {//单击事件触发的方法
                MyJDialog dialog =new MyJDialog(MyFrame.this);//创建 MyJDialog对话框 
                dialog .setVisible(true);//是对话框可见
            }
        });
        container.add(bl);//将按钮添加到容器中
        setSize(200,200);//窗体的宽高
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//关闭窗体则停止程序
        setVisible(true);//使窗体可见
    }
}

运行结果如下:

JOptionPane 小型对话框

Java API 中的,Javax.swing,JOptionPane 类时一个非常简便的小型对话框类,该类用于创建对话框的方法都是静态方法,无须创建对象即可弹出。在日常开发中经常使用该类弹出提示、确认用户需要、调试程序等。

1、自定义对话框

package eighteenth;
 
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
 
public class Demo {
    public static void main(String[] args) {
        Object O[]= {new JButton("是的"),new JButton("再想想")};//按钮对象的 Object 数组
        Icon icon=new ImageIcon("src/注意.png");//获取图标对象
        JOptionPane.showOptionDialog(null, "你做好准备了吗", "注意了!",
                JOptionPane.DEFAULT_OPTION,JOptionPane.DEFAULT_OPTION,icon,O, null);
    }
}
运行结果如下:

2、确认框

package eighteenth;
 
import javax.swing.JOptionPane;
 
public class Demo {
    public static void main(String[] args) {
        int answer=JOptionPane.showConfirmDialog(null,"确定离开吗?","标题",
                JOptionPane.YES_NO_CANCEL_OPTION);
    }
}

运行结果如下:

3、输入框

package eighteenth;
 
import javax.swing.JOptionPane;
 
public class Demo {
    public static void main(String[] args) {
        String name=JOptionPane.showInputDialog(null,"请输入您的姓名");
    }
}

运行结果如下:

4、通知框

package eighteenth;
 
import javax.swing.JOptionPane;
 
public class Demo {
    public static void main(String[] args) {
        JOptionPane.showMessageDialog(null,"您与服务器断开了连接","发生错误",JOptionPane.ERROR_MESSAGE);
    }
}

运行结果如下:

常用布局管理器 

null 绝对布局 

绝对布局也叫 null 布局,其特点是硬性指定组件在容器中的位置大小,组件的位置通过绝对坐标的方式来指定。使用绝对布局首先使用 Container.seLayout(null)方法取消容器的布局管理器,然后再使用 Component.setBounds(int x,int y,int width,int height)方法设置每个组件在容器中的位置和大小。

package eighteenth;
 
import java.awt.Container;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
 
public class AbsolutePosition extends JFrame{
    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)管理器是 Swing 中最基本的布局管理器。使用流布局管理器摆放组件时,组件被从左到右摆放。当组件占据了当前的所有空间时,溢出的组件会被移动到当前的下一行。默认情况下,行组件的排列方式会被指定为居中对齐,但是通过设置可以更改每一行组件的排序方式。  

package eighteenth;
 
import java.awt.Container;
import java.awt.FlowLayout;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
 
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++) {
            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 边界布局管理器

使用 Swing 创建窗体后,容器默认的布局管理器是边界布局(BorderLayout )管理器 ,边界布局把容量划分为东、南、西、北、中5个区域,但组件被添加到设置为边界布局管理器的容器时,需要使用 BorderLayout 类中成员变量指定被添加的组件在边界布局管理器中的区域。

package eighteenth;
 
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
 
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 网格布局管理器 

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

常用面板 

JPanel 面板 

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

package eighteenth;
 
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
 
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
 
public class JPanelTest extends JFrame{
    public  JPanelTest(){
        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) {
        JPanelTest test=new JPanelTest();
        test.setVisible(true);
    }
}

运行结果如下:


JScrollPane 滚动面板

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

package eighteenth;
 
import java.awt.Container;
 
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
 
public class JScrollPaneTest extends JFrame {
    public JScrollPaneTest(){
        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) {
        JScrollPaneTest test=new JScrollPaneTest();
        test.setVisible(true);
 
    }
 
}

运行结果如下:

 文字标签组件与图标 

JLabel 标签 

标签(JLabel)的父类是 JComponent 类。虽然标签不能被添加监听器,但是标签显示的文本、图表等内容可以把被指定对齐方式。通过 JLabel 类的构造方法,可以创建多种标签,如显示只有文本标签、只有图标的标签以及同时包含文本和图标的标签等。

package eighteenth;
 
import java.awt.Container;
 
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
 
public class JLabelTest extends JFrame{
    public  JLabelTest (){
        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) {
        new JLabelTest();
 
    }
}

运行结果如下:

图标的使用

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

package eighteenth;
 
import java.awt.Container;
 
import java.net.URL;
 
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
 
public class MyImageIcon extends JFrame {
    public MyImageIcon() {
        Container container=getContentPane();
        JLabel jl=new JLabel("这是一个 JFrame 窗体");//创建标签
        URL url=MyImageIcon.class.getResource("75bdcc56c512088f7252bcaabd968bd.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) {
        new MyImageIcon();
    }
 
}

运行结果如下:

按钮组件 

JButton 按钮

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

 publicJButton():创建一个不带文本或图标的按钮。
publicJButton(String text):创建一个带文本的按钮。
publicJButton(Icon icon): 创建一个带图标的按钮。
public JButton(String text,Icon icon):创建一个带文本和图标的按钮。

package eighteenth;
 
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.WindowConstants;
 
public class JButtonTest extends JFrame{
    public  JButtonTest(){
        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(JButtonTest.this,"点击按钮");//弹出确认对话框
            }
        });
        setTitle("创建不同样式的按钮");
        setBounds(100,100,400,200);//设置窗体大小
        setVisible(true);//设置窗体可见
        setDefaultCloseOperation(EXIT_ON_CLOSE);//关闭窗体则停止程序
    }
 
    public static void main(String[] args) {
        new JButtonTest();
    }
}

JRadioButton 单选按钮

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

import javax.swing.*;
public class RadioButtonTest extends JFrame{
        public RadioButtonTest() {
            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) {
        RadioButtonTest frame = new RadioButtonTest();//创建窗体对象
            frame.setVisible(true);//使窗体可见
 
    }
 
}

 运行结果如下:

JCheckBox 复选框

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

package eighteenth;
 
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
 
public class CheckBoxTest extends JFrame {
    public CheckBoxTest() {
        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) {
                //在控制台分别输出3个复选框的选中状态
                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 CheckBoxTest();
 
    }
 
}

运行结果如下:

列表组件 

JComboBox 下拉列表框

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

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
 
public class JComboBoxTest extends JFrame {
    public JComboBoxTest() {
        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);     //将下拉列表添加到容器中
        JLabel lblResult = new JLabel("");
        lblResult.setBounds(0,57,146,15);
        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
                lblResult.setText("你的选择的是:"+ comboBox.getSelectedItem());
            }
            
        });
        
    }
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JComboBoxTest frame = new JComboBoxTest();    //创建窗体对象
        frame.setVisible(true);//使窗体可见
    }
 
}

 运行结果如下:

JList 列表框

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

package eighteenth;
 
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.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
 
public class JListTest extends JFrame{
    public  JListTest(){
        Container cp=getContentPane();//获取窗体主容器
        cp.setLayout(null);//容器使用绝对布局
        //创建字符串数组,保存列表中的数据
        String[] contents= {"列表1","列表2","列表3","列表4","列表5","列表6","列表7"};
        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 btnNewButton=new JButton("确认");//创建”确认“按钮
        btnNewButton.setBounds(120,96,71,23);//设定按钮的坐标和大小
        cp.add(btnNewButton);
        btnNewButton.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(217,167);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
 
    public static void main(String[] args) {
        new JListTest();
 
    }
 
}

运行结果如下:

文本组件 

JTextField 文本

package eighteenth;
 
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.plaf.synth.SynthOptionPaneUI;
 
public class JTextFieldTest extends JFrame {
    public  JTextFieldTest(){
        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 arg0) {
                jt.setText("触发事件");//为文本框中的值
            }
        });
        jb.addActionListener(new ActionListener() {//为按钮添加事件
            public void actionPerformed(ActionEvent arg0) {
                System.out.println(jt.getText());//输出当前文本框的值
                jt.setText("");//将文本框空置
                jt.requestFocus();//焦点回到文本框
            }
        });
        c.add(jt);//窗体容器添加文本框
        c.add(jb);//窗体添加按钮
        setBounds(100,100,250,110);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
 
    public static void main(String[] args) {
        new JTextFieldTest();
 
    }
 
}

运行结果如下:

JPasswordField 密码框


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

JTextArea 文本域


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

public JTextArea():

public JTextArea(String text):

public JTextArea(int rows,int columns):

public JTextArea(Document doc):

public JTextArea(Document doc ,String Text,int rows,int columns):

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

package eighteenth;
 
import java.awt.Container;
 
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
 
public class Demo extends JFrame {
    public   Demo() {
        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 Demo();
    }
}

 运行结果如下:

表格组件

创建表格

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

JTanle(Object[][]rowDate,Object[]columnNames)

owDate存储表格数据的二维数组
columnNames,存储表格列明的一维数组
在使用表格时,要先把表格添加到滚动面板,再把滚动面板添加到窗体的相应位置 .

package eighteenth;
 
import java.awt.BorderLayout;
 
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
 
 
public class Demo extends JFrame {
    public static void main(String args[]) {
        Demo frame = new Demo();
        frame.setVisible(true);
    }
    public Demo() {
        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);
    }
}

运行结果如下:

DefaultTableModel 表格数据模型 

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

package eighteenth;
import java.awt.BorderLayout;
 
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
 
public class SortingTable extends JFrame{
    private static final long serialversionUID=1L;
    public static void main(String[] args) {
        SortingTable frame=new SortingTable();
        frame.setVisible(true);
        
    }
    public SortingTable() {
        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);
    }
    }

运行结果如下:

维护表格模型

        表格中的数据内容需要用于维护,使用getValueAt()方法获得表格中某一个单元格的值,使用addRow()方法向表格中添加新的行,使用setValueAt方法修改表格中某一个单元格的值,使用removeRow方法从表格中删除指定行等。

package eighteenth;
 
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
 
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[] coulumnNames={"A","B"};//定义表格列名数组
        //定义表格数据数组
        String[][] tableVaues= {{"A1","B1"},{"A2","B2"},{"A3","B3"}};
        tableModel=new DefaultTableModel(tableVaues,coulumnNames);
        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(tableVaues);//像表格模型中添加一行
                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, 0);
                }
            }
        });
        panel.add(updButton);
        JButton delButton=new JButton("删除");
        updButton.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.9 描述了动作事件监听器的接口与事件源等。

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 Demo extends JFrame {
    private JButton jb=new JButton("我是按钮,点击我");
    public Demo() {
        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 Demo();
    }
}

 运行结果如下:

KeyEvent 键盘事件

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

package eighteenth;
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 Demo 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 {
                    Demo frame = new Demo(); // 创建KeyBoard对象
                    frame.setVisible(true); // 使frame可视
                    frame.addButtons();// 初始化存储所有按键的集合
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
 
    /**
     * 创建JFrame窗体
     */
    public Demo() { // 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 接口的监听器类来处理相应的鼠标事件。

import java.awt.BorderLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
 
import javax.swing.JFrame;
import javax.swing.JLabel;
 
public class Demo extends JFrame { // 继承窗体类JFrame
 
    public static void main(String args[]) {
        Demo frame = new Demo();
        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 Demo() {
        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);
    }
}

运行结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值