Swing 的組件與AWT 組件相似,但又為每一個(gè)組件增添了新的方法,并提供了更多的高級(jí)組件.
Swing 的基本組件:
1.按鈕(JButton):
Swing 中的按鈕可以顯示圖像,并且可以將按鈕設(shè)置為窗口的默認(rèn)圖標(biāo),而且還可以將多個(gè)圖像指定給一個(gè)按鈕。
(1).JButton 常用的構(gòu)造方法。
JButton(String text):按鈕上顯示字符。
JButton(Icon icon) :按鈕上顯示圖標(biāo)。
JButton(String text, Icon icon):按鈕上既顯示圖標(biāo)又顯示字符。
(2).常用方法:
b1.setEnabled(false); //使按鈕當(dāng)前不可用
b1.setToolTipText("..."): //設(shè)置按鈕提示文本
b1.setMnemonic(KeyEvent.VK_D);// 將b1邦定alt+D鍵
(3).案例代碼:
public class JButtonExample3 extends JPanel implements ActionListener {
protected JButton b1, b2, b3;
public JButtonExample3() {
ImageIcon leftButtonIcon = createImageIcon("right.gif");
ImageIcon middleButtonIcon = createImageIcon("middle.gif");
ImageIcon rightButtonIcon = createImageIcon("left.gif");
b1 = new JButton("失效中間按鈕(D)", leftButtonIcon);
b1.setVerticalTextPosition(AbstractButton.CENTER);// 水平中間對(duì)齊
b1.setHorizontalTextPosition(AbstractButton.LEADING);// 相當(dāng)于LEFT
b1.setMnemonic(KeyEvent.VK_D);// 將b1邦定alt+D鍵
b1.setActionCommand("disable");
b2 = new JButton("M中間按鈕", middleButtonIcon);
b2.setVerticalTextPosition(AbstractButton.BOTTOM);
b2.setHorizontalTextPosition(AbstractButton.CENTER);
b2.setMnemonic(KeyEvent.VK_M);// 將b2邦定alt+M鍵
b3 = new JButton("E激活中間按鈕", rightButtonIcon);
b3.setMnemonic(KeyEvent.VK_E);// 將b3邦定alt+E鍵
b3.setActionCommand("enable");
b3.setEnabled(false);
// 給1和3添加事件監(jiān)聽(tīng)
b1.addActionListener(this);
b3.addActionListener(this);
// 設(shè)置按鈕提示文本
b1.setToolTipText("點(diǎn)擊這個(gè)按鈕,將使中間的按鈕失效!");
b2.setToolTipText("點(diǎn)擊這個(gè)按鈕,沒(méi)有任何的事件發(fā)生!");
b3.setToolTipText("點(diǎn)擊這個(gè)按鈕,將使中間的按鈕有效");
// 將按鈕添加到JPanel中
add(b1);
add(b2);
add(b3);
}
public void actionPerformed(ActionEvent e) {
if ("disable".equals(e.getActionCommand())) {
b2.setEnabled(false);
b1.setEnabled(false);
b3.setEnabled(true);
} else {
b2.setEnabled(true);
b1.setEnabled(true);
b3.setEnabled(false);
}
}
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = JButtonExample3.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn′t find file: " + path);
return null;
}
}
public static void main(String[] args) {
// 設(shè)置使用新的swing界面
//提供一個(gè)關(guān)于新創(chuàng)建的 JFrame 是否應(yīng)該具有當(dāng)前外觀為其提供的 Window 裝飾(如邊框、關(guān)閉窗口的小部件、標(biāo)題等等)的提示。
JFrame.setDefaultLookAndFeelDecorated(true);
// 創(chuàng)建一個(gè)窗體
JFrame frame = new JFrame("小龍按鈕");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 創(chuàng)建一個(gè)面板
JButtonExample3 newContentPane = new JButtonExample3();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
// 顯示窗體
frame.pack();
frame.setLocation(300, 200);
frame.setVisible(true);
}
}
運(yùn)行截圖:
2.組合框(JComboBox):
組合框(下拉列表JComboBox)使用方法及示例詳解:
構(gòu)造方法:
* JComboBox() 建立一個(gè)JComboBox組件.
* JComboBox(ComboBoxModel model) 根據(jù)model建立一個(gè)JComboBox組件.
* JComboBox(Objext[] items) 利用數(shù)組對(duì)象建立一個(gè)JComboBox組件.
* JComboBox(Vector items) 利用Vector對(duì)象建立一個(gè)JComboBox組件.
常用方法:
....
綜合示例:
import java.awt.*; /* 包含用于創(chuàng)建用戶界面和繪制圖形圖像的所有類。 */
import javax.swing.*; /* 提供一組"輕量級(jí)"組件,盡量讓這些組件在所有平臺(tái)上的工作方式都相同 */
public class JComboBoxDemo extends JFrame {
public JComboBoxDemo() {
/*
* Container是所有容器的父類,又是Java語(yǔ)言的組件類Component的子類. 容器是一種具有容納其他組件和容器的功能的組件
* 一個(gè)Java的圖形用戶界面的最基本元素是組件,組件是可以以圖形化的方式顯示在屏幕上并能與用戶進(jìn)行交互的對(duì)象,如一個(gè)按鈕,一個(gè)文本框等.
* 在Java中,通常將組件放在一定的容器內(nèi)使用 this.getContentPane()方法返回此窗體的 contentPane 對(duì)象
*/
Container contentPane = this.getContentPane();
/* 創(chuàng)建一個(gè)面板對(duì)象,指定布局管理器為GridLayout,1行2列.Jpanel的默認(rèn)版面管理為FlowLayout */
JPanel jPanel1 = new JPanel(new GridLayout(1, 2));
// 利用String數(shù)組建立JComboBox
String[] fruit = { "蘋果", "香蕉", "桔子", "梨", "芒果" };
JComboBox jComboBox1 = new JComboBox(fruit);
jComboBox1.addItem("其他"); // 在列表框選項(xiàng)的最后再添加一個(gè)"其他"選項(xiàng)
// 設(shè)置jList1對(duì)象的帶標(biāo)題邊框
jComboBox1.setBorder(BorderFactory.createTitledBorder("您最喜歡的水果:"));
// 添加列表框jComboBox1至面板
jPanel1.add(jComboBox1);
// 利用ComboBoxModel建立JComboBox
ComboBoxModel myModel = new MyModel();
JComboBox jComboBox2 = new JComboBox(myModel);
// 設(shè)置jList1對(duì)象的帶標(biāo)題邊框
jComboBox2.setBorder(BorderFactory.createTitledBorder("您最喜歡的水果:"));
// 添加列表框jComboBox2至面板
jPanel1.add(jComboBox2);
// 添加面板至父容器
contentPane.add(jPanel1);
// 設(shè)置本窗體的標(biāo)題
this.setTitle("JComboBoxDemo");
// 設(shè)置本窗體顯示的初始大小
this.setSize(350, 90);
this.setLocation(300, 200);
// 設(shè)置本窗體初始可見(jiàn)
this.setVisible(true);
}
class MyModel extends DefaultComboBoxModel {
String[] fruit = { "蘋果", "香蕉", "桔子", "梨", "芒果" };
MyModel() {
for (int i = 0; i < fruit.length; i++) {
/* addElement()方法用于向列表框添加選項(xiàng)元素 */
this.addElement(fruit[i]);
}
}
}
public static void main(String args[]) {
JComboBoxDemo test = new JComboBoxDemo();
}
}
截圖:
3.列表框(JList):
列表框的功能與下拉列表框相似,也是讓用戶在幾個(gè)條目中做出選擇,但又有一些區(qū)別,它提供給用戶的選擇模式更為多樣,分別是單一選擇、連續(xù)選擇、多項(xiàng)選擇,對(duì)應(yīng)于 ListSelectionModel 中的3個(gè)常量:
(1) static int SINGLE_SELECTION 只能選擇一條。
(2) static int SINGLE_INTERVAL_SELECTION 按住[Shift]鍵可選擇聯(lián)系的區(qū)間。
(3) static int MULTIPLE_INTERVAL_SELECTION 按住[Ctrl]鍵可選擇多條。
構(gòu)造函數(shù)如下:
(1) JList() 建立一個(gè) JList 組件。
(2) JList(ListModel model) 根據(jù) model 建立一個(gè) JList 組件。
(3) JList(Object[] items) 利用數(shù)組對(duì)象建立一個(gè) JList 組件。
(4) JList(Vector items) 利用 Vector 對(duì)象建立一個(gè) JList 組件。
將列表框JList添加到JScrollPane中可以實(shí)現(xiàn)列表框的滾動(dòng).
列表(JList)組件使用示例1如下:
public class JListDemo1 extends JFrame{
Container contentPane;
JPanel jp;
JList jList1,jList2,jList3;
public JListDemo1(){
contentPane = this.getContentPane();
jp = new JPanel(new GridLayout(1,3));
//利用String數(shù)組建立JList對(duì)象
String[] fruit={"蘋果","香蕉","桔子","梨","芒果"};
jList1=new JList(fruit);
//設(shè)置jList1對(duì)象的帶標(biāo)題邊框
jList1.setBorder(BorderFactory.createTitledBorder("您最喜歡的水果: "));
//設(shè)置jList1對(duì)象的選擇模式為單一選擇
jList1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jp.add(jList1);
//利用ListModel建立JList對(duì)象,可實(shí)現(xiàn)列表內(nèi)容的動(dòng)態(tài)
ListModel myModel=new MyModel(); //創(chuàng)建一個(gè)列表模型對(duì)象
jList2=new JList(myModel); //根據(jù)列表模型對(duì)象創(chuàng)建列表
jList2.setBorder(BorderFactory.createTitledBorder("您最喜歡的水果: "));
//設(shè)置jList2對(duì)象的選擇模式為按住[Ctrl]可多項(xiàng)選擇
jList2.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
jp.add(jList2);
jList3=new JList(fruit);
jList3.setBorder(BorderFactory.createTitledBorder("您最喜歡的水果: "));
jList3.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
jList3.setVisibleRowCount(3);
jList3.setFixedCellWidth(120);
jList3.setFixedCellHeight(30);
JScrollPane jScrollPane = new JScrollPane(jList3);
jp.add(jScrollPane);
contentPane.add(jp);
this.setTitle("JListDemo");
this.setSize(340,200);
//pack();
this.setLocation(400, 300);
this.setVisible(true);
}
//通過(guò)繼承DefaultListModel類可實(shí)現(xiàn)動(dòng)態(tài)內(nèi)容的列表選擇
class MyModel extends DefaultListModel{
String[] fruit={"蘋果","香蕉","桔子","梨","芒果"};
MyModel(){
for(int i=0;i<fruit.length;i++){
/* void addElement(Object obj)
* 將指定組件添加到此類表的末尾。*/
this.addElement(fruit[i]);
}
}
}
public static void main(String[] args){
JListDemo1 test=new JListDemo1();
}
}
運(yùn)行結(jié)果如下圖所示:
列表框示例2代碼:
public class JListDemo2 extends JFrame {
Container contentPane;
JPanel jp;
JList jListFont, jListSize;
// 構(gòu)造函數(shù)
public JListDemo2() {
contentPane = this.getContentPane();
jp = new JPanel(new GridLayout());
setJListFont();
setJListFontSize();
contentPane.add(jp);
this.setTitle("JListDemo");
this.setSize(240, 200);
this.setLocation(400, 300);
this.setVisible(true);
} // End of JListDemo2
public void setJListFont() {
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
final String fontName[] = ge.getAvailableFontFamilyNames(); // 獲取系統(tǒng)的本地字體
jListFont = new JList(fontName);
// 設(shè)置jList1對(duì)象的帶標(biāo)題邊框
jListFont.setBorder(BorderFactory.createTitledBorder("系統(tǒng)字體: "));
// 設(shè)置jList1對(duì)象的選擇模式為單一選擇
jListFont.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jListFont.setVisibleRowCount(3);
jListFont.setFixedCellWidth(120);
jListFont.setFixedCellHeight(20);
JScrollPane jScrollPane1 = new JScrollPane(jListFont);
jp.add(jScrollPane1);
}
public void setJListFontSize() {
final String fontSize[] = { "8", "9", "10", "12", "14", "15", "16",
"18", "20", "21", "22", "24", "26", "28", "30", "36", "48",
"54", "72", "89" };
// 創(chuàng)建字號(hào)的列表框listSize
jListSize = new JList(fontSize);
jListSize.setBorder(BorderFactory.createTitledBorder("字體大小: "));
// 設(shè)置jList2對(duì)象的選擇模式為按住[Ctrl]可多項(xiàng)選擇
jListSize
.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
jListSize.setVisibleRowCount(3);
jListSize.setFixedCellWidth(120);
jListSize.setFixedCellHeight(20);
JScrollPane jScrollPane2 = new JScrollPane(jListSize);
jp.add(jScrollPane2);
}
public static void main(String[] args) {
JListDemo2 test = new JListDemo2();
}
}
程序運(yùn)行示意圖:
4.javax.swing
類 JColorChooser:
JColorChooser (顏色選擇對(duì)話框)提供一個(gè)用于允許用戶操作和選擇顏色的控制器窗格。
JColorChooser構(gòu)造函數(shù):
JColorChooser():建立一個(gè)JColorChooer對(duì)象,默認(rèn)顏色為白色.
JColorChooser(Color initialColor):建立一個(gè)JColorChooer對(duì)象,并設(shè)置初始顏色.
JColorChooser(ColorSelectionModel modal):以ColorSelectionModel構(gòu)造JColorChooser對(duì)象.
最常使用JColorChooser的方式是使用JColorChooser的靜態(tài)方法showDialog().也就是說(shuō)在大部份的情況下,我們不會(huì)new一個(gè)JColorChooser對(duì)象,而是直接使用JColorChooser的靜態(tài)方法(showDialog())來(lái)輸出顏色選擇對(duì)話框.利用這個(gè)方法我們亦可以得到用戶所選擇的顏色,若用戶沒(méi)有選擇則返回null值.
顏色選擇對(duì)話框的簡(jiǎn)單案例1代碼:
public class JColorChooserDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("JColorChooserDemo");
MyPanel panel = new MyPanel();
frame.getContentPane().add(panel);
frame.pack();
frame.setLocation(300, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class MyPanel extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private JButton button,rgb,red,green,blue;
private Color color = new Color(255, 51, 150);
public MyPanel() {
button = new JButton("Get Color");
rgb = new JButton("RGB: ");
red = new JButton("Red: ");
green = new JButton("Green: ");
blue = new JButton("Blue: ");
button.addActionListener(this);
setPreferredSize(new Dimension(550, 250));
setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
setBackground(color);
add(button);
add(rgb);
add(red);
add(green);
add(blue);
}
public void actionPerformed(ActionEvent e) {
color = JColorChooser.showDialog(this, "Choose Color", color);
if (color != null) {
setBackground(color);
button.setText("Get again");
rgb.setText("RGB: " + color.getRGB());
red.setText("Red: " + color.getRed());
green.setText("Green: " + color.getGreen());
blue.setText("Blue: " + color.getBlue());
}
}
}
運(yùn)行結(jié)果示意圖如下:
另外還有一個(gè)使用JColorChooser常用的方式,那就是使用createDialog()靜態(tài)方法.使用這個(gè)靜態(tài)方法后會(huì)得到一個(gè)JDialog對(duì)象,我們可以利用這個(gè)JDialog對(duì)象對(duì)顏色選擇對(duì)話框做更多的設(shè)置.不過(guò)利用這個(gè)方法必須配合JColorChooser對(duì)象才行,也就是必須new出一個(gè)JColorChooser對(duì)象來(lái).下面范例介紹最簡(jiǎn)單的也是最實(shí)用JColorChooser,選擇顏色完畢后就能更改JLabel上的背景顏色.
顏色選擇對(duì)話框的簡(jiǎn)單案例2代碼:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ColorChooserDemo1 extends MouseAdapter {
JFrame f = null;
JLabel label = null;
JLabel label1 = null;
JLabel label2 = null;
Rectangle rec1 = null;
Rectangle rec2 = null;
public ColorChooserDemo1() {
f = new JFrame("ColorChooser Example");
Container contentPane = f.getContentPane();
contentPane.addMouseListener(this);
label = new JLabel(" ", JLabel.CENTER);
label.setPreferredSize(new Dimension(300, 20));
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1, 2));
label1 = new JLabel("左Label", JLabel.CENTER);
label1.setBackground(Color.red);
label1.setForeground(Color.black);
label1.setOpaque(true);
label1.setBounds(0, 0, 150, 150);
panel.add(label1);
label2 = new JLabel("右Label", JLabel.CENTER);
label2.setBackground(Color.green);
label2.setForeground(Color.black);
label2.setOpaque(true);
label2.setBounds(150, 0, 150, 150);
panel.add(label2);
rec1 = label1.getBounds();
rec2 = label2.getBounds();
contentPane.add(panel, BorderLayout.CENTER);
contentPane.add(label, BorderLayout.SOUTH);
f.setSize(new Dimension(300, 150));
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
// 實(shí)現(xiàn)MouseAdapter中的mousePressed()與mouseClicked()方法.當(dāng)按下鼠標(biāo)時(shí),就能知道鼠標(biāo)光標(biāo)目前的位置.當(dāng)連續(xù)鍵擊鼠標(biāo)
// 兩次時(shí),若光標(biāo)所在位置在label中,就會(huì)出現(xiàn)顏色選擇對(duì)話框,用戶可選擇任一顏色更改label的顏色.
public void mousePressed(MouseEvent e) {
label.setText("目前鼠標(biāo)坐標(biāo)(X,Y)為:(" + e.getX() + "," + e.getY() + ")");
}
public void mouseClicked(MouseEvent e) {
Point point = e.getPoint();
if (e.getClickCount() == 2) {
if (rec1.contains(point)) {
/*
* 利用JColorChooser的showDialog()靜態(tài)方法輸出顏色選擇對(duì)話框
* ,showDialog()中的3個(gè)參數(shù)依次是: 對(duì)話框的父組件,顏色選擇對(duì)話框標(biāo)題
* ,與對(duì)話框默認(rèn)顏色.當(dāng)用戶選擇完顏色之后,按下"OK"按鈕則返回
* Color對(duì)象,若按下"Cancel"按鈕則返回null值.
*/
Color color = JColorChooser.showDialog(f,
"Change label1 Color", Color.white);
if (color != null) // 若為null值表示用戶按下Cancel按鈕
label1.setBackground(color);
}
if (rec2.contains(point)) {
Color color = JColorChooser.showDialog(f,
"Change label2 Color", Color.yellow);
if (color != null) // 若為null值表示用戶按下Cancel按鈕
label2.setBackground(color);
}
}
}
public static void main(String[] arg) {
new ColorChooserDemo1();
}
}
程序運(yùn)行示意圖: