再见!【JAVA GUI】

1.GUI概述

图形用户界面(Graphical User Interface,简称 GUI,又 称图形用户接口)是指采用图形方式显示的计算机操作用户界面。

java作为一种面向对象的程序设计语言,它将图形界面设计相关的元素与成分都抽象为类和接口。现主要有java.awt包和javax.swing包

AWT(Abstract Window Toolkit)—抽象窗口工具

Java中用来生成图形用户界面的类库是 java.awt包,它是Java基本包中最大的一个, 定义了所有GUI组件类,以及其它用于构造图形界面的类。

AWT类库中的各种操作被定义成在一个并不存在的“抽象窗口”中进行,以实现跨平台特性,但其具体实现效果会有所不同(与本地对等组件相关联)。

Swing——轻量级组件

swing是为了解决awt存在的问题而新开发的包,它以awt为基础的。

Swing包含250多个类(有些是组件, 有些是支持类即继承自awt子类的类,组件的名字都以 J 开 头);

Swing GUI组件=java.awt包的各种GUI组件+新功能;

用轻量组件(没有本地对等组件)代替了AWT的重量组件(与本地对等组件相关联)。

Swing采用的MVC设计范式:

 模型(Model)——用于存储定义该组件的数据(如:大小,颜色,布局....);

视图(View)——用模型中的数据生成该组件的可视化表示(即显示出该组件);

控制器(Controller)——响应用户对该组件的交互操作。

AWT和Swing之间的区别

1.AWT 是基于本地方法的C/C++程序,其运行速度比较快;Swing是基于AWT的Java程序,其运行速度比较慢。

2.AWT的控件在不同的平台可能表现不同,而Swing在所有平台表现一致。

3.AWT用的是重量组件(与本地对等组件相关联);Swing使用的是轻量组件(没有本地对等组件)。

4.AWT是抽象窗口组件工具包,是 java 最早的用于编写图形设计应用程序的开发包;swing是为了解决awt存在的问题而新开发的包,它以awt为基础的。

图形用户界面元素

组件

容器

用户自定义图形界面成分:(1) 绘制图形(2) 显示文字(3) 控制颜色(4) 显示图象(5) 实现动画效果

2.AWT与Swing组件简介

AWT和Swing容器

容器组件的主要作用是包容其他组件,并按照一定的方式组织排列他们。同一个容器中的所有组件 通常总是同时被显示或同时被隐藏。

所有容器组件都是Container类的子类。在Container类中定义了容器所需 要用到的属性及方法。

常用的方法有:setLayout( LayoutManager mgr)   add (Component omp)

JAVA中的常用容器组件:面板 (JPanel)框架 (JFrame)

(1)面板(Panel、JPanel):

Panel属于无边框容器,无边框容器包括Panel和 Applet,其中Panel是Container的子类,Applet 是Panel的子类,它提供空间将其它的组件附在其上。。

使用Panel (JPanel)的好处就是可将相关的组件整合组织起来,让用户接口更为简洁清楚。

一 个 Frame ( JFrame ) 里 面 可 放 入 好 几 个 Panel(JPanel) 。可以在一个Panel(JPanel)上放入其它Panel(JPanel) 。

创建面板:

Panel() //用默认的布局管理器(FlowLayout)

 Panel(LayoutManager layout)//用指定的布局 管理器(Layout)创建面板

(2)框架(Frame、JFrame)

Frame是独立于浏览器的可独立运行的主窗口,通常 用于开发桌面应用程序。 Frame拥有边界和标题栏设 置,大小、内容可以调整。 Frame是容器,里面需要 加入组件,也可以加入菜单,可以在上面绘图。

Frame的创建

Frame()——创建一个没有窗口标题的窗口框架

Frame(String)——创建一个指定窗口标题的窗口框架

注:框架是容器,就像面板一样,用户可以用add()方法将其他组件加到该框架容器中。该容器的缺省布局是BorderLayout。

Frame的主要方法

(来自网络)

与Frame的相关的方法

(1)Swing中的 setDefaultCloseOperation()方法

功能:设置用户在窗体上发起 "close" 时默认执行的操作。

该方法的参数值:

EXIT_ON_CLOSE(在 JFrame 中定义):使用 System exit 方法 退出应用程序(仅在应用程序中使用) DO_NOTHING_ON_CLOSE(在 WindowConstants 中定义)

HIDE_ON_CLOSE(在 WindowConstants 中定义)

DISPOSE_ON_CLOSE(在 WindowConstants 中定义)

(2)Swing中的 getContentPane()方法

由于在过去的J2SE版本中,组件(Component)不能直接添加到最高级(top level)的Swing容器,这些容器包括:JFrame, JApplet等。 因此需要调用JFrame的getContentPane()方法获得内容面板,然后该内容面板调用add()方法添加组件。但在J2SE5.0中,我们可以直接添加组件到最高级 的Swing容器,也可以直接在容器内设置布局管理和删除组件。

 

标签(Label、JLabel)

专门用于显示输出,它的功能为显示一行“只读文本”;常用于在屏幕上显示一些提示性,说明性的文字。

Label的构造方法及主要成员方法

Label():用来创建一个没有显示内容的标签

Label(String str):创建一个带初始字符串的标签

Label(String str,int alignment):创建一个带初始字符串及指定对齐方式的标签

void setAlignment(int alignment) :设置标签对齐方式。参数int代表的三种对齐方式 0= Label.LEFT 1= Label.CENTER 2= Label .RIGHT

JLabel的构造方法及类方法

(来自网络)

void setAlignment(int alignment) 方法与Label的一致

JLabel的新增功能:可以提供带图标的标签,图标和文字的位置是可以控制的。

 

文本框(TextField、JTextField、JPasswordField)

单行文本框,用来接收用户从键盘上的输入,也可用来显示输出单行文本信息。

TextField的构造方法及成员方法(常用)

(来自网络)

JTextField的构造方法及成员方法(常用)

与TextField的构造方法及成员方法一致只是构造方法名前以J开头

JPasswordField的构造方法及成员方法(常用)

JPasswordField类是继承JTextField类而来,是一个专门用来输入“密码”的单行文本框。即对用户输入的字符采用密文的形式进行显示,如“****”。

(来自网络)

文本域(TextArea、JTextArea)

文本域允许用户编辑具有多行的文本, 可以用于输出信息,也可以用于接收信息。

注:当JTextArea的内容布满时不会产生滚 动条,而是自动加大文本区的大小。

TextArea的构造方法及成员方法(常用)

(来自网络)

JTextArea的构造方法及成员方法(常用)

(来自网络)

按钮(Button、JButton)

某类创建一个按钮。当 按下该按钮时,应用程序能执行某项动作。产生ActionEvent事件 (通过按下 该按钮触发)

Button的构造方法及成员方法(常用)

构造方法 Button() 创建一个没有标题的按钮
  Button(String label) 创建一个有显示标题的按钮
成员方法 void addNotify() 创建一个按钮对象的同位体(可以改变外观但不改变功能)
  getActionComand() 返回激发动作事件按钮的标题
  String getLabel() 返回按钮的标题
  void setLabel(String label) 设置按钮上的标题

JButton的构造方法及成员方法(常用)

(来自网络)

JButton的新增功能:可以提供带图标的按钮。

复选框(Checkbox、JCheckBox)

可以通过鼠标单击复选框的 操作来设置其状态为“选中” 或“非选中”,可以让用户作出多项选择。会产生ItemEvent事件(“复 选框状态发生改变”时触发)

Checkbox的构造方法及成员方法(常用)

(来自网络)

注:复选框组件有状态属性,为true/false,默认情况下为false

JCheckBox的构造方法及成员方法(常用)

(来自网络)

JCheckBox的新增功能:可以提供带图标的复选框。

单选框(CheckboxGroup、 JRadioButton、ButtonGroup)

在AWT中通过复选框组CheckboxGroup来实现单 选框的功能,而在Swing中 则通过JRadioButton来实现。产生ItemEvent事件 (“选择项改变”时触发)

CheckboxGroup及Checkbox实现单选功能

构造方法:public CheckboxGroup()常用成员方法:public Checkbox getSelectedCheckbox() 从此复选框组中获取当前选择

特点:CheckboxGroup是Object的直接子类;CheckboxGroup的对象不产生事件。

结合CheckboxGroup与Checkbox来实现单选功能:

1、CheckboxGroup()方法构造一个CheckboxGroup对象; 2、Checkbox(String, CheckboxGroup ,boolean)方法创建Checkbox对象,同一 组的Checkbox的CheckboxGroup参数值相同 。

//该示例生成了一个新的复选框组,其中有三个复选框:
 CheckboxGroup cbg = new CheckboxGroup();
add(new Checkbox("one", cbg, true)); 
add(new Checkbox("two", cbg, false)); 
add(new Checkbox("three", cbg, false));

JRadioButton的构造方法及成员方法(常用)

(来自网络)

ButtonGroup的构造方法及成员方法(常用)

(来自网络)

下拉列表(Choice、JComboBox)

实现一个下拉式列表, 在显示方式上,使用“弹出 式菜单”动态地显示选项, 并且只会将被选择的选项显 示出来 ;支持单选。会产生ActionEvent事件() 和ItemEvent事件()

  Choice的构造方法及成员方法(常用)

Choice() //创建一个新的选择菜单。

(来自网络)

JComboBox的构造方法及成员方法(主要)

(来自网络)

JComboBox的新增功能 :JComboBox的每项都可以是任意类的对象。

列表组件(List、JList)

提供了一个可滚动的选 项列表;可设置此 list,使 其允许用户进行单项或多项选择。会产生ActionEvent事件(双击某选项时) 和ItemEvent事件(双击某选项时)

List的构造方法及成员方法(常用)

List() 创建列表
List(int) 以指定的行数创建列表
List(int,boolean) 指定行数和是否允许多项选择
String getSelectedItem(int ) 返回选中的字符串
int countItems( ) 返回下拉列表条目数
int getSelectedIndex() 返回当前选项的索引
String getItem(int ) 返回指定索引处的字符串
void removeAll( ) 删除所有选项
void remove(int) 删除指定位置的选项
void addItem(String ,int) 在指定位置加入一个选项
void addItem (String) 向列表末尾加入一个选项
void select(String) 选择指定字符串的选项
   

JList的构造方法及成员方法(常用)

(来自网络)

JList的新增功能:List的项目只能是文本,JList的项目可以由任意类型对象构成。

3.布局管理器

总结了下各种布局管理器,具体用法后面有示例程序,高清图片链接

4.事件处理

概述

(1)事件处理三要素

事件源:图形用户界面的每个可能产生事件的组件。(事件源可以注册监听者对象,并向其发送事件对象)

事件类型:Java事件类被集中在java.awt.event 包中,并所有的事件类都继承了AWTEvent类的一个方法getSource(), 该方法返回所发生事件的对象,即事件源。

事件监听者

(2)AWTEvent类体系结构图

AWTEvent类体系结构

(3)事件监听接口层次结构

(4)事件处理机制

动作事件

后面补~

5.对话框

后面补~

6.菜单

后面补~

7.经典示例程序

1.FlowLayout示例:

import java.awt.*;
public class Frame_FlowLayout {
	public static void main(String[] args) {//流式布局:当一行组件满了后,组件会换行继续添加
		//创建一个名为FlowLayout的窗体
		Frame f =new Frame("FlowLayout");
		//设置窗体中的布局管理器FlowLayout,所有组件左对齐,水平间距为20,垂直间距为30
		f.setLayout(new FlowLayout(FlowLayout.LEFT,20,30));
		//设置窗体大小
		f.setSize(220,300);
		//设置窗体显示的位置
		f.setLocation(300,200);
		//把按钮添加到f窗口中
		f.add(new Button("第1个按钮"));
		f.add(new Button("第2个按钮"));
		f.add(new Button("第3个按钮"));
		f.add(new Button("第4个按钮"));
		f.add(new Button("第5个按钮"));
		f.add(new Button("第6个按钮"));
		//设置窗体可见
		f.setVisible(true);
	}

}

2.BorderLayout示例:

import java.awt.*;

import javax.swing.JFrame;

public class Frame_BorderLayout {

	public static void main(String[] args) {
		Frame f =new Frame("BoderLayout");//创建一个名为BoderLayout的窗体
		f.setLayout(new BorderLayout());//设置窗体中的布局管理器BoderLayout
		f.setSize(300,300);//设置窗体的大小
		f.setLocation(300, 200);//设置窗体显示的位置
		f.setVisible(true);//设置窗体可见
		//下面代码创建5个按钮,分别用于填充BorderLayout的5个区域
		Button but1 = new Button("东部");
		Button but2 = new Button("西部");
		Button but3 = new Button("南部");
		Button but4 = new Button("北部");
		Button but5 = new Button("中部");
		//将创建好的按钮添加到窗体中,并设置按钮所在的区域
		f.add(but1,BorderLayout.EAST);
		f.add(but2,BorderLayout.WEST);
		f.add(but3,BorderLayout.SOUTH);
		f.add(but4,BorderLayout.NORTH);
		f.add(but5,BorderLayout.CENTER);
	}

}

3.GridLayout示例:

import java.awt.*;

public class Frame_GridLayout {

	public static void main(String[] args) {
		//创建一个名为GridLayout的窗体
		Frame f=new Frame("GridLayout");
		f.setLayout(new GridLayout(3,3));//设置该窗体为3*3网格
		f.setSize(300,300);//设置窗体大小
		f.setLocation(900,300);
		//循环添加9个按钮到GridLayout中
		for(int i=1;i<=9;i++){
			Button btn=new Button("btn"+i);
			f.add(btn);//向窗体中添加按钮
		}
		f.setVisible(true);
	}

}

4.GridBagLayout示例:

import java.awt.*;
//网格包布局管理器
class Layout extends Frame{
	public Layout(String title){
		GridBagLayout layout=new GridBagLayout();
		GridBagConstraints c=new GridBagConstraints();//约束对象
		this.setLayout(layout);//设置布局管理器
		c.fill=GridBagConstraints.BOTH;//设置组件横向纵向可以拉伸
		c.weightx=1;//设置横向权重为1
		c.weighty=1;//设置纵向权重为1
		//增加组件
		this.addComponent("btn1",layout,c);
		this.addComponent("btn2",layout,c);
		this.addComponent("btn3",layout,c);
		c.gridwidth=GridBagConstraints.REMAINDER;//添加的组件是本行最后一个组件
		this.addComponent("btn4",layout,c);
		
		c.weightx=0;//设置横向权重为0
		c.weighty=0;//设置纵向权重为0
		this.addComponent("btn5", layout, c);
		
		c.gridwidth=1;//设置组件第一个网络(默认值)
		this.addComponent("btn6", layout, c);
		
		c.gridwidth=GridBagConstraints.REMAINDER;//添加的组件是本行最后一个组件
		this.addComponent("btn7", layout, c);
		
		c.gridheight=2;//设置组件跨俩个网格
		c.gridwidth=1;//设置组件跨一个网格(默认值)
		c.weightx=1;//设置横向权重为2
		c.weighty=1;//设置纵向权重为2
		this.addComponent("btn8", layout, c);
		
		c.gridwidth=GridBagConstraints.REMAINDER;//添加的组件是本行最后一个组件
		c.gridheight=1;//设置组件跨一个网格(默认值)
		this.addComponent("btn9", layout, c);
		this.addComponent("btn10", layout, c);
		
		
		this.setTitle(title);
		this.pack();//设置自动窗体大小
		this.setVisible(true);
	}
	//
	public void addComponent(String name,GridBagLayout layout,GridBagConstraints c){
		Button bt =new Button(name);//创建一个名为name的按钮
		layout.setConstraints(bt, c);//设置约束对象和按钮的关联
		this.add(bt);//添加按钮
	}
}
public class Frame_GridBagLayout {
	public static void main(String[] args) {
	new Layout("GridBagLayout");

	}

}

5.CardLayout示例:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Frame_CardLayout extends Frame implements ActionListener{
	CardLayout cardLayout =new CardLayout();//定义卡片布局管理器
	Panel cardPanel = new Panel();//定义面板放置卡片
	Panel controlPanel =new Panel();//定义面板放置按钮
	Button preButton;//声明切换到上一张卡片的按钮
	Button nextButton;//声明切换到下一张卡片的按钮

	public Frame_CardLayout(){
		this.setSize(300,200);//设置窗体大小
		cardPanel.setLayout(cardLayout);//设置放置卡片的面板布局为卡片布局管理器
		//在cardPanel中添加3个文本标签
		cardPanel.add(new Label("第一个界面",Label.CENTER));
		cardPanel.add(new Label("第二个界面",Label.CENTER));
		cardPanel.add(new Label("第三个界面",Label.CENTER));
		
		//创建两个按钮
		nextButton = new Button("下一张卡片");
		preButton = new Button("下一张卡片");
		//将按钮添加到controlPanel面板中,panel默认为流式布局
		controlPanel.add(preButton);
		controlPanel.add(nextButton);
		//把面板添加到窗体中,窗体为默认边界布局
		this.add(cardPanel,BorderLayout.CENTER);
		this.add(controlPanel,BorderLayout.SOUTH);

		//为按钮添加事件监听器
		nextButton.addActionListener(this);
		preButton.addActionListener(this);
		//为窗口添加关闭事件监听器
		this.addWindowListener(new WindowAdapter(){
			public void windowClosing(WindowEvent e){
				Frame_CardLayout.this.dispose();
			}
		});
		
		this.setVisible(true);//设置窗体显示
	}
	
	//实现按钮监听触发,并对触发事件作为相应的处理
	public void actionPerformed(ActionEvent e){
		//如果用户点击nextButton执行操作
		if(e.getSource()==nextButton){
			//切换cardPanel面板当前的卡片向后切换一张
			cardLayout.next(cardPanel);
		}
		if(e.getSource()==preButton){
			//切换cardPanel面板当前的卡片向前切换一张
			cardLayout.previous(cardPanel);
		}
	}
	
	public static void main(String[] args) {
		Frame_CardLayout layout = new Frame_CardLayout();

	}

}

6.空布局管理器:

import java.awt.Button;
import java.awt.Frame;

public class Not_Layout {

	public static void main(String[] args) {
		Frame f =new Frame("不使用布局管理器");
		f.setLayout(null);//取消布局管理器
		f.setSize(300,150);
		Button btn1 =new Button("press");
		Button btn2 =new Button("pop");
		//设置按钮显示的位置与大小
		btn1.setBounds(50,50,100,30);
		btn2.setBounds(140,90,100,30);
		//添加按钮到窗口
		f.add(btn1);
		f.add(btn2);
		//显示窗口
		f.setVisible(true);
	}

}

7.事件处理机制:

import java.awt.Frame;
import java.awt.Window;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

public class Frame_Listener1 {

	public static void main(String[] args) {
		Frame f =new Frame("我的窗口");
		f.setSize(400,300);//设置窗口大小
		f.setLocation(300,200);//设置窗口显示位置
		f.setVisible(true);//设置窗口显示
		//为窗口组件注册监听器
		f.addWindowListener(new MyWindowListener());
	}

}
//创建MyWindowListenter类实现WindowListener接口
class MyWindowListener implements WindowListener{

	@Override
	public void windowActivated(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowClosed(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowClosing(WindowEvent e) {
		// 监听器监听事件对象做出处理
		Window window = e.getWindow();
		window.setVisible(false);
		//释放窗口
		window.dispose();
	}

	@Override
	public void windowDeactivated(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowDeiconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowIconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowOpened(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	
}

8.事件适配器示例:

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Frame_Listener2 {
	public static void main(String[] args) {
		//1.创建窗体
		Frame f = new Frame("我的窗体");
		f.setSize(400,300);//2.设置窗口大小
		f.setLocation(300,200);//3.设置窗口显示位置
		f.setVisible(true);//4.设置窗口显示
		//5.为窗口组件注册监听器
		f.addWindowListener(new MyWindowListener());
	}

}
//6.继承windowAdapter类,重写windowCosing()方法
class MyWindowLinstener extends WindowAdapter{
	public void windowClosing(WindowEvent e){
		Window window=(Window)e.getComponent();
		window.dispose();
	}
}

9.匿名内部类实现事件处理示例:

import java.awt.Button;
import java.awt.Frame;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class 匿名内部类实现事件处理 {

	public static void main(String[] args) {
		Frame f = new Frame("我的窗体");
		f.setSize(400,300);
		f.setLocation(300, 200);
		f.setVisible(true);
		Button btn = new Button("EXIT");
		f.add(btn);
		
		//用内部类的方式为按钮注册监听器
		btn.addMouseListener(new MouseAdapter(){
			@Override
			public void mouseClicked(MouseEvent e) {
				System.exit(0);
			}
		});
		
		
	}
}

10.键盘事件示例:

import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.TextField;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class keyEvent {

	public static void main(String[] args) {
		Frame f = new Frame("KeyEvent");
		f.setLayout(new FlowLayout());
		f.setSize(900,900);
		f.setLocation(300, 200);
		f.setVisible(true);
		
		TextField tf = new TextField(30);//创建文本对象
		f.add(tf);
		tf.addKeyListener(new KeyAdapter(){

			@Override
			public void keyPressed(KeyEvent e) {
				
				int keyCode=e.getKeyCode();//返回所按对应的整数值
				String s =KeyEvent.getKeyText(keyCode);//返回按键的字符串概述
				System.out.println("输入的内容为:"+s+",");
				System.out.println("对应的值:"+keyCode);
			}
			
		});
	}

}

11.窗体事件示例:

import java.awt.Frame;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

public class ListennerEvent1 {

	public static void main(String[] args) {
		Frame f = new Frame("WindowEvent");
		f.setSize(400,300);
		f.setLocation(300,200);
		f.setVisible(true);

		f.addWindowListener(new WindowListener(){

			@Override
			public void windowActivated(WindowEvent arg0) {
				System.out.println("windowActivated---窗体激活事件");
			}
			@Override
			public void windowClosed(WindowEvent arg0) {
				System.out.println("windowClosed---窗体关闭事件");
			}
			@Override
			public void windowClosing(WindowEvent arg0) {
				System.out.println("windowClosing---窗体正在关闭事件");
			}
			@Override
			public void windowDeactivated(WindowEvent arg0) {
				System.out.println("windowDeactivated---窗体停用事件");
			}
			@Override
			public void windowDeiconified(WindowEvent arg0) {
				System.out.println("windowDeiconified---窗体取消图标化事件");
			}
			@Override
			public void windowIconified(WindowEvent arg0) {
				System.out.println("windowIconified---窗体图标化事件");
			}
			@Override
			public void windowOpened(WindowEvent e) {
				System.out.print("windowOpened---窗体打开事件");
			}
		});
	}

}

12.鼠标事件示例:

import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class MouseEvent1 {

	public static void main(String[] args) {
		Frame f = new Frame("MouseEvent");
		//为窗口设置布局
		f.setLayout(new FlowLayout());
		f.setSize(300,200);
		f.setLocation(300,200);
		f.setVisible(true);
		
		Button but = new Button("but");
		f.add(but);
		but.addMouseListener(new MouseListener(){

			@Override
			public void mouseClicked(MouseEvent arg0) {
				System.out.println("mouseClicked--鼠标完成点击事件");
				
			}

			@Override
			public void mouseEntered(MouseEvent arg0) {
				System.out.println("mouseEntered--鼠标进入按钮区域事件");
				
			}

			@Override
			public void mouseExited(MouseEvent arg0) {
				System.out.println("mouseExited--鼠标移出按钮区域事件");
				
			}

			@Override
			public void mousePressed(MouseEvent arg0) {
				System.out.println("mouseClicked--鼠标按下事件");
				
			}

			@Override
			public void mouseReleased(MouseEvent arg0) {
				System.out.println("mouseReleased--鼠标放开事件");
				
			}
			
		});
	}

}

13.Jtable组件示例:

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class Jtable1 extends JFrame{
	public Jtable1(){
		init();//使用JTable对象创建表格
	}
	
	//使用JTable对象创建表格
	public void init(){
		//定义一维数组作为列标题
		Object[] columnNames={"姓名","年龄","性别"};
		//定义二维数组作为表格行对象数据
		Object[][]rowData={
				new Object[]{"李清照","29","女"},
				new Object[]{"苏格拉底","56","男"},
				new Object[]{"胡适","26","男"},
				new Object[]{"虎头","3","男"},
		};
		//创建一个表格
		JTable table = new JTable(rowData,columnNames);
		//添加表格组件到窗体中
		JScrollPane pane = new JScrollPane();
		pane.setViewportView(table);
		this.add(pane);
		//this.add(new JScrollPane(table));
		//设置自适应JFrame窗体大小
		this.pack();
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
	}
	public static void main(String[] args) {
		new Jtable1();

	}

}

14.JCheckBox示例:

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class JCheckBox1 extends JFrame{
	public JCheckBox1(){
		//创建一个标签,标签文本居中对齐
		JLabel label = new JLabel("TT欢迎你!",JLabel.CENTER);
		label.setFont(new Font("宋体",Font.PLAIN,20));//设置标签文本的字体
		this.add(label);//把标签添加到窗体中显示
		
		//下面的
		JCheckBox italic = new JCheckBox("italic");//倾斜
		JCheckBox bold = new JCheckBox("BOLD");//加粗
		JPanel panel = new JPanel();//创建一个面板
		//添加复选框按钮到面板中
		panel.add(italic);
		panel.add(bold);
		this.add(panel,BorderLayout.SOUTH);//
		
		//为复选框定义ActionListener监听器
		ActionListener listener = new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				int mode = Font.PLAIN;//字体默认样式
				if(italic.isSelected()){
					//选中了倾斜复选框
					mode+=Font.ITALIC;
				}
				if(bold.isSelected()){
					//选中了加粗复选框
					mode+=Font.BOLD;
				}
				//设置标签文字的样式
				label.setFont(new Font("宋体",mode,20));
			}
			
		};
		//为两个复选框添加监听器
		italic.addActionListener(listener);
		bold.addActionListener(listener);
		this.setSize(300,300);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
	}
	public static void main(String[] args) {
		new JCheckBox1();

	}

}

15.JComboBox示例:

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

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class JComboBox1 extends JFrame{
	public JComboBox1(){
		//创建JPanel面板
		JPanel panel = new JPanel();
		//创建一个下拉列表
		JComboBox<String>comboBox = new JComboBox<String>();
		//为下拉列表添加选项
		comboBox.addItem("请选择城市");
		comboBox.addItem("北京");
		comboBox.addItem("天津");
		comboBox.addItem("南京");
		comboBox.addItem("上海");
		comboBox.addItem("重庆");
		//创建一个文本框
		JTextField field = new JTextField(20);
		//添加组件到面板中
		panel.add(comboBox);
		panel.add(field);
		//把面板添加到窗体上
		this.add(panel);
		
		this.setSize(350,100);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
		
		//为下拉列表添加事件监听器
		comboBox.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				String item =(String)comboBox.getSelectedItem();
				if("请选择城市".equals(item)){
					field.setText("");
				}else{
					field.setText("您选择的城市是:"+item);
				}
				
			}
			
		});
	}
	public static void main(String[] args) {
		new JComboBox1();

	}

}

16.JDialog示例:

import java.awt.FlowLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
public class JDialog1 {
	public static void main(String[] args) {
		//1创建两个按钮
		JButton btn1 = new JButton("模式对话框");
		JButton btn2 = new JButton("非模式对话框");
		JFrame f =new JFrame("DialogDemo");
		f.setSize(300,300);
		f.setLocation(300,200);
		f.setLayout(new FlowLayout());
		f.add(btn2);
		f.add(btn1);
		//设置点击关闭按钮的模式关闭窗口操作
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.setVisible(true);
		//创建JDialog
		final JDialog dialog = new JDialog(f,"Dialog");
		dialog.setSize(300,300);
		dialog.setLocation(350,350);
		dialog.setLayout(new FlowLayout());
		JButton btn3 = new JButton("确定");//在对话框中创建一个按钮
		dialog.add(btn3);
		Label label = new Label("标签");//在对话框中创建一个标签
		dialog.add(label);
		//为“模式对话框”按钮添加点击事件
		btn1.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				//设置对话框的状态为模式对话框
				dialog.setModal(true);
				//修改标签的内容
				label.setText("模式对话框,点击确定按钮关闭");
				//显示对话框
				dialog.setVisible(true);
			}
			
		});
		//为“非模式对话框”按钮添加点击事件
				btn2.addActionListener(new ActionListener(){

					@Override
					public void actionPerformed(ActionEvent e) {
						//设置对话框的状态为模式对话框
						dialog.setModal(false);
						//修改标签的内容
						label.setText("非模式对话框,点击确定按钮关闭");
						//显示对话框
						dialog.setVisible(true);
					}
					
				});
				//为对话框中按钮添加点击事件
				btn3.addActionListener(new ActionListener(){

					@Override
					public void actionPerformed(ActionEvent e) {
						dialog.dispose();//关闭
						
					}
					
				});
	}

}

17.JMenuBar示例:

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

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class JMenuBar1 extends JFrame{
	public JMenuBar1(){
		JMenuBar menuBar = new JMenuBar();//创建菜单栏
		JMenu menu = new JMenu("操作");//创建菜单
		JMenuItem item1 = new JMenuItem("弹出窗口");//创建两个菜单项
		JMenuItem item2 = new JMenuItem("关闭");	
		//组建下拉式菜单
		menu.add(item1);
		menu.addSeparator();//添加分隔符
		menu.add(item2);
		menuBar.add(menu);//菜单添加到菜单栏
		this.setJMenuBar(menuBar);//菜单栏添加到窗体
		
		this.setSize(500,500);
		this.setVisible(true);
		
		//为菜单项添加事件监听器
		item1.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				JDialog dialog = new JDialog(JMenuBar1.this,true);
				dialog.setTitle("弹出对话框");
				dialog.setSize(200,200);
				dialog.setVisible(true);
			}
			
		});
		item2.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				System.exit(0);
			}
			
		});
	}
	public static void main(String[] args) {
		new JMenuBar1();

	}

}

18.JPopupMenu示例:

import java.awt.event.*;
import javax.swing.*;
//右键弹出式菜单
public class JPopupMenu1 extends JFrame{
	public JPopupMenu1(){
		//创建一个JPopupMenu菜单
		JPopupMenu popupMenu = new JPopupMenu();
		//创建三个菜单项
		JMenuItem refreshItem = new JMenuItem("refresh");//刷新
		JMenuItem createItem = new JMenuItem("create");//新建
		JMenuItem exitItem = new JMenuItem("exit");//退出
		//把菜单项添加到菜单中
		popupMenu.add(refreshItem);
		popupMenu.add(createItem);
		popupMenu.addSeparator();//添加菜单项的分隔符
		popupMenu.add(exitItem);
		
		//为JFrame添加鼠标clicked的事件监听器
		this.addMouseListener(new MouseAdapter(){

			@Override
			public void mouseClicked(MouseEvent e) {
				//如果点击的是鼠标的右键,显示弹出式菜单
				if(e.getButton()==e.BUTTON3){
					popupMenu.show(e.getComponent(),e.getX(),e.getY());
				}
			}
			
		});
		//为菜单项添加事件监听器
		exitItem.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				System.exit(0);
				
			}
			
		});
		
		this.setSize(500,500);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
	}
	public static void main(String[] args) {
		new JPopupMenu1();

	}

}

19.JRadioButton示例:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class JRadioButton1 extends JFrame{
	public JRadioButton1(){
		JPanel pallet = new JPanel();//创建一个调色板
		this.add(pallet,BorderLayout.CENTER);//将调色板添加到窗体的中间位置
		
		ButtonGroup group = new ButtonGroup();//单选按钮组对象
		final JRadioButton btn1 = new JRadioButton("灰");
		final JRadioButton btn2 = new JRadioButton("粉");
		final JRadioButton btn3 = new JRadioButton("黄");
		//添加按钮到按钮组中
		group.add(btn1);
		group.add(btn2);
		group.add(btn3);
		JPanel panel = new JPanel();//创建一个面板
		panel.add(btn1);//添加三个单选框按钮到面板
		panel.add(btn2);
		panel.add(btn3);
		//添加面板到窗体的下方
		this.add(panel,BorderLayout.SOUTH);
		
		//创建单选框的ActionListener监听器
		ActionListener Listener = new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				Color color = null;
				if(btn1.isSelected()){
					color=Color.GRAY;
				}else if(btn2.isSelected()){
					color=Color.PINK;
				}else if(btn3.isSelected()){
					color=Color.YELLOW;
				}
				//为调色板设置背景颜色
				pallet.setBackground(color);
			}
			
		};
		//为单选框添加监听器
		btn1.addActionListener(Listener);
		btn2.addActionListener(Listener);
		btn3.addActionListener(Listener);
		
		this.setSize(300,300);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
	}
	public static void main(String[] args) {
		new JRadioButton1();

	}

}

20.中间容器示例:

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;

//中间容器添加按钮
public class 中间容器1 extends JFrame{
	public 中间容器1(){
		this.setTitle("PanelDemo");
		
		//定义一个JPanel面板
		JPanel panel = new JPanel();
		//在panel面板中添加四个按钮
		panel.add(new JButton("按钮1"));
		panel.add(new JButton("按钮2"));
		panel.add(new JButton("按钮3"));
		panel.add(new JButton("按钮4"));
		
				
		//创建一个滚动面板
		JScrollPane scrollPane = new JScrollPane();
		//设置水平滚动条一直显示
		scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
		//设置垂直滚动条需要时显示
		scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
		
		//设置panel面板在滚动面板中显示
		scrollPane.setViewportView(panel);
		//将面板scrollPane添加到窗体中
		this.add(scrollPane);
		
		//在panel面板中添加到窗体中
//				this.add(panel);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setSize(400,250);
		this.setVisible(true);
	}
	public static void main(String[] args) {
		new 中间容器1();

	}

}

21.文本组件示例:

import java.awt.BorderLayout;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
//文本组件JTextField和JTextArea组件的使用
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class 文本组件1 extends JFrame{
	public 文本组件1(){
		this.setLayout(new BorderLayout());//设置窗口的布局
		this.setTitle("聊天窗口");//设置窗口标题
		this.setSize(400,300);//设置窗口大小
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setDefaultLookAndFeelDecorated(true);
		
		JTextArea chatContent = new JTextArea(12,34);//创建一个文本域
		//创建一个滚动面板并把文本域添加到其中
		JScrollPane showPanel = new JScrollPane(chatContent);
		chatContent.setEditable(false);//设置文本域不可编辑
		//添加滚动面板到窗体上
		this.add(showPanel,BorderLayout.CENTER);
		//下面部分
		Label label = new Label("聊天信息");//创建一个标签
		JTextField inputField = new JTextField(20);//创建一个文本框
		JButton sendBt = new JButton("发送");//创建一个按钮
		JPanel inputPanel = new JPanel();//创建一个面板,用来存放下面的组件
		inputPanel.add(label); //添加组件到下面的面板中
		inputPanel.add(inputField);
		inputPanel.add(sendBt);

		//添加下面的面板到窗口中
		this.add(inputPanel,BorderLayout.SOUTH);
		
		//为按钮添加事件
		sendBt.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
			String content=inputField.getText();//获取输入的文本框内容
				if(content!=null&&!content.trim().equals("")){//内容不是空且				//如果不为空,将输入的文本信息追加到
					chatContent.append("本人:"+content+"\n");
				}else{
					//如果为空,提示聊天信息不能为空
					chatContent.append("聊天内容不能为空"+"\n");
				}
				inputField.setText("");//将输入框设置为空
			}
			
		});
		inputField.addKeyListener(new KeyAdapter(){

			@Override
			public void keyPressed(KeyEvent e) {
				if(e.getKeyCode()==e.VK_ENTER){//如果获取到的是回车键
					String content=inputField.getText();//获取输入的文本框内容
					if(content!=null&&!content.trim().equals("")){//内容不是空且				 
                     //如果不为空,将输入的文本信息追加到
						chatContent.append("本人:"+content+"\n");
					}else{
						//如果为空,提示聊天信息不能为空
						chatContent.append("聊天内容不能为空"+"\n");
					}
					inputField.setText("");//将输入框设置为空
				}
				
			}
		});
		this.setVisible(true);
	}
	public static void main(String[] args) {
		new 文本组件1();

	}

}

 

8.优化程序与小项目

持续更新中..............

 

 


注:

本文参照过杨夏老师的《Java核心技术》课程、王敏老师的《JAVA高级开发》课程、《java基础案例教程》、江苏海洋大学java面向对象程序设计MOOC、《java核心技术》,对内容有任何问题的同学欢迎留言。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章