再見!【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核心技術》,對內容有任何問題的同學歡迎留言。

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