圖形用戶界面開發(gui)
在學習swing前,我們需要了解這樣幾個概念:awt、swing、swt、Jface。
sun公司提供了一個跨平台GUI開發工具包awt(抽象窗口工具箱Abstract Window Toolkit)。
sun公司又提供了swing,解決swt中存在的lcd(本地化)問題。
IBM為了解決swing耗內存的問題,創建了新的gui庫swt。
IBM在swt的基礎上開發了更強大的JFace。
Swing組件分類:
1、頂層容器:JFrame、JApplet、JDialog
2、中間層容器:JPanel、JScrollPane、JSplitPane、JToolBar
3、特殊中間層容器:JIternalFrame、JLayeredPane、JRootPane
4、基本控制容器:JButton、JComboBox、JList、JMenu、JSlider、JTestField
5、不可編輯信息顯示容器:JLable、JProgressBar
6、可編輯信息顯示容器:JTable、JFileChooser、JTree
一個swing例子Swing.java,顯示helloWorld。
package com.test.swing; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class Swing extends JFrame{ //一個組件 public JLabel label = null; //JPanel是一個中間層容器類,可以添加其他組件。 public JPanel jPanel = null; public Swing(){ //給窗體設置標題 this.setTitle("helloWorld!"); //設置大小,按像素計數 this.setSize(300, 300); //設置窗口初始位置 this.setLocation(100, 200); //顯示 this.setVisible(true); //設置當關閉窗口時,jvm也關閉 this.setDefaultCloseOperation(this.EXIT_ON_CLOSE); jPanel = new JPanel(); label = new JLabel("helloWorld!"); //將組件添加到中間層組件。 jPanel.add(label); //將中間層組件設置為頂層組件的內容面板。 this.setContentPane(jPanel); } /** * @main */ public static void main(String[] args) { Swing swing = new Swing(); } }
布局管理器:
組件在容器中的位置和大小是由布局管理器來決定的,所有的組件都會使用一個布局管理器,通過它來自動進行布局管理。
java提供五種布局管理器:流式布局管理器(FlowLayout)、邊界布局管理器(BorderLayout)、網格布局管理器(GridLayout)、卡片布局管理器(CardLayout)、網格包布局管理器(GridBagLayout)。
流式布局:按順序從左到右,可指定對齊方式,左對齊右對齊居中對齊等。
邊界布局:將容器簡單的划分為東西南北中五個區域,中間區域最大,不是五個部分都必須添加。
網格布局:將容器划分為多列,組件被依次填充到每個網格中,從左上角開始。
JFrame、JDialog對話框組件你默認邊界布局。
代碼編寫步驟:
1、繼承JFrame
2、定義你需要的組件
3、創建組件(構造函數)
4、添加組件
5、對窗體進行設置
6、顯示窗體
樣例:
this.add(label1, BorderLayout.EAST); this.add(label2, BorderLayout.NORTH);
指定布局管理器:
jPanel.setLayout(new BorderLayout());
流式布局管理器:
jPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
拆分窗格:
JSplitPane jSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,jPanel,label1);