Sunday, 13 May 2007

复选框、选项按钮、列表方框、下拉式列表的使用与介绍

7-1:使用JCheckBox组件:
类层次结构图:
java.lang.Object
--java.awt.Component
--java.awt.Container
--javax.swing.JComponent
--javax.swing.AbstractButton
--javax.swing.JToggleButton
--javax.swing.JCheckBox
JCheckBox与JRadioButton为JToggleButton的子类,因此它们可以使用AbstractButton抽象类里面许多好用的方法,如addItemLi
stener()、setText()、isSelected()等等。
构造函数:
JCheckBox():建立一个新的JChcekBox.
JCheckBox(Icon icon):建立一个有图像但没有文字的JCheckBox.
JCheckBox(Icon icon,boolean selected):建立一个有图像但没有文字的JCheckBox,且设置其初始状态(有无被选取)。
JCheckBox(String text):建立一个有文字的JCheckBox.
JCheckBox(String text,boolean selected):建立一个有文字的JCheckBox,且设置其初始状态(有无被选取)。
JCheckBox(String text,Icon icon):建立一个有文字且有图像的JCheckBox,初始状态为无被选取。
JCheckBox(String text,Icon icon,boolean selected):建立一个有文字且有图像的JCheckBox,且设置其初始状态(有无被选取
)。
7-1-1:构造JCheckBox组件:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JCheckBox1{
public static void main(String[] args){
JFrame f=new JFrame("JCheckBox1");
Container contentPane=f.getContentPane();
contentPane.setLayout(new GridLayout(2,1));
JPanel p1=new JPanel();
p1.setLayout(new GridLayout(1,3));
p1.setBorder(BorderFactory.createTitledBorder("你最喜欢哪一家快餐店呢?"));
JCheckBox c1=new JCheckBox("麦当劳");
JCheckBox c2=new JCheckBox("肯德基");
JCheckBox c3=new JCheckBox("21世纪");
p1.add(c1);
p1.add(c2);
p1.add(c3);
JPanel p2=new JPanel();
p2.setLayout(new GridLayout(2,1));
p2.setBorder(BorderFactory.createTitledBorder("以下为JCheckBox的图形示范:"));
JCheckBox c4=new JCheckBox("图形1",new ImageIcon(".\\icons\\x.jpg"));
JCheckBox c5=new JCheckBox("图形2",new ImageIcon(".\\icons\\x.jpg"));
p2.add(c4);
p2.add(c5);
contentPane.add(p1);
contentPane.add(p2);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}

7-1-2:JCheckBox事件处理:
你可以在上面的选项中勾选你喜欢吃的快餐店,在勾选的过程中,你可以发现它是可以复选的。但在图形选项中,我们并无法
清楚用户是否选择此项目,因为选或不选图形都一样。为解决这个问题,我们要使用到事件处理方法。当JCheckBox中的选项被选取
或取消时,它会触发ItemEvent的事件,ItemEvent这个类共提供了4种方法可以使用,分别是getItem()、getItemSelectable()、
getStateChange()、paramString()。getItem()与paramString()方法会返回一些这个JCheckBox的状态值。一般我们较少用到这两
个方法。
getItemSelectable()相当于getSource()方法,一样都是返回触发事件的组件,用来判断是那个组件产生事件。在上一章中我
们曾经说过,getSource()方法是EventObject类所提供,而所有事件类都会继承这个类,因此所有的事件我们均能用getSource()
方法来判断到底是哪个组件触发了事件。
最后getStateChange()方法会返回此组件到底有没有被选取。这个方法会返回一个整数值。而我们可以用ItemEvent所提供的类
变量;若被选取则返回SELECTED,若没有被选取则返回DESELECTED.
下面这个范例我们即利用ItemListener来选取图形产生变化,ItemListener这个inteface只有定义一个方法,那就是
itemStateChange(ItemEvent e),因此我们只需实作这个方法.


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JCheckBox2 implements ItemListener
{
JFrame f = null;
JCheckBox c4 = null;
JCheckBox c5 = null;

JCheckBox2(){
f = new JFrame("JCheckBox");
Container contentPane = f.getContentPane();
contentPane.setLayout(new GridLayout(2,1));
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(1,3));
p1.setBorder(BorderFactory.createTitledBorder("您最喜欢哪一家速食店呢?"));
JCheckBox c1 = new JCheckBox("麦当劳");
JCheckBox c2 = new JCheckBox("肯德鸡");
JCheckBox c3 = new JCheckBox("21世纪");
p1.add(c1);
p1.add(c2);
p1.add(c3);
JPanel p2 = new JPanel();
p2.setLayout(new GridLayout(2,1));
p2.setBorder(BorderFactory.createTitledBorder("您喜欢哪种程序语言,喜欢的请打勾:"));
c4 = new JCheckBox("JAVA",new ImageIcon(".\\icons\\x.jpg"));
c5 = new JCheckBox("C++",new ImageIcon(".\\icons\\x.jpg"));
c4.addItemListener(this);
c5.addItemListener(this);
p2.add(c4);
p2.add(c5);
contentPane.add(p1);
contentPane.add(p2);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

public void itemStateChanged(ItemEvent e)
{
if (e.getStateChange() == e.SELECTED)
{
if(e.getSource() == c4)
c4.setIcon(new ImageIcon(".\\icons\\r.jpg"));
if(e.getSource() == c5)
c5.setIcon(new ImageIcon(".\\icons\\r.jpg"));

}
else
{
if(e.getSource() == c4)
c4.setIcon(new ImageIcon(".\\icons\\x.jpg"));
if(e.getSource() == c5)
c5.setIcon(new ImageIcon(".\\icons\\x.jpg"));
}
}

public static void main(String args[])
{
new JCheckBox2();
}
}
7-2:JRadioButton的使用:
java.lang.Object
--java.awt.Component
--java.awt.Container
--javax.swing.JComponent
--javax.swing.Abstractbutton
--javax.swing.JToggleButton
--javax.swing.JRadioButton

JRadioButtonBN J JToggleButton的一个了类,因此它也可以使用AbstractButton抽象类里的方法。如同前面所述,JChexkBox
主要用在多重选择时机,而JRadioButton则是运用在单一选择时机。
JRadioButton构造函数:
JRadioButton():建立一个新的JRadioButton.
JRadioButton(Icon icon):建立一个有图像但没有文字的JRadioButton.
JRadioButton(Icon icon,boolean selected):建立一个有图像但没有文字的JRadioButton,且设置其初始状态(有无被选取).
JRadioButton(String text):建立一个有文字的JRadioButton.
JRadioButton(String text,boolean selected):建立一个有文字的JRadioButton,且设置其初始状态(有无被选取)。
JRadioButton(String text,Icon icon):建立一个有文字且有图像的JRadioButton,初始状态为无被选取。
JRadioButton(String text,Icon icon,boolean selected):建立一个有文字且有图像的JRadioButton,且设置其初始状态(有无
被选取。
7-2-1:构造JRadioButton组件与事件处理:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JRadioButton1 implements ItemListener
{
JFrame f = null;
JRadioButton r4 = null;
JRadioButton r5 = null;

JRadioButton1(){
f = new JFrame("JRadioButton");
Container contentPane = f.getContentPane();
contentPane.setLayout(new GridLayout(2,1));
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(1,3));
p1.setBorder(BorderFactory.createTitledBorder("您最喜欢哪一家速食店呢?"));
JRadioButton r1 = new JRadioButton("麦当劳");
JRadioButton r2 = new JRadioButton("肯德鸡");
JRadioButton r3 = new JRadioButton("21世纪");
p1.add(r1);
p1.add(r2);
p1.add(r3);
JPanel p2 = new JPanel();
p2.setLayout(new GridLayout(2,1));
p2.setBorder(BorderFactory.createTitledBorder("您喜欢哪种程序语言? 喜欢的请打勾"));
r4 = new JRadioButton("JAVA",new ImageIcon(".\\icons\\x.jpg"));
r5 = new JRadioButton("C++",new ImageIcon(".\\icons\\x.jpg"));
r4.addItemListener(this);
r5.addItemListener(this);
p2.add(r4);
p2.add(r5);
contentPane.add(p1);
contentPane.add(p2);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

public void itemStateChanged(ItemEvent e)
{
if (e.getStateChange() == e.SELECTED)
{
if(e.getSource() == r4)
r4.setIcon(new ImageIcon(".\\icons\\r.jpg"));
if(e.getSource() == r5)
r5.setIcon(new ImageIcon(".\\icons\\r.jpg"));

}
else
{
if(e.getSource() == r4)
r4.setIcon(new ImageIcon(".\\icons\\x.jpg"));
if(e.getSource() == r5)
r5.setIcon(new ImageIcon(".\\icons\\x.jpg"));
}
}

public static void main(String args[])
{
new JRadioButton1();
}
}
要将RadioButton改成单选,我们必须用到ButtonGroup这个类。这个类位于javax.swing这个package下面,ButtonGroup类的主
要功能是:同一时间内只会有一个组件的状态为"on",其他皆为"off",也就是同一时间只有一个组件会被选取。而ButtonGroup类可
被AbstractButton下面的子类所使用,最常被使用的就是JRadioButton、JradioButtonMenu、Item与JToggleButton这些组件。
下面是ButtonGroup的类层次结构图:
ButtonGroup的类层次结构图:
java.lang.Object
--javax.swing.ButtonGroup
我们更改上例,使RadioButton变成单选吧!

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JRadioButton2 implements ItemListener{
JFrame f=null;
JRadioButton r4=null;
JRadioButton r5=null;

JRadioButton2(){
f=new JFrame("JRadioButton2");
Container contentPane=f.getContentPane();
contentPane.setLayout(new GridLayout(2,1));
JPanel p1=new JPanel();
p1.setLayout(new GridLayout(1,3));
p1.setBorder(BorderFactory.createTitledBorder("你最喜欢哪一家快餐店呢?"));
JRadioButton r1=new JRadioButton("麦当劳");
JRadioButton r2=new JRadioButton("肯德基");
JRadioButton r3=new JRadioButton("21世纪");
p1.add(r1);
p1.add(r2);
p1.add(r3);
/*
将3个RadioButton对象放进ButtonGroup中,表示此3个RadioButton同一时间只有一个RadioButton的状态可以为"on";
*/
ButtonGroup bgroup1=new ButtonGroup();
bgroup1.add(r1);
bgroup1.add(r2);
bgroup1.add(r3);
JPanel p2=new JPanel();
p2.setLayout(new GridLayout(2,1));
p2.setBorder(BorderFactory.createTitledBorder("你最喜欢哪种程序语言,喜欢的请打勾:"));
r4=new JRadioButton("java",new ImageIcon(".\\icons\\x.jpg"));
r5=new JRadioButton("c++",new ImageIcon(".\\icons\\x.jpg"));
r4.addItemListener(this);
r5.addItemListener(this);
p2.add(r4);
p2.add(r5);
ButtonGroup bgroup2=new ButtonGroup();
bgroup2.add(r4);
bgroup2.add(r5);
contentPane.add(p1);
contentPane.add(p2);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public void itemStateChanged(ItemEvent e){
if (e.getStateChange()==e.SELECTED){
if (e.getSource()==r4)
r4.setIcon(new ImageIcon(".\\icons\\r.jpg"));
if (e.getSource()==r5)
r5.setIcon(new ImageIcon(".\\icons\\r.jpg"));
}else{
if (e.getSource()==r4)
r4.setIcon(new ImageIcon(".\\icons\\x.jpg"));
if (e.getSource()==r5)
r5.setIcon(new ImageIcon(".\\icons\\x.jpg"));
}
}
public static void main(String[] args){
new JRadioButton2();
}
}

7-3:JList的使用:
类层次结构图:
java.lang.Object
--java.awt.Component
--java.awt.Container
--javax.swing.JComponent
--javax.swing.JList
JList与JCheckBox有点相似,都可以让你选择一到多个选项,较不同的是,JList的选项方式是整列选取。我们先来看看JList
所提供的构造函数,方便迅速建立JList对象,如下所示:
JList构造函数:
JList():建立一个新的JList组件。
JList(ListModel dataModel):利用ListModel建立一个新的JList组件.
JList(Object[] listData):利用Array对象建立一个新的JList组件。
JList(Vector listData):利用Vector对象建立一个新的JList组件。

7-3-1:建立一般的JList:

一般我们若不需要在JList中加入Icon图像,通常会用第3或第4个构造函数建立JList对象。而这两个最大的不同在于使用Array对
象建立JList组件就无法改变项目的数量。对于项目数量经常改变的环境来说,以Vector对象来建立JList组件当然比较适合。例如
一个卖手机的店家,可能动不动就会有新手机上市,此时若用Array对象就不是很适当了!
我们来看个范例看怎么构造一个简单的JList吧!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Vector;

public class JList1
{
public static void main(String args[])
{
JFrame f = new JFrame("JList");
Container contentPane = f.getContentPane();
contentPane.setLayout(new GridLayout(1,2));
String[] s = {"美国","日本","大陆","英国","法国"};
Vector v = new Vector();
v.addElement("Nokia 8850");
v.addElement("Nokia 8250");
v.addElement("Motorola V8088");
v.addElement("Motorola V3688x");
v.addElement("Panasonic GD92");
v.addElement("其他");

JList list1 = new JList(s);
list1.setBorder(BorderFactory.createTitledBorder("您最喜欢到哪个国家玩呢?"));

JList list2 = new JList(v);
list2.setBorder(BorderFactory.createTitledBorder("您最喜欢哪一种手机?"));

contentPane.add(new JScrollPane(list1));
contentPane.add(new JScrollPane(list2));
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
在这个范例中,当窗口变小时,JList并不会有滚动(ScrollBar)的效果,所以可能无法看到比较下面的选项。若我们要有滚动的
效果,必须将JList放入滚动面版中(JScrollPane),如我们在程序改为:
contentPane.add(new JScrollPane(list1));
contentPane.add(new JScrollPane(list2));
如此就有滚动的效果了,若我们要有多个选项呢?在JList中有3种选择模式(Selection Mode)可供我们使用,分别是单一选择、
连续区间选择、与多重选择。我们可以在ListSelectionModel这个interface中找到这3个常数值,如下:
static int SINGLE_SELECTION:一次只能选择一个项目。
static int SINGLE_INTERVAL_SELECTION:按住[shift]键,可以对某一边续的项目作选取。
static int MULTIPLE_INTERVAL_SELECTION:没有任何限制。可作单一选择,连续区间选择,或对不连续的项目作多重选择(按
住[Ctrl]键)。多得选择是java对JList的默认值,因此在上例中你可以在JList中作这3种模式的选择方式。

设置选择模式可以利用JList所提供的setSelectionMode(int selectionMode)方法。例如,若我们将上例改成如下:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Vector;

public class JList2
{
public static void main(String args[])
{
JFrame f = new JFrame("JList");
Container contentPane = f.getContentPane();
contentPane.setLayout(new GridLayout(1,3));
String[] s1 = {"美国","日本","大陆","英国","法国","意大利","澳洲","韩国"};
String[] s2 = {"范志毅","符兵","周宁","杨晨","高锋","南方","其他"};
Vector v = new Vector();
v.addElement("Nokia 3310");
v.addElement("Nokia 8850");
v.addElement("Nokia 8250");
v.addElement("Motorola V8088");
v.addElement("Motorola V3688x");
v.addElement("Panasonic GD92");
v.addElement("Panasonic GD93");
v.addElement("NEC DB2100");
v.addElement("Alcatel OT500");
v.addElement("Philips Xenium 9@9 ");
v.addElement("Ericsson T29sc");
v.addElement("其他");

JList list1 = new JList(s1);
list1.setBorder(BorderFactory.createTitledBorder("您最喜欢到哪个国家玩呢?"));

JList list2 = new JList(s2);
list2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list2.setBorder(BorderFactory.createTitledBorder("您最喜欢哪个运动员呢?"));

JList list3 = new JList(v);
list3.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list3.setBorder(BorderFactory.createTitledBorder("您最喜欢哪一种手机?"));

contentPane.add(new JScrollPane(list1));
contentPane.add(new JScrollPane(list2));
contentPane.add(new JScrollPane(list3));
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}

7-3-2:利用ListModel构造JList:
ListModel是一个interface,主要的功能是定义一些方法,让JList或JComboBox这些组件取得每个项目的值,并可限定项目的显示
时机与方式,下面为ListModel这个interface所定义的方法:
ListModel interface定义的方法:
void addListDataListener(ListDataListener l):当data model的长度或内容值有任何改变时,利用此
方法就可以处理ListDataListener的事件。data model是vector或array的数据类型,里面存放List
中的值。
Object getElementAt(int index):返回在index位置的Item值。
int getSize():返回List的长度。
void removeListDataListener(ListDataListener l):删除ListDataListener.
还记得我们一开始在介绍JList时所提到的构造函数吗?其中有一个JList的构造函数是这样的:
JList(ListModel dataModel)
因此我们必须实作ListModel所有的方法,才能利用上面这个构造函数建立JList.不过要实现ListModel所有的方法有点麻烦,因
为一般我们不会用到addListDataListener()与removeListDataListener()这两个方法。因此java提供了AbstractListModel这个抽
象类,此抽象类实作了addListDataListener()与removeListDataListener()这两个方法。若我们继承AbstractListModel,就不需
实现这两个方法,只需要实作getElementAt()与getSize()方法即可,我们来看下面的范例:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JList3{
public JList3(){
JFrame f=new JFrame("JList");
Container contentPane=f.getContentPane();
/*由于我们在DataModelodel类中继承AbstractListModel,并实作了getElementAt()与getSize()方法,因此
*我们可以由DataModel类产生一个ListModel的实体来。
*/
ListModel mode=new DataModel();
JList list=new JList(mode);//利用ListModel建立一个JList.
list.setVisibleRowCount(5);//设置程序一打开时所能看到的数据项个数。
list.setBorder(BorderFactory.createTitledBorder("你最喜欢到哪个国家玩呢?"));

contentPane.add(new JScrollPane(list));
f.pack();
/*当程序要show出list时,系统会先自动调用getSize()方法,看看这个list长度有多少;然后再调 用setVisibleRowCount()方
法,看要一次输出几笔数据;最后调用getElementAt()方法,将list中的项目值(item)填入list中。读者若还不太清楚,可直接
在getSize()与getElementAt()方法中个别加入System.out.println("size");与System.out.println("element")叙述,就可以
在dos console清楚看出整个显示list调用的过程。
*/
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String[] args){
new JList3();
}
}
/*由于我们在下面程序中继承AbstractListModel抽象类,因此我们分别在下面程序中实现了getElementAt()与getSize()方法。
*/
class DataModel extends AbstractListModel{
String[] s={"美国","越南","大陆","英国","法国","大陆","意大利","澳洲"};
public Object getElementAt(int index){//getxElementAt()方法中的参数index,系统会自动由0开始计算,不过要自己作累加
//的操作.
return (index+1)+"."+s[index++];
}
public int getSize(){
return s.length;
}
}

事实上,java本身还提供另一个类,DefaultListModel实体类。此类继承了AbstractListModel抽象类,并实现里面所有的抽象方
法,因此你不需要再自行实作任何的方法,可以说是相当的方便。不过既然所有的抽象都已经被实现,因此在设计的弹性上就会有
有所降低。若你是喜欢自行管理JList项目的设计者,你可以不要使用DefaultListModel这个类,只需要在AbstractListModel上多
下功夫即可。
下面的例子我们改写上面的例子,直接使用DefaultListModel类:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Vector;

public class JList4
{
public JList4()
{
JFrame f = new JFrame("JList");
Container contentPane = f.getContentPane();

ListModel mode = new DataModel();
JList list = new JList(mode);
list.setVisibleRowCount(5);
list.setBorder(BorderFactory.createTitledBorder("您最喜欢到哪个国家玩呢?"));

contentPane.add(new JScrollPane(list));
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

public static void main(String args[])
{
new JList4();
}
}
/*使DataModel继承DefaultListModel实体类,因此就不需要再实作getSize()与getElementAt()两个方法,
*直接将所要的项目用addElementAt()方法加入即可。系统会自动将所加入的项目放入一个Vector对象中,
*并在输出JList时自动调用getSize()与getElementAt()方法。你可以在DefaultListModel类中找到getSize()与
*getElementAt()两个方法,你可以发现这两个方法已经被实作,不再是抽象方法了。
*/
class DataModel extends DefaultListModel
{
String[] s = {"美国"," 日本","大陆","英国","法国","意大利","澳洲","韩国"};

DataModel()
{
for(int i=0; i < s.length; i++)
addElement((i+1)+"."+s[i]);
}
}

程序运行结果与上个范例相同。
好奇怪,这不是跟我们使用Vector方式,利用JList(Vector v)构造函数来建立新的JList一样吗?如同JList1.java中的例子,为
什么还要多此一举呢?其实若读者去查看DefaultListModel类,可发现此类提供不少好用的方法,例如你可以随意的增加一个项目(
addElement())、或是删除一个项目(removeElement)、甚至你可以很方便地做到查询(getElementAt())与汇出(copyInto())项目的
操作。你可以发现,利用DefaultListModel可以直接动态地更改JList的项目值,而不需要自行产生一个Vecotr对象;相对于JList(
Vector v)这个构造函数,可说更方便且实用许多.
至于利用ListModel或AbstractListModel来构造JList有什么好处?读者只要这么想,ListModel中文就是“列出模式”,那么每
个老师都会有自己开课的学生成绩,老师应该可以看到每个同学的成绩,而深长应该只能看到自己的成绩,所以我们就会有两种不
同的“列出模式”。我们只需要去改写getElementAt()方法,就会有不同的列出模式产生,如下面的范例:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Vector;

public class JList5
{
public JList5()
{
JFrame f = new JFrame("JList");
Container contentPane = f.getContentPane();
contentPane.setLayout(new GridLayout(1,2));
ListModel mode = new DataModel(1);
JList list1 = new JList(mode);
list1.setVisibleRowCount(5);
list1.setBorder(BorderFactory.createTitledBorder("您玩过哪些软件?"));

mode = new DataModel(2);
JList list2 = new JList(mode);
list2.setBorder(BorderFactory.createTitledBorder("您玩过哪些数据库软件?"));

contentPane.add(new JScrollPane(list1));
contentPane.add(new JScrollPane(list2));
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

public static void main(String args[])
{
new JList5();
}
}

class DataModel extends AbstractListModel
{
String[] s = {"MS SQL","MySQL","IBM DB2","ORACLE","Windows 2000","Linux","UNix","OS2"};
int flag;

DataModel(int flag)
{
this.flag = flag;
}
public Object getElementAt(int index)
{
String tmp = null;

if (flag == 1)
tmp = (index+1)+"."+s[index++];
if (flag == 2)
{
if(index < 4)
tmp = (index+1)+"."+s[index++];
}

return tmp;
}

public int getSize()
{
return s.length;
}
}



7-3-3:建立有图像的JList:
我们也可以在JList中加入Icon图像,不过JList加入图像比较麻烦一点,不像JLabel或JButton那样简单。要在JList上加入Icon,
要先了解ListCellRenderer interface.我们必须由这个interface所定义的方法,将图像画在JList中的每个项目。
ListCellRenderer interface里只定义了一个方法,那就是getListCellRendererComponent,不过这个参数有点多,我们把它列出来
看看:
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
list:即所要画上的图像的JList组件。
value:JList项目值,如list.getModel().getElementAt(index)所返回的值。
index:为JList项目的索引值,由0开始。
isSelected与cellHasFocus:判断JList中的项目是否有被选取或是有焦点置入。
上面这4个参数会在你设置JList的绘图样式(setCellRenderer())时自动的由JList组件提供,你只要关心怎么控制
getListCellRendererComponent()方法中的4个参数,而无需担心怎么参数传入。
要在JList中加入Icon图像的技巧就是将JList中的每一个项目当作是JLabel,因为JLabel在使用文字与图像上非常的方便,要设置
JList的图像,必须使用setCellRenderer(ListCellRenderer cellRenderer)这个方法。我们来看下面这个范例,你就能明白了!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Vector;

public class JList6
{
public JList6()
{
String[] s = {"西瓜","苹果","草莓","香蕉","葡萄"};
JFrame f = new JFrame("JList");
Container contentPane = f.getContentPane();
JList list1 = new JList(s);
list1.setBorder(BorderFactory.createTitledBorder("您喜欢吃哪些水果?"));
/*设置在JList中画上图像。在此参数中,我们产生一个CellRenderer对象,此对象实作了ListCellRenderer interface,
*因此可以返回一个ListCellRenderer对象当作setCellRenderer()方法的参数.
*/
list1.setCellRenderer(new CellRenderer());

contentPane.add(new JScrollPane(list1));
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

public static void main(String args[])
{
new JList6();
}
}

class CellRenderer extends JLabel implements ListCellRenderer
{
/*类CellRenderer继承JLabel并实作ListCellRenderer.由于我们利用JLabel易于插图的特性,因此CellRenderer继承了JLabel
*可让JList中的每个项目都视为是一个JLabel.
*/
CellRenderer()
{
setOpaque(true);
}
/*从这里到结束:实作getListCellRendererComponent()方法*/
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
/*我们判断list.getModel().getElementAt(index)所返回的值是否为null,例如上个例子中,若JList的标题是"你玩过哪
*些数据库软件",则index>=4的项目值我们全都设为null.而在这个例子中,因为不会有null值,因此有没有加上这个判
*断并没有关系.
*/
if (value != null)
{
setText(value.toString());
setIcon(new ImageIcon(".\\icons\\fruit"+(index+1)+".jpg"));
}
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
}
else {
//设置选取与取消选取的前景与背景颜色.
setBackground(list.getBackground());
setForeground(list.getForeground());
}
return this;
}
}

7-3-4:JList的事件处理:
JList的事件处理一般可分为两种:一种是取得用户选取的项目;另一种是在JList的项目上双击鼠标两次,运行相对应的工作。我
们先来看第一种事件处理方式:
在JList类中有addListSelectionListener()方法,可以检测用户是否对JList的选取有任何的改变。ListSelectionListener
interface中只有定义一个方法,那就是valueChanged(ListSelectionEvent e),我们必须实作这个方法,才能在用户改变选取值时
取得用户最后的选取状态。我们来看一下的例子: 这个例子匀们抓取用户所选取的项目,并将所选的项目显示在JLabel上。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;//由于ListSelectionEvent是swing的事件,不是awt的事件,因此我们必须import
//javax.swing.event.*。

public class JList7 implements ListSelectionListener
{
JList list = null;
JLabel label = null;
String[] s = {"美国","日本","大陆","英国","法国","意大利","澳洲","韩国"};

public JList7()
{
JFrame f = new JFrame("JList");
Container contentPane = f.getContentPane();
contentPane.setLayout(new BorderLayout());
label = new JLabel();

list = new JList(s);
list.setVisibleRowCount(5);
list.setBorder(BorderFactory.createTitledBorder("您最喜欢到哪个国家玩呢?"));
list.addListSelectionListener(this);

contentPane.add(label,BorderLayout.NORTH);
contentPane.add(new JScrollPane(list),BorderLayout.CENTER);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

public static void main(String args[])
{
new JList7();
}

public void valueChanged(ListSelectionEvent e)
{
int tmp = 0;
String stmp = "您目前选取:";
int[] index = list.getSelectedIndices();//利用JList类所提供的getSelectedIndices()方法可得到用户所选取的所有
for(int i=0; i < index.length ; i++)//index值,这些index值由一个int array返回.
{
tmp = index[i];
stmp = stmp+s[tmp]+" ";
}
label.setText(stmp);
}
}

接下来,我们来看如何处理在JList上双击鼠标的操作。由于JList本身并无提供这样的EventListener,因此我们必须利用
MouseListener来达到捕获双击鼠标的事件。至于要怎么知道我们到底在哪个项目上双击鼠标呢?我们可以利用JList类所提供的
LocatToindex()方法得知。以下为我们所举的范例:
这个例子一开始左边列有国这名称,当你在某个国家名称上双击鼠标,这个国家名称就会移到右边去,反之亦同。
1.这个范例我们应用DefaultListModel类,因主DefaultListModel类实作了Vector中的方法,使我们在处理动态的JList项目值
比较容易.
2.由于我们要处理鼠标事件,为了编写方便,在程序中我们继承MouseAdapte抽象类.
3.在程序中,我们建立两个DataModel,第一个JList,也就是list1一开始时会将String Array s中的所有值依次放入list1的项
目中,而list2一开始为空白。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class JList8 extends MouseAdapter{
JList list1=null;
JList list2=null;
DefaultListModel mode1=null;
DefaultListModel mode2=null;
String[] s = {"美国","日本","大陆","英国","法国","意大利","澳洲","韩国"};

public JList8(){
JFrame f=new JFrame("JList");
Container contentPane=f.getContentPane();
contentPane.setLayout(new GridLayout(1,2));

mode1=new DataModel(1);
list1=new JList(mode1);
list1.setBorder(BorderFactory.createTitledBorder("国家名称!"));
list1.addMouseListener(this);//一遇到鼠标事件立即执行.

mode2=new DataModel(2);
list2=new JList(mode2);
list2.setBorder(BorderFactory.createTitledBorder("你最喜欢到哪个国家玩呢!"));
list2.addMouseListener(this);//一遇到鼠标事件立即执行.

contentPane.add(new JScrollPane(list1));
contentPane.add(new JScrollPane(list2));
f.pack();
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String[] args){
new JList8();
}
//处理鼠标键击事件.
public void mouseClicked(MouseEvent e){
int index;
/*对list1而言,当鼠标在某个项目连续按两下时,我们利用JList所提供的locationToIndex()方法,找到所键击的项目,并
*由tmp取得此项目的项目值,然后将此项目值增加到mode2中[mode2.addElement(tmp)],用setModel重新设置list2的
*ListModel,使list2可显示出所增加的项目,将刚刚在list1双击的项目删除.
*/
if (e.getSource()==list1){
if (e.getClickCount()==2){
index=list1.locationToIndex(e.getPoint());
String tmp=(String)mode1.getElementAt(index);
mode2 .addElement(tmp);
list2.setModel(mode2);
mode1.removeElementAt(index);
list1.setModel(mode1);
}
}
if (e.getSource()==list2){
if (e.getClickCount()==2){
index=list2.locationToIndex(e.getPoint());
String tmp=(String)mode2.getElementAt(index);
mode1 .addElement(tmp);
list1.setModel(mode1);
mode2.removeElementAt(index);
list2.setModel(mode2);
}
}
}
class DataModel extends DefaultListModel{
DataModel(int flag){
if (flag==1){
for (int i=0;i < s.length;i++) addElement(s[i]);
}
}
}
}

7-4:JComboBox的使用:
类层次结构图:
java.lang.Object
--java.awt.Component
--java.awt.Container
--javax.swing.JComponent
--javax.swing.JComboBox
构造函数:
JComboBox():建立一个新的JComboBox组件。
JComboBox(ComboBoxModel aModel):用ListModel建立一个新的JComboBox组件。
JComboBox(Object[] items):利用Array对象建立一个新的JComboBox组件。
JComboBox(Vector items):利用Vector对象建立一个新的JComboBox组件。
7-4-1:建立一般的JComboBox:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Vector;

public class JComboBox1{
public static void main(String[] args){
JFrame f=new JFrame("JComboBox1");
Container contentPane=f.getContentPane();
contentPane.setLayout(new GridLayout(1,2));
String[] s = {"美国","日本","大陆","英国","法国","意大利","澳洲","韩国"};
Vector v=new Vector();
v.addElement("Nokia 8850");
v.addElement("Nokia 8250");
v.addElement("Motorola v8088");
v.addElement("Motorola v3850");
v.addElement("Panasonic 8850");
v.addElement("其它");

JComboBox combo1=new JComboBox(s);
combo1.addItem("中国");//利用JComboBox类所提供的addItem()方法,加入一个项目到此JComboBox中。
combo1.setBorder(BorderFactory.createTitledBorder("你最喜欢到哪个国家玩呢?"));
JComboBox combo2=new JComboBox(v);
combo2.setBorder(BorderFactory.createTitledBorder("你最喜欢哪一种手机呢?"));
contentPane.add(combo1);
contentPane.add(combo2);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
7-4-2:利用ComboModel构造JComboBox:
如同JList一般,在JComboBox中也有一个构造函数是利用某种Model来构造。如下所示:
JComboBox(COmboBoxModel aModel)
ComboBoxModel是一个interface,里面定义了两个方法,分别是setSelectedItem()与getSelectedItem().这两个方法目的是让用
户选取某个项目后,可正确地显示出用户所选取的项目。下面是这两个方法的详细定义:
ComboBoxModel interface定义的方法:
Object getSelectedItem():返回所选取的项目值。
Void setSelectedItem(Object anItem):设置所选取的项目值.

与JList不同的是,JComboBox是利用ComboBoxModel,而不是ListModel.不过ComboBoxModel interface是继承ListModel interface,因此若我们要利用ComboBoxModel来构造JComboBox,除了要实作ComboBoxModel的两个方法外,还必须实作ListModel的所定义的4个方法,这样的做法可说相当麻烦。
在介绍JList时我们曾经提到AbstractListModel这个抽象类。这个抽象类实作了ListModel interface中的addListDataListener()、removeListDataListener()这两个方法。因此若我们继承AbstractListModel,则可少掉实作这两个方法,只需要实作getElementAt()、getSize()、setSelectedItem()与getSelectedItem()这4个方法。这样的作法就显得比较简单一点.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JComboBox2{
String[] s= {"美国","日本","大陆","英国","法国","意大利","澳洲","韩国"};
public JComboBox2(){
JFrame f=new JFrame("JComboBox2");
Container contentPane=f.getContentPane();

ComboBoxModel mode=new UserDefineComboBoxModel();
JComboBox combo=new JComboBox(mode);
combo.setBorder(BorderFactory.createTitledBorder("你最喜欢到哪个国家去玩?"));
contentPane.add(combo);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String[] args){
new JComboBox2();
}

class UserDefineComboBoxModel extends AbstractListModel implements ComboBoxModel{
String item=null;
public Object getElementAt(int index){
return s[index++];
}
//由于继承AbstractListModel抽象类。因此我们分别在程序中实作了getElementAt()与getSize()方法。
public int getSize(){
return s.length;
}
//由于我们实现了ComboBoxModel interface.因此我们必须在程序中实作setSelectedItem()与getSelectedItem()方法.
public void setSelectedItem(Object anItem){
item=(String)anItem;
}
public Object getSelectedItem(){
return item;
}
}
}
当程序要show出JComboBox时,系统会先自动调用getSize()方法,看看这个JComboBox长度有多少,然后再调用getElementAt()
方法,将String Array s中的值填入JComboBox中。当用户选择项目时,系统会调用getSelectedItem()方法,返回所选取的项目,并
利用setSelectedItem()方法,将选取项目放在JComboBox最前端。
getElementAt()方法中的“index”参数,系统会自动由0计算,不过要自己作累加的操作,如程序中:
return s[index++];
如同JList一般,java对于JComboBox也提供了另一个类,DefaultComboBoxModel实体类。此类继承了AbstractListModel抽象类,也
实作了ComboBoxModel interface.因此你不需要再实作getSize()、getElementAt()、setSelectedItem()与getSelectedItem()方法。
利用DefaultComboBoxModel这个类我们可以很方便地做到动态更改JComboBox的项目值。当你没有必要自己定义特殊的ComboBoxModel
时,使用DefaultComboBoxModel就显得非常的方便,我们来看下面的例子:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JComboBox3{
String[] s = {"美国","日本","大陆","英国","法国","意大利","澳洲","韩国"};
public JComboBox3(){
JFrame f=new JFrame("JComboBox3");
Container contentPane=f.getContentPane();

ComboBoxModel mode=new AModel();
JComboBox combo=new JComboBox(mode);
combo.setBorder(BorderFactory.createTitledBorder("您最喜欢到哪个国家玩呢?"));
contentPane.add(combo);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String[] args){
new JComboBox3();
}
class AModel extends DefaultComboBoxModel{
AModel(){
for (int i=0;i addElement(s[i]);
}
}
}
1.由于AModel继承DefaultComboBoxModel实体类,由AModel可得到一个ComboBoxModel实体对象。
2.我们使AModel继承DefaultComboBoxModel实体类,因此就不需要再实作getElementAt()、getSize()、setSelectedItem()与 getSelectedItem()这4个方法,直接将所要的项目用addElement()方法加入即可。系统会自动将所加入的项目放进一个Vector中,并在输出JComboBox时自动调用getSize()与getElementAt()方法。
7-4-3:建立有图像的JComboBox:
在上一节中我们利用ListCellRenderer interface在JList中加入Icon图像,而要在JComboBox中加入图像的方法也是一样的。我们必须实作ListCellRenderer interface所定义的方法getListCellRendererComponent.以下为这个方法的定义:要先了解ListCellRenderer interface.我们必须由这个interface所定义的方法,将图像画在JComboBox中的每个项目。ListCellRenderer interface里只定义了一个方法,那就是getListCellRendererComponent,不过这个参数有点多,我们把它列出来看看:
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
list:即所要画上的图像的JComboBox组件。
value:JComboBox项目值,如JComboBox.getModel().getElementAt(index)所返回的值。
index:为JComboBox项目的索引值,由0开始。
isSelected与cellHasFocus:判断JComboBox中的项目是否有被选取或是有焦点置入。
上面这4个参数会在你设置JComboBox的绘图样式(setCellRenderer())时自动的由JComboBox组件提供,你只要关心怎么控制getListCellRendererComponent()方法中的4个参数,而无需担心怎么参数传入。
要在JList中加入Icon图像的技巧就是将JComboBox中的每一个项目当作是JLabel,因为JLabel在使用文字与图像上非常的方便,要设置JComboBox的图像,
必须使用setRenderer(ListCellRenderer cellRenderer){注:我们在JList中画上图像是利用JList所提供的setCellRenderer(ListCellRenderer
cellRenderer)方法,读者请小心}这个方法。我们来看下面这个范例,你就能明白了!

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JComboBox4{
String[] s={"西瓜","苹果","草莓","香蕉","葡萄"};
public JComboBox4(){
JFrame f=new JFrame("JComboBox");
Container contentPane=f.getContentPane();

JComboBox combo=new JComboBox(s);
combo.setBorder(BorderFactory.createTitledBorder("你最喜欢吃哪些水果?"));
combo.setRenderer(new ACellRenderer());
combo.setMaximumRowCount(3);

contentPane.add(combo);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String[] args){
new JComboBox4();
}
}
class ACellRenderer extends JLabel implements ListCellRenderer{
ACellRenderer(){
setOpaque(true);
}
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus){
if (value!=null){
setText(value.toString());
setIcon(new ImageIcon(".\\icons\\fruit"+(index+1)+".jpg"));
}
if (isSelected){
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
}else{
setBackground(list.getBackground());
setForeground(list.getForeground());
}
return this;
}
}
各们读者在运行这个程序时会发现,即使JComboBox的选项中有图标,但在选后图标却不会显示在显示列中,原因是在上面程序中
我们以String Array s建立JComboBox:
JComboBox combo=new JComboBox(s);
String Array s里面放的只是水果名称,而并没有图标。当我们使用setRenderer()方法来JComboBox时,只会绘制JComboBox的
选项部份,而最后显示在JComboBox上的值还是以String Array s为依据。因此JComboBox显示列就只会显示文字而已,而不会显示出
图形。要解决这个问题,我们必须改变JComboBox所传入的参数内容,也就是将原来的String Array s更改成具有图形的数据项。在
此我们是利用JComboBox(Object[] items)来建立有图像的JComboBox,我们所传进去的Object Array不应该只有文字,而必须连图标一并传入。我们修改上个范例修改如下:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JComboBox5
{
String[] s = {"西瓜","苹果","草莓","香蕉","葡萄"};
ImageIcon[] icons = new ImageIcon[5];;

public JComboBox5()
{
JFrame f = new JFrame("JComboBox");
Container contentPane = f.getContentPane();
ItemObj[] obj = new ItemObj[5];

for(int i=0; i < 5; i++)
{
icons[i] = new ImageIcon(".\\icons\\fruit"+(i+1)+".jpg");
obj[i] = new ItemObj(s[i],icons[i]);
}

JComboBox combo = new JComboBox(obj);//利用ItemObj Array obj当作是JComboBox的参数传入,构造出JComboBox.
combo.setBorder(BorderFactory.createTitledBorder("您喜欢吃哪些水果?"));
combo.setRenderer(new ACellRenderer());
combo.setMaximumRowCount(3);

contentPane.add(combo);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

public static void main(String args[])
{
new JComboBox5();
}
}

class ItemObj
{
String name;
ImageIcon icon;

public ItemObj(String name, ImageIcon icon){
this.name = name;
this.icon = icon;
}
}

class ACellRenderer extends JLabel implements ListCellRenderer
{
ACellRenderer()
{
setOpaque(true);
}

public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
if (value != null)
{
setText(((ItemObj)value).name);
setIcon(((ItemObj)value).icon);
}

if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
}
else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}

return this;
}
}

你可以发现,第一栏显示有图标显示出来了。当然你也可以利用ComboBoxModel方式来构造出有图标的JComboBox.我们来看下面
的例子:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JComboBox6{
String[] s={"西瓜","苹果","草莓","香蕉","葡萄"};
ImageIcon[] icons=new ImageIcon[5];
public JComboBox6(){
JFrame f=new JFrame("JComboBox");
Container contentPane=f.getContentPane();
for(int i=0; i < 5; i++)
{
icons[i] = new ImageIcon(".\\icons\\fruit"+(i+1)+".jpg");
}
ComboBoxModel mode=new AModel();
JComboBox combo=new JComboBox(mode);
combo.setBorder(BorderFactory.createTitledBorder("您喜欢吃哪些水果?"));
combo.setRenderer(new ACellRenderer());
combo.setMaximumRowCount(3);

contentPane.add(combo);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args){
new JComboBox6();
}
/*我们用JComboBox(ComboBoxModel aModel)来构造图标的JComboBox,因此我们在程序中编写一个继承DefaultComboBoxModel的
ComboBoxModel.
*/
class AModel extends DefaultComboBoxModel{
AModel(){
for (int i=0;i ItemObj obj=new ItemObj(s[i],icons[i]);
addElement(obj);
}
}
}
}
class ItemObj
{
String name;
ImageIcon icon;

public ItemObj(String name, ImageIcon icon){
this.name = name;
this.icon = icon;
}
}

class ACellRenderer extends JLabel implements ListCellRenderer
{
ACellRenderer()
{
setOpaque(true);
}

public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
if (value != null)
{
setText(((ItemObj)value).name);
setIcon(((ItemObj)value).icon);
}

if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
}
else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}

return this;
}
}

我们用JComboBox(ComboBoxModel aModel)来构造图标的JComboBox,因此我们在程序中编写一个继承DefaultComboBoxModel的
ComboBoxModel.

7-4-4:建立可自行输入的JComboBox:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JComboBox7
{
String[] fontsize = {"12","14","16","18","20","22","24","26","28"};
String defaultMessage = "请选择或直接输入文字大小!";

public JComboBox7()
{
JFrame f = new JFrame("JComboBox");
Container contentPane = f.getContentPane();

JComboBox combo = new JComboBox(fontsize);
combo.setBorder(BorderFactory.createTitledBorder("请选择你要的文字大小"));
combo.setEditable(true);//将JComboBox设成是可编辑的.
ComboBoxEditor editor = combo.getEditor();//getEditor()方法返回ComboBoxEditor对象,如果你查看手册,你就会发现ComboBoxEditor是个接口(interface),因此你可以自行实作这个接口,制作自己想要的ComboBoxEditor组件。但通常我们不需要这么做,因为默认的ComboBoxEditor是使用JTextField,这已经足够应付大部份的情况了。
//configureEditor()方法会初始化JComboBox的显示项目。例如例子中一开始就出现:"请选择或直接输入文字大小!"这个字符串。
combo.configureEditor(editor, defaultMessage);


contentPane.add(combo);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

public static void main(String args[])
{
new JComboBox7();
}
}


7-4-5:JComboBox的事件处理:
JComboBox的事件处理亦可分为两种,一种是取得用户选取的项目;另一种是用户在JComboBox上自行输入完毕后按下[Enter]键,运作相对应的工作。对于第一种事件的处理,我们使用ItemListener.对于第二种事件的处理,我们使用ActionListener.这个范例用户可以选取所要的字号,字号的变化会呈现在JLabel上,并可让用户自行输入字体的大小。当用户按下[Enter]键后,若用户输入的值不在选项上时,此输入值会增加至JComboBox中,并将输入字体的大小显示在JLabel上。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JComboBox8 implements ItemListener,ActionListener{
String[] fontsize={"12","14","16","18","20","22","24","26","28"};
String defaultMessage="请选择或直接输入文字大小!";
Font font=null;
JComboBox combo=null;
JLabel label=null;

public JComboBox8(){
JFrame f=new JFrame("JComboBox");
Container contentPane=f.getContentPane();
contentPane.setLayout(new GridLayout(2,1));
label=new JLabel("Swing",JLabel.CENTER);
font=new Font("SansSerif",Font.PLAIN,12);
label.setFont(font);

combo=new JComboBox(fontsize);
combo.setBorder(BorderFactory.createTitledBorder("请选择你要的文字大小:"));
combo.setEditable(true);
ComboBoxEditor editor=combo.getEditor();
combo.configureEditor(editor,defaultMessage);
combo.addItemListener(this);0
combo.addActionListener(this);

contentPane.add(label);
contentPane.add(combo);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String[] args){
new JComboBox8();
}
public void actionPerformed(ActionEvent e){
boolean isaddItem=true;
int fontsize=0;
String tmp=(String)combo.getSelectedItem();
//判断用户所输入的项目是否有重复,若有重复则不增加到JComboBox中。
try{
fontsize=Integer.parseInt(tmp);
for(int i=0;i if (combo.getItemAt(i).equals(tmp)){
isaddItem=false;
break;
}
}
if (isaddItem){
combo.insertItemAt(tmp,0);//插入项目tmp到0索引位置(第一列中).
}
font=new Font("SansSerif",Font.PLAIN,fontsize);
label.setFont(font);
}catch(NumberFormatException ne){
combo.getEditor().setItem("你输入的值不是整数值,请重新输入!");
}
}
public void itemStateChanged(ItemEvent e){//ItemListener界面只有itemStateChanged()一个方法,在此实作它。
if (e.getStateChange()==ItemEvent.SELECTED){//当用户的选择改变时,则在JLabel上会显示出Swing目前字形大小信息.
int fontsize=0;
try{
fontsize=Integer.parseInt((String)e.getItem());
label.setText("Swing 目前字形大小:"+fontsize);
}catch(NumberFormatException ne){//若所输入的值不是整数,则不作任何的操作.

}
}
}
}

菜单与工具栏的使用与介绍

使用JMenuBar组件:
JMenuBar的类层次结构图:
java.lang.Object
--java.awt.Component
--java.awt.Container
--javax.swing.JComponent
--javax.swing.JMenuBar
在介绍JMenu组件前,我们先介绍JMenuBar组件,JMenuBar组件的功能是用来摆入JMenu组件.当我们建立完许多的JMenu组件后, 需要通过JMenuBar组件来将JMenu组件加入到窗口中.虽然我们由下表中看出JMenuBar组件只有一种构造方式,但是它对于构造一个菜单来说是个不可缺少的组件.
JMenuBar构造函数:
JMenuBar():建立一个新的JMenuBar;
由于构造一个空的JMenuBar然后设置到窗口上对于窗口来说是没有意义的,因此JMenuBar需要结合至少一个以上的JMenu组件才会在画面上显现出视觉的效果,所以JMenuBar的构造方法及范例我们留到JMenu的第一个范例中再加以说明.

12-1:使用JMenu组件:
JMenu的类层次结构图:
java.lang.Object
--java.awt.Component
--java.awt.Container
--javax.swing.JComponent
--javax.swing.AbstractButton
--javax.swing.JMenuItem
--javax.swing.JMenu
JMenu组件是用来存放和整合JMenuItem的组件,这个组件也是在构成一个菜单中不可或缺的组件之一.JMenu可以是单一层次的结构也可以是一个层次式的结构,要使用何种形式的结构取决于界面设计上的需要而定,如下表所示:
JMenu构造函数:
JMenu():建立一个新的JMenu.
JMenu(Action a):建立一个支持Action的新的JMenu.
JMenu(String s):以指定的字符串名称建立一个新的JMenu.
JMenu(String,Boolean b):以指定的字符串名称建立一个新的JMenu并决定这个菜单是否可以下拉式的属性.

12-1-2:构造JMenu组件:
在看过JMenu的构造函数之后,我们先来看一个具有图标菜单的范例:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import com.incors.plaf.alloy.*;
import com.incors.plaf.alloy.themes.glass.*;

public class JMenu1 extends JFrame{

JTextArea theArea = null;

public JMenu1(){

super("JMenu1");
theArea = new JTextArea();
theArea.setEditable(false);
getContentPane().add(new JScrollPane(theArea));
JMenuBar MBar = new JMenuBar();
//调用自行编写的buildFileMenu()方法来构造JMenu.
JMenu mfile = buildFileMenu();

MBar.add(mfile); //将JMenu加入JMenuBar中.
setJMenuBar(MBar);//将JMenuBar设置到窗口中.
}//end of JMenu1()

public JMenu buildFileMenu() {

JMenu thefile = new JMenu("File");
thefile.setIcon(new ImageIcon("icons/file.gif"));
return thefile;
}//end of buildFileMenu()


public static void main(String[] args){
SwingUtil.setLookAndFeel();
JFrame F = new JMenu1();
F.setSize(400,200);
F.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});//end of addWindowListener

F.setVisible(true);
} // end of main
}//end of class JMenu1
class SwingUtil{
public static final void setLookAndFeel() {
try{
Font font = new Font("JFrame", Font.PLAIN, 12);
Enumeration keys = UIManager.getLookAndFeelDefaults().keys();

while (keys.hasMoreElements()) {
Object key = keys.nextElement();
if (UIManager.get(key) instanceof Font) {
UIManager.put(key, font);
}
}
AlloyLookAndFeel.setProperty("alloy.isLookAndFeelFrameDecoration", "true");
AlloyTheme theme = new GlassTheme();
LookAndFeel alloyLnF = new AlloyLookAndFeel(theme);
UIManager.setLookAndFeel(alloyLnF);
}catch(UnsupportedLookAndFeelException ex){
ex.printStackTrace();
}
}
}

12-3:使用JMenuItem组件:
JMenuItem组件的类层次结构图:

java.lang.Object
--java.awt.Component
--java.awt.Container
--javax.swing.JComponent
--javax.swing.AbstractButton
--javax.swing.JMenuItem
JMenuItem继承AbstractButton类,因此JMenuItem具有许多AbstractButton的特性,也可以说JMenuItem是一种特殊的Button,所以JMenuItem支持许多在Button中好用的功能,例如加入图标文件或是当我们在菜单中选择某一项JMenuItem时就如同按下按钮的操作一样触发ActionEvent,通过ActionEvent的机制我们就能针对不同的JMenuItem编写其对应的程序区段,我们来看看JMenuItem的构造
方式有哪些:

JMenuItem构造函数:
JMenuItem():建立一个新的JMenuItem.
JMenuItem(Action a):建立一个支持Action的新的JMenuItem.
JMenuItem(Icon icon):建立一个有图标的JMenuItem.
JMenuItem(String text):建立一个有文字的JMenuItem.
JMenuItem(String text,Icon icon):建立一个有图标和文字的JMenuItem.
JMenuItem(String text,int mnemonic):建立一个有文字和键盘设置快捷键的JMenuItem.

12-3-1:构造JMenuItem组件:
在看过JMenuItem的构造方式之后,我们来看一个例子了解JMenuItem是如何运作的.这个例子延伸JMenu1.java,改写buileFileMenu()方法部份.

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import com.incors.plaf.alloy.*;
import com.incors.plaf.alloy.themes.glass.*;

public class JMenuItem1 extends JFrame{

JTextArea theArea = null;

public JMenuItem1(){

super("JMenu1");
theArea = new JTextArea();
theArea.setEditable(true);
getContentPane().add(new JScrollPane(theArea));
JMenuBar MBar = new JMenuBar();

JMenu mfile = buildFileMenu();

MBar.add(mfile);
setJMenuBar(MBar);
}//end of JMenu1()

public JMenu buildFileMenu() {

JMenu thefile = new JMenu("文件");
JMenuItem newf=new JMenuItem("新建");
JMenuItem open=new JMenuItem("打开");
JMenuItem close=new JMenuItem("关闭");
JMenuItem exit=new JMenuItem("退出");

thefile.add(newf);
thefile.add(open);
thefile.add(close);
thefile.addSeparator();//分隔线
thefile.add(exit);
return thefile;
}//end of buildFileMenu()


public static void main(String[] args){
SwingUtil.setLookAndFeel();
JFrame F = new JMenuItem1();
F.setSize(400,200);
F.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) { System.exit(0); }});//end of addWindowListener
F.setVisible(true);
} // end of main
}//end of class JMenu1

class SwingUtil{
public static final void setLookAndFeel() {
try{
Font font = new Font("JFrame", Font.PLAIN, 12);
Enumeration keys = UIManager.getLookAndFeelDefaults().keys();

while (keys.hasMoreElements()) {
Object key = keys.nextElement();
if (UIManager.get(key) instanceof Font) {
UIManager.put(key, font);
}
}
AlloyLookAndFeel.setProperty("alloy.isLookAndFeelFrameDecoration", "true");
AlloyTheme theme = new GlassTheme();
LookAndFeel alloyLnF = new AlloyLookAndFeel(theme);
UIManager.setLookAndFeel(alloyLnF);
}catch(UnsupportedLookAndFeelException ex){
ex.printStackTrace();
}
}
}
我们在一开始就提到JMenuItem是一个特殊的Button组件,因此我们可以在JMenuItem中加入图标文件来美化界面的显示状态,我们来看下面这个范例:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import com.incors.plaf.alloy.*;
import com.incors.plaf.alloy.themes.glass.*;

public class JMenuItem2 extends JFrame{

JTextArea theArea = null;

public JMenuItem2(){

super("JMenuItem2");
theArea = new JTextArea();
theArea.setEditable(false);
getContentPane().add(new JScrollPane(theArea));
JMenuBar MBar = new JMenuBar();
MBar.setOpaque(true);

JMenu mfile = buildFileMenu();

MBar.add(mfile);
setJMenuBar(MBar);
}//end of JMenuItem2()

public JMenu buildFileMenu() {

JMenu thefile = new JMenu("File");

JMenuItem newf = new JMenuItem("New",new ImageIcon("icons/new24.gif"));
JMenuItem open = new JMenuItem("Open",new ImageIcon("icons/open24.gif"));
JMenuItem close= new JMenuItem("Close",new ImageIcon("icons/close24.gif"));
JMenuItem quit = new JMenuItem("Exit",new ImageIcon("icons/exit24.gif"));


thefile.add(newf);
thefile.add(open);
thefile.add(close);
thefile.addSeparator();
thefile.add(quit);


return thefile;
}//end of buildFileMenu()

public static void main(String[] args){
SwingUtil.setLookAndFeel();
JFrame F = new JMenuItem2();
F.setSize(400,200);
F.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});//end of addWindowListener
F.setVisible(true);
} // end of main
}//end of class JMenuItem2
class SwingUtil{
public static final void setLookAndFeel() {
try{
Font font = new Font("JFrame", Font.PLAIN, 12);
Enumeration keys = UIManager.getLookAndFeelDefaults().keys();

while (keys.hasMoreElements()) {
Object key = keys.nextElement();
if (UIManager.get(key) instanceof Font) {
UIManager.put(key, font);
}
}
AlloyLookAndFeel.setProperty("alloy.isLookAndFeelFrameDecoration", "true");
AlloyTheme theme = new GlassTheme();
LookAndFeel alloyLnF = new AlloyLookAndFeel(theme);
UIManager.setLookAndFeel(alloyLnF);
}catch(UnsupportedLookAndFeelException ex){
ex.printStackTrace();
}
}
}
运行程序我们可看到在文字左边出现了我们所指定的图标文件.这时我们又会有疑问了,图标文件一定要摆在文字的左边吗?答案是不一定的!图标在这里会出现在文字左边是因为JMenuItem默认值的关系,我们可以利用setHorizontalTextPosition()方法改变文字的位置.我们将上面程序的buildFileMenu()方法改写如下:
public JMenu buildFileMenu() {

JMenu thefile = new JMenu("File");

JMenuItem newf = new JMenuItem("New",new ImageIcon("icons/new24.gif"));
JMenuItem open = new JMenuItem("Open",new ImageIcon("icons/open24.gif"));
JMenuItem close= new JMenuItem("Close",new ImageIcon("icons/close24.gif"));
JMenuItem quit = new JMenuItem("Exit",new ImageIcon("icons/exit24.gif"));

//定义文字位置
//在这里我们使用了SwingConstants这个interface,这个interface定义了许多在Swing中常用的数值,由于AbstractButton类实作了SwingConstants interface,所以我们可以直接使wingConstants.LEFT代表JMenuItem组件的最左边界值.
newf.setHorizontalTextPosition(SwingConstants.LEFT);
open.setHorizontalTextPosition(SwingConstants.LEFT);
close.setHorizontalTextPosition(SwingConstants.LEFT);
quit.setHorizontalTextPosition(SwingConstants.LEFT);

thefile.add(newf);
thefile.add(open);
thefile.add(close);
thefile.addSeparator();
thefile.add(quit);

return thefile;
}//end of buildFileMenu()

到目前为止我们已经能将一个菜单的外观构造起来,不过我们还少了一个小小的功能,那就是快捷键的设置.快捷键是让我们能使用键盘来控制菜单并方便操作之用.那么怎么将它加入到菜单中呢?我们来看看下面的范例是怎么实现的.
在JMenuItem2.jav中修改buildFileMenu()方法:操作方式->:[Alt]+快捷键
public JMenu buildFileMenu() {

JMenu thefile = new JMenu("File");
thefile.setMnemonic('F');

JMenuItem newf = new JMenuItem("New",new ImageIcon("icons/new24.gif"));
JMenuItem open = new JMenuItem("Open",new ImageIcon("icons/open24.gif"));
JMenuItem close= new JMenuItem("Close",new ImageIcon("icons/close24.gif"));
JMenuItem quit = new JMenuItem("Exit",new ImageIcon("icons/exit24.gif"));

newf.setMnemonic('N');
open.setMnemonic('O');
close.setMnemonic('C');
quit.setMnemonic('X');

thefile.add(newf);
thefile.add(open);
thefile.add(close);
thefile.addSeparator();
thefile.add(quit);

return thefile;
}//end of buildFileMenu()

上面的方法是以[Alt+快捷键]操作,一般的快捷键会设置为[Ctrl]加上某个字符,来直接运行某项功能,要在菜单中加入快捷键很简单,只需要使用setAccelerator()方法即可,我们来看下面的范例:
public JMenu buildFileMenu() {

JMenu thefile = new JMenu("File");
thefile.setMnemonic('F');

JMenuItem newf = new JMenuItem("New",new ImageIcon("icons/new24.gif"));
JMenuItem open = new JMenuItem("Open",new ImageIcon("icons/open24.gif"));
JMenuItem close= new JMenuItem("Close",new ImageIcon("icons/close24.gif"));
JMenuItem quit = new JMenuItem("Exit",new ImageIcon("icons/exit24.gif"));

newf.setMnemonic('N');
open.setMnemonic('O');
close.setMnemonic('L');
quit.setMnemonic('X');

newf.setAccelerator( KeyStroke.getKeyStroke('N', java.awt.Event.CTRL_MASK, false) );
open.setAccelerator( KeyStroke.getKeyStroke('O', java.awt.Event.CTRL_MASK, false) );
close.setAccelerator( KeyStroke.getKeyStroke('L', java.awt.Event.CTRL_MASK, false) );
quit.setAccelerator( KeyStroke.getKeyStroke('X', java.awt.Event.CTRL_MASK, false) );

thefile.add(newf);
thefile.add(open);
thefile.add(close);
thefile.addSeparator();
thefile.add(quit);

return thefile;
}//end of buildFileMenu()


说明:利用setAccelerator()方法,分别设置各个JMenuItem的快捷键值.在setAccelerator()方法中使用了KeyStroke类,这个类是用来管理键盘上的各种信息,我们利用getKeyStroke()方法来指定快捷键的键值.getKeyStroke()方法的三个字段值分别代表键值,屏蔽键值各放开按键时是否触发事件.在这个范例里我们设置[Ctrl+英文字符]来运行JMenuItem的选项功能.
当然,快捷键的屏蔽键值不一定要是[Ctrl],也可以是[Alt],[Shift].
newf.setAccelerator( KeyStroke.getKeyStroke('N', java.awt.Event.SHIFT_MASK, false) );
open.setAccelerator( KeyStroke.getKeyStroke('O', java.awt.Event.SHIFT_MASK, false) );
close.setAccelerator( KeyStroke.getKeyStroke('L', java.awt.Event.SHIFT_MASK, false) );
quit.setAccelerator( KeyStroke.getKeyStroke('X', java.awt.Event.SHIFT_MASK, false) );
现在我们已经能够完整的建立一个菜单了,但是我们现在看到的菜单都是单一层次的,如何来建立具有层次式的菜单呢?我们来看
下面的范例:
由于这支程序修改自JMenuItem3.java,由于只修改了bulidMenu()方法,所以在这里我们只列出bulidMenu()方法的程序部份:

public JMenu buildFileMenu() {

JMenu thefile = new JMenu("File");
thefile.setMnemonic('F');

JMenuItem newf = new JMenuItem("New",new ImageIcon("icons/new24.gif"));
JMenuItem open = new JMenuItem("Open",new ImageIcon("icons/open24.gif"));
JMenuItem close= new JMenuItem("Close",new ImageIcon("icons/close24.gif"));
JMenuItem quit = new JMenuItem("Exit",new ImageIcon("icons/exit24.gif"));

newf.setMnemonic('N');
open.setMnemonic('O');
close.setMnemonic('L');
quit.setMnemonic('X');

newf.setAccelerator( KeyStroke.getKeyStroke('N', java.awt.Event.CTRL_MASK, false) );
open.setAccelerator( KeyStroke.getKeyStroke('O', java.awt.Event.CTRL_MASK, false) );
close.setAccelerator( KeyStroke.getKeyStroke('L', java.awt.Event.CTRL_MASK, false) );
quit.setAccelerator( KeyStroke.getKeyStroke('X', java.awt.Event.CTRL_MASK, false) );


JMenu prefMenu = new JMenu("Preferences..");
prefMenu.setMnemonic('P');

JMenuItem setPage = new JMenuItem("setPage",new ImageIcon("icons/setpage24.gif"));
JMenuItem setImport = new JMenuItem("Import",new ImageIcon("icons/import24.gif"));
JMenuItem setExport = new JMenuItem("Export",new ImageIcon("icons/export24.gif"));

setPage.setMnemonic('S');
setImport.setMnemonic('I');
setExport.setMnemonic('E');

setPage.setAccelerator( KeyStroke.getKeyStroke('S', java.awt.Event.CTRL_MASK, false) );
setImport.setAccelerator( KeyStroke.getKeyStroke('I', java.awt.Event.CTRL_MASK, false) );
setExport.setAccelerator( KeyStroke.getKeyStroke('E', java.awt.Event.CTRL_MASK, false) );

prefMenu.add(setPage);
prefMenu.add(setImport);
prefMenu.add(setExport);


thefile.add(newf);
thefile.add(open);
thefile.add(close);
thefile.addSeparator();
thefile.add(prefMenu);
thefile.addSeparator();
thefile.add(quit);

return thefile;
}//end of buildFileMenu()


12-3-2:JMenuItem的事件处理:
由于JMenuItem继承AbstractButton类,因此JMenuItem也具备了许多AbstractButton的特性,当然也包含了事件处理的机制.JMenuItem的事件处理机制是类似JButton的事件处理模式,换名话说,当按下JMenuItem组件时就如同按下JButton组件一般,均会产生ActionEvent事件,我们来看下面这一范例:
JMenuItem5.java

import javax.swing.*;
import java.awt.event.*;

public class JMenuItem5 extends JFrame{
JTextArea theArea=null;
public JMenuItem5(){
super("JMenuItem5");
theArea=new JTextArea();
theArea.setEditable(false);
getContentPane().add(new JScrollPane(theArea));
JMenuBar MBar=new JMenuBar();
MBar.setOpaque(true);

JMenu mfile=buildFileMenu();
MBar.add(mfile);
setJMenuBar(MBar);
}
public JMenu buildFileMenu() {

JMenu thefile = new JMenu("File");
thefile.setMnemonic('F');

JMenuItem newf = new JMenuItem("New",new ImageIcon("icons/new24.gif"));
JMenuItem open = new JMenuItem("Open",new ImageIcon("icons/open24.gif"));
JMenuItem close= new JMenuItem("Close",new ImageIcon("icons/close24.gif"));
JMenuItem quit = new JMenuItem("Exit",new ImageIcon("icons/exit24.gif"));

newf.setMnemonic('N');
open.setMnemonic('O');
close.setMnemonic('L');
quit.setMnemonic('X');

newf.setAccelerator( KeyStroke.getKeyStroke('N', java.awt.Event.CTRL_MASK, false) );
open.setAccelerator( KeyStroke.getKeyStroke('O', java.awt.Event.CTRL_MASK, false) );
close.setAccelerator( KeyStroke.getKeyStroke('L', java.awt.Event.CTRL_MASK, false) );
quit.setAccelerator( KeyStroke.getKeyStroke('X', java.awt.Event.CTRL_MASK, false) );

newf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
theArea.append("- MenuItem New Performed -\n");
}});


open.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
theArea.append("- MenuItem Open Performed -\n");
}});


close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
theArea.append("- MenuItem Close Performed -\n");
}});


quit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}});


thefile.add(newf);
thefile.add(open);
thefile.add(close);
thefile.addSeparator();
thefile.add(quit);

return thefile;
}//end of buildFileMenu()

public static void main(String[] args){

JFrame F = new JMenuItem5();
F.setSize(400,200);
F.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});//end of addWindowListener
F.setVisible(true);
} // end of main
}

12-4:使用JCheckBoxMenuItem:
JCheckBoxMenuItem的类层次结构图:
java.lang.Object
--java.awt.Component
--java.awt.Container
--javax.swing.JComponent
--javax.swing.AbstractButton
--javax.swing.JMenuItem
--javax.swing.JCheckBoxMenuItem
JCheckBoxMenuItem继承JMenuItem类,因此JCheckBoxMenuItem可以使用JMenuItem所提供的方法,而且JCheckBoxMenuItem也具有AbstractButton的特性,而JChcekBoxMenuItem和JCheckBox的性质几乎是一样,两者间最大的差别在于JCheckBoxMenuItem是专用在MenuItem上.我们来看看JCheckBoxMenuItem的构造方法:
JCheckBoxMenuItem构造函数:
JCheckBoxMenuItem():建立一个新的JCheckBoxMenuItem.
JCheckBoxMenuItem(Action a):建立一个支持Action的新的JCheckBoxMenuItem.
JCheckBoxMenuItem(Icon icon):建立一个有图标的JCheckBoxMenuItem.
JCheckBoxMenuItem(String text):建立一个有文字的JCheckBoxMenuItem.
JCheckBoxMenuItem(String text,Boolean b):建立一个有文字和设置选择状态的JCheckBoxMenuItem.
JCheckBoxMenuItem(String text,Icon icon):建立一个有文字和图标的JCheckBoxMenuItem.
JCheckBoxMenuItem(String text,Icon icon,Boolean b):建立一个有文字,图标和设置状态的JCheckBoxMenuItem.

12-4-1:构造JCheckBoxMenuItem组件:
由上表可以看出JCheckBoxMenuItem的构造方式与JMenuItem的构造方式几乎一模一样,唯一有差异的是JCheckBoxMenuItem的构造方式中多了设置选择状况的构造方式,设置选择状态就是决定是否要将构造好的JCheckBoxMenuItem组件设置成默认值.我们来看下面的范例:
JCheckBoxMenuItem1.java

import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import java.awt.*;
import com.incors.plaf.alloy.*;
import com.incors.plaf.alloy.themes.glass.*;
public class JCheckBoxMenuItem1 extends JFrame implements ActionListener{//由于我们要处理ActionEvent事件,因此要实作
//ActionListener界面.

JTextArea theArea = null;

public JCheckBoxMenuItem1(){

super("JCheckBoxMenuItem1");
theArea = new JTextArea();
theArea.setEditable(false);
getContentPane().add(new JScrollPane(theArea));
JMenuBar MBar = new JMenuBar();
MBar.setOpaque(true);

JMenu mfile = buildFileMenu();
JMenu mstyle = buildStyleMenu();//调用buildStyleMenu()方法来建立包含JCheckBoxMenuItem的JMenu.

MBar.add(mfile);
MBar.add(mstyle);
setJMenuBar(MBar);
}//end of JCheckBoxMenuItem1()

public JMenu buildFileMenu() {

JMenu thefile = new JMenu("File");
thefile.setMnemonic('F');

JMenuItem newf = new JMenuItem("New",new ImageIcon("icons/new24.gif"));
JMenuItem open = new JMenuItem("Open",new ImageIcon("icons/open24.gif"));
JMenuItem close= new JMenuItem("Close",new ImageIcon("icons/close24.gif"));
JMenuItem quit = new JMenuItem("Exit",new ImageIcon("icons/exit24.gif"));

newf.setMnemonic('N');
open.setMnemonic('O');
close.setMnemonic('L');
quit.setMnemonic('X');

newf.setAccelerator( KeyStroke.getKeyStroke('N', java.awt.Event.CTRL_MASK, false) );
open.setAccelerator( KeyStroke.getKeyStroke('O', java.awt.Event.CTRL_MASK, false) );
close.setAccelerator( KeyStroke.getKeyStroke('L', java.awt.Event.CTRL_MASK, false) );
quit.setAccelerator( KeyStroke.getKeyStroke('X', java.awt.Event.CTRL_MASK, false) );

//将File Menu内的三个JMenuItem对象加入事件处理模式.
newf.addActionListener(this);
open.addActionListener(this);
close.addActionListener(this);
quit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}});

thefile.add(newf);
thefile.add(open);
thefile.add(close);
thefile.addSeparator();
thefile.add(quit);

return thefile;
}//end of buildFileMenu()

public JMenu buildStyleMenu() {
//建立新的JMenu组件
JMenu style = new JMenu("Style");
//设置其快捷键
style.setMnemonic('S');

JCheckBoxMenuItem Left = new JCheckBoxMenuItem("Left",new ImageIcon("icons/left24.gif"));
JCheckBoxMenuItem Center = new JCheckBoxMenuItem("Center",new ImageIcon("icons/center24.gif"));
JCheckBoxMenuItem Right = new JCheckBoxMenuItem("Right",new ImageIcon("icons/right24.gif"));
JCheckBoxMenuItem Justify = new JCheckBoxMenuItem("Justify",new ImageIcon("icons/justify24.gif"));

Left.setMnemonic('L');
Center.setMnemonic('E');
Right.setMnemonic('R');
Justify.setMnemonic('J');

Left.setAccelerator( KeyStroke.getKeyStroke('L', java.awt.Event.SHIFT_MASK, false) );
Center.setAccelerator( KeyStroke.getKeyStroke('E', java.awt.Event.SHIFT_MASK, false) );
Right.setAccelerator( KeyStroke.getKeyStroke('R', java.awt.Event.SHIFT_MASK, false) );
Justify.setAccelerator( KeyStroke.getKeyStroke('J', java.awt.Event.SHIFT_MASK, false) );
//分别将四个JCheckBoxMenuItem加入事件处理模式.
Left.addActionListener(this);
Center.addActionListener(this);
Right.addActionListener(this);
Justify.addActionListener(this);

style.add(Left);
style.add(Center);
style.add(Right);
style.add(Justify);

return style;
}//end of buildStyleMenu()

public void actionPerformed(ActionEvent ae){
//为事件处理区段,在这里是将被点选的JMenuItem组件名称填入JTextArea中.
try{
theArea.append("* action '"+ae.getActionCommand()+"' performed. *\n");
}catch(Exception e){
System.out.println("actionPerformed Exception:"+e);
}
}

public static void main(String[] args){
SwingUtil.setLookAndFeel();
JFrame F = new JCheckBoxMenuItem1();
F.setSize(400,200);
F.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});//end of addWindowListener
F.setVisible(true);
} // end of main
}//end of class JCheckBoxMenuItem1
class SwingUtil{
public static final void setLookAndFeel() {
try{
Font font = new Font("JFrame", Font.PLAIN, 12);
Enumeration keys = UIManager.getLookAndFeelDefaults().keys();

while (keys.hasMoreElements()) {
Object key = keys.nextElement();
if (UIManager.get(key) instanceof Font) {
UIManager.put(key, font);
}
}
AlloyLookAndFeel.setProperty("alloy.isLookAndFeelFrameDecoration", "true");
AlloyTheme theme = new GlassTheme();
LookAndFeel alloyLnF = new AlloyLookAndFeel(theme);
UIManager.setLookAndFeel(alloyLnF);
}catch(UnsupportedLookAndFeelException ex){
ex.printStackTrace();
}
}
}

12-5:使用JRadioButtonMenuItem组件:
JRadioButtonMenuItem的类层次结构图:
java.lang.Object
--java.awt.Component
--java.awt.Container
--javax.swing.JComponent
--javax.swing.AbstractButton
--javax.swing.JMenuItem
--javax.swing.JRadioButtonMenuItem
与JCheckBoxMenuItem相同,JRadioButtonItem也是继承JMenuItem,因此JRadioButtonMenuItem也具备JMenuItem的许多特性.而JRadioButtonMenuItem和JCheckBoxMenuItem一样也是一种特殊的JMenuItem.我们在前面也介绍过JRadioButton组件,而JRadioButtonMenuItem是专用在MenuItem上.我们来看看JRadioButtonMenuItem的构造方法,如下表:

JRadioButtonMenuItem的构造函数:
JRadioButtonMenuItem():建立一个新的JRadioButtonMenuItem.
JRadioButtonMenuItem(Action a):建立一个支持Action的新的JRadioButtonMenuItem.
JRadioButtonMenuItem(Icon icon):建立一个有图标的JRadioButtonMenuItem.
JRadioButtonMenuItem(Icon icon,Boolean selected):建立一个有图标和设置选择状态的JRadioButtonMenuItem.
JRadioButtonMenuItem(String text):建立一个有文字的JRadioButtonMenuItem.
JRadioButtonMenuItem(String text,Boolean selected):建立一个有文字和设置选择状态的JRadioButtonMenuItem.
JRadioButtonMenuItem(String text,Icon icon):建立一个有文字和图标的JRadioButtonMenuItem.
JRadioButtonMenuItem(String text,Icon icon,Boolean selected):建立一个有文字,图标和设置状态的JRadioButtonMenuItem.

12-5-1:构造JRadioButtonMenuItem组件:
由一表可以看出JRadioButtonMenuItem的构造方式与JCheckBoxMenuItem构造方式几乎相同,而且和JCheckBoxMenuItem的构造方式一样都是比JMenuItem的构造方式多了设置选择状况的构造方式,设置选择状态就是决定是否要将构造好的JRadioButtonMenuItem
设置为默认值.我们来看下面这个范例:

import javax.swing.*;
import java.awt.event.*;

public class JRadioButtonMenuItem1 extends JFrame implements ActionListener{

JTextArea theArea = null;

public JRadioButtonMenuItem1(){

super("JRadioButtonMenuItem1");
theArea = new JTextArea();
theArea.setEditable(false);
getContentPane().add(new JScrollPane(theArea));
JMenuBar MBar = new JMenuBar();
MBar.setOpaque(true);

JMenu mfile = buildFileMenu();
JMenu mstyle = buildStyleMenu();

MBar.add(mfile);
MBar.add(mstyle);
setJMenuBar(MBar);
}//end of JRadioButtonMenuItem1()

public JMenu buildFileMenu() {

JMenu thefile = new JMenu("File");
thefile.setMnemonic('F');

JMenuItem newf = new JMenuItem("New",new ImageIcon("icons/new24.gif"));
JMenuItem open = new JMenuItem("Open",new ImageIcon("icons/open24.gif"));
JMenuItem close= new JMenuItem("Close",new ImageIcon("icons/close24.gif"));
JMenuItem quit = new JMenuItem("Exit",new ImageIcon("icons/exit24.gif"));

newf.setMnemonic('N');
open.setMnemonic('O');
close.setMnemonic('L');
quit.setMnemonic('X');

newf.setAccelerator( KeyStroke.getKeyStroke('N', java.awt.Event.CTRL_MASK, false) );
open.setAccelerator( KeyStroke.getKeyStroke('O', java.awt.Event.CTRL_MASK, false) );
close.setAccelerator( KeyStroke.getKeyStroke('L', java.awt.Event.CTRL_MASK, false) );
quit.setAccelerator( KeyStroke.getKeyStroke('X', java.awt.Event.CTRL_MASK, false) );

newf.addActionListener(this);
open.addActionListener(this);
close.addActionListener(this);
quit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}});

thefile.add(newf);
thefile.add(open);
thefile.add(close);
thefile.addSeparator();
thefile.add(quit);

return thefile;
}//end of buildFileMenu()

public JMenu buildStyleMenu() {

JMenu style = new JMenu("Style");
style.setMnemonic('S');

JRadioButtonMenuItem Left = new JRadioButtonMenuItem("Left",new ImageIcon("icons/left24.gif"));
JRadioButtonMenuItem Center = new JRadioButtonMenuItem("Center",new ImageIcon("icons/center24.gif"));
JRadioButtonMenuItem Right = new JRadioButtonMenuItem("Right",new ImageIcon("icons/right24.gif"));
JRadioButtonMenuItem Justify = new JRadioButtonMenuItem("Justify",new ImageIcon("icons/justify24.gif"));

Left.setMnemonic('L');
Center.setMnemonic('E');
Right.setMnemonic('R');
Justify.setMnemonic('J');

Left.setAccelerator( KeyStroke.getKeyStroke('L', java.awt.Event.SHIFT_MASK, false) );
Center.setAccelerator( KeyStroke.getKeyStroke('E', java.awt.Event.SHIFT_MASK, false) );
Right.setAccelerator( KeyStroke.getKeyStroke('R', java.awt.Event.SHIFT_MASK, false) );
Justify.setAccelerator( KeyStroke.getKeyStroke('J', java.awt.Event.SHIFT_MASK, false) );

Left.addActionListener(this);
Center.addActionListener(this);
Right.addActionListener(this);
Justify.addActionListener(this);

style.add(Left);
style.add(Center);
style.add(Right);
style.add(Justify);

return style;
}//end of buildStyleMenu()

public void actionPerformed(ActionEvent ae){
try{
theArea.append("* action '"+ae.getActionCommand()+"' performed. *\n");
}catch(Exception e){
System.out.println("actionPerformed Exception:"+e);
}
}
public static void main(String[] args){

JFrame F = new JRadioButtonMenuItem1();
F.setSize(400,200);
F.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});//end of addWindowListener
F.setVisible(true);
} // end of main
}//end of class JRadioButtonMenuItem1

在这个范例中我们遇到了与JRadioButton同样的问题,那就是选项的单、复选的问题.一般来说RadioButton组件是用来做单选的情况时使用,而CheckBox则是多为复选情况时使用.那么我们该怎么来解决这个问题呢?还记得我们介绍JRadioButton时的解决方式吗?没错,就是要利用ButtonGroup类来处理.我们在JRadioButtonMenuItem1.java的buildStyleMenu()方法中加下下列五行:
ButtonGroup bg=new ButtonGroup();
bg.add(Left);
bg.add(Center);
bg.add(Right);
bg.add(Justify);

运行程序我们可看到加入ButtonGroup后的JRadioButtonMenuItem变成只能被单选的菜单.

12-6:使用JToolBar组件:

JToolBar的类层次结构图:
java.lang.Object
--java.awt.Component
--java.awt.Container
--javax.swing.JComponent
--javax.swing.JToolBar
ToolBar的功能是用来放置各种常用的功能或控制组件,这个功能在各类软件中都可以很轻易的看到.一般我们在设计软件时,会将所有功能依类放置在菜单中(JMenu),但当功能数量相当多时,可能造成用户操作一个简单的操作就必须繁复的寻找菜单中相关的功能,这将造成用户操作上的负担.若我们能将一般常用的功能以工具栏方式呈现在菜单下,让用户很快得到他想要的功能,不仅增加用户使用软件的意愿,也加速工作的运行效率.这就是使用ToolBar的好处.我们现在来看看JTooBar的构造方式.
JToolBar构造函数:
JToolBar():建立一个新的JToolBar,位置为默认的水平方向.
JToolBar(int orientation):建立一个指定的JToolBar.
JToolBar(String name):建立一个指定名称的JToolBar.
JToolBar(String name,int orientation):建立一个指定名称和位置的JToolBar.

12-6-1:构造JToolBar组件:
在使用JToolBar时一般都采用水平方向的位置,因此我们在构造时多是采用上表中的第一种构造方式来建立JToolBar.如果需要
改变方向时再用JToolBar内的setOrientation()方法来改变设置,或是以鼠标拉动的方式来改变JToolBar的位置.我们来看下面的例
子:
JToolBar1.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import com.incors.plaf.alloy.*;
import com.incors.plaf.alloy.themes.glass.*;

public class JToolBar1 extends JFrame{

JTextArea theArea = null;
static final String ComboStr[] = {"Times New Roman","Dialog","宋体","黑体","楷体"};

public JToolBar1(){

super("JToolBar1");
theArea = new JTextArea();
theArea.setEditable(false);
getContentPane().add(new JScrollPane(theArea));
JMenuBar MBar = new JMenuBar();
MBar.setOpaque(true);

JMenu mfile = buildFileMenu();
JToolBar theBar = buildToolBar();
this.getContentPane().add(theBar,BorderLayout.NORTH);//将构造好的JToolBar放置到窗口上
.

MBar.add(mfile);//将JMenu加入到JMenuBar中
setJMenuBar(MBar);//将JMenuBar设置到窗口中.
}//end of JToolBar1()

public JMenu buildFileMenu() {

JMenu thefile = new JMenu("File");
thefile.setMnemonic('F');

JMenuItem newf = new JMenuItem("New",new ImageIcon("icons/new24.gif"));
JMenuItem open = new JMenuItem("Open",new ImageIcon("icons/open24.gif"));
JMenuItem close= new JMenuItem("Close",new ImageIcon("icons/close24.gif"));
JMenuItem quit = new JMenuItem("Exit",new ImageIcon("icons/exit24.gif"));

newf.setMnemonic('N');
open.setMne

Saturday, 12 May 2007

Panel in a Panel in a Panel



import java.awt.* ;
import java.awt.event.*;
import javax.swing.*;

public class MorningNoonNight extends JFrame
implements ActionListener
{
JLabel lData1 = new JLabel("Data Item 1");
JTextField txData1 = new JTextField( 7 );
JPanel Panel1 = new JPanel();

JLabel lData2 = new JLabel("Data Item 2");
JTextField txData2 = new JTextField( 7 );
JPanel Panel2 = new JPanel();

JLabel lData3 = new JLabel("Data Item 3");
JTextField txData3 = new JTextField( 7 );
JPanel Panel3 = new JPanel();

JLabel lData4 = new JLabel("Data Item 4");
JTextField txData4 = new JTextField( 7 );
JPanel Panel4 = new JPanel();

JLabel lData5 = new JLabel("Data Item 5");
JTextField txData5 = new JTextField( 7 );
JPanel Panel5 = new JPanel();

JLabel lData6 = new JLabel("Data Item 6");
JTextField txData6 = new JTextField( 7 );
JPanel Panel6 = new JPanel();

JPanel dataPan = new JPanel();

JButton butMorn = new JButton("Morning");
JButton butNoon = new JButton("Noon");
JButton butNite = new JButton("Night");

JPanel leftPanel = new JPanel();
JPanel rightPanel = new JPanel();
JPanel butPan = new JPanel();

public MorningNoonNight()
{
setTitle( "Morning Noon Night" );

Panel1.add( lData1 ); Panel1.add( txData1 );
Panel2.add( lData2 ); Panel2.add( txData2 );
Panel3.add( lData3 ); Panel3.add( txData3 );
Panel4.add( lData4 ); Panel4.add( txData4 );
Panel5.add( lData5 ); Panel5.add( txData5 );
Panel6.add( lData6 ); Panel6.add( txData6 );

butPan.setLayout(
new BoxLayout( butPan, BoxLayout.X_AXIS ) );
butPan.add( butMorn );
butPan.add( butNoon );
butPan.add( butNite );

leftPanel.setLayout(
new BoxLayout( leftPanel, BoxLayout.Y_AXIS ) );
leftPanel.add( Panel1 );
leftPanel.add( Panel2 );
leftPanel.add( Panel3 );

rightPanel.setLayout(
new BoxLayout( rightPanel, BoxLayout.Y_AXIS ) );
rightPanel.add( Panel4 );
rightPanel.add( Panel5 );
rightPanel.add( Panel6 );

dataPan.setLayout(
new BoxLayout( dataPan, BoxLayout.X_AXIS ) );
dataPan.add( leftPanel);
dataPan.add( rightPanel);


getContentPane().setLayout(
new BoxLayout( getContentPane(), BoxLayout.Y_AXIS ) );
getContentPane().add( dataPan );
getContentPane().add( butPan );

setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
}

public void actionPerformed( ActionEvent evt)
{
repaint();
}

public static void main ( String[] args )
{
MorningNoonNight mnn = new MorningNoonNight() ;

mnn.setSize( 400, 250 );
mnn.setVisible( true );
}
}

Friday, 11 May 2007

AWK_中文版

AWK是一种优良的文本处理工具。它不仅是 Linux 中也是任何环境中现有的功能最强大的数据处理发动机之一。这种编程及数据操作语言(其名称得自于它的创始人 Alfred Aho 、Peter Weinberger 和 Brian Kernighan 姓氏的首个字母)的最大功能取决于一个人所拥有的知识。 AWK 提供了极其强大的功能:可以进行样式装入、流控制、数学运算符、进程控制语句甚至于内置的变量和函数。它具备了一个完整的语言所应具有的几乎所有精美特性。实际上 AWK 的确拥有自己的语言: AWK 程序设计语言,三位创建者已将它正式定义为“样式扫描和处理语言”。它允许您创建简短的程序,这些程序读取输入文件、为数据排序、处理数据、对输入执行计算以及生成报表,还有无数其他的功能。

你可能对UNIX比较熟悉,但你可能对awk很陌生,这一点也不奇怪,的确,与其优秀的功能相比,awk还远没达到它应有的知名度。awk是什么?与其它大多数UNIX命令不同的是,从名字上看,我们不可能知道awk的功能:它既不是具有独立意义的英文单词,也不是几个相关单词的缩写。事实上,awk是三个人名的缩写,他们是:Aho、(Peter)Weinberg和 (Brain)Kernighan。正是这三个人创造了awk---一个优秀的样式扫描与处理工具。

   最简单地说, AWK 是一种用于处理文本的编程语言工具。AWK 在很多方面类似于 shell 编程语言,尽管 AWK 具有完全属于其本身的语法。它的设计思想来源于 SNOBOL4 、sed 、Marc Rochkind设计的有效性语言、语言工具 yacc 和 lex ,当然还从 C 语言中获取了一些优秀的思想。在最初创造 AWK 时,其目的是用于文本处理,并且这种语言的基础是,只要在输入数据中有模式匹配,就执行一系列指令。该实用工具扫描文件中的每一行,查找与命令行中所给定内容相匹配的模式。如果发现匹配内容,则进行下一个编程步骤。如果找不到匹配内容,则继续处理下一行。

   尽管操作可能会很复杂,但命令的语法始终是:

   awk '{pattern + action}' {filenames}

   其中 pattern 表示 AWK 在数据中查找的内容,而 action 是在找到匹配内容时所执行的一系列命令。花括号 ({}) 不需要在程序中始终出现,但它们用于根据特定的模式对一系列指令进行分组。

   gawk 是 AWK 的 GNU 版本。

一、AWK的功能是什么?

与sed和 grep很相似,awk是一种样式扫描与处理工具。但其功能却大大强于sed和grep。awk提供了极其强大的功能:它几乎可以完成grep和sed所能完成的全部工作,同时,它还可以可以进行样式装入、流控制、数学运算符、进程控制语句甚至于内置的变量和函数。它具备了一个完整的语言所应具有的几乎所有精美特性。实际上,awk的确拥有自己的语言:awk程序设计语言,awk的三位创建者已将它正式定义为:样式扫描和处理语言。

二、为什么使用awk?

即使如此,你也许仍然会问,我为什么要使用awk?

使用awk的第一个理由是基于文本的样式扫描和处理是我们经常做的工作,awk所做的工作有些象数据库,但与数据库不同的是,它处理的是文本文件,这些文件没有专门的存储格式,普通的人们就能编辑、阅读、理解和处理它们。而数据库文件往往具有特殊的存储格式,这使得它们必须用数据库处理程序来处理它们。既然这种类似于数据库的处理工作我们经常会遇到,我们就应当找到处理它们的简便易行的方法,UNIX有很多这方面的工具,例如sed 、grep、sort以及find等等,awk是其中十分优秀的一种。

使用awk的第二个理由是awk是一个简单的工具,当然这是相对于其强大的功能来说的。的确,UNIX有许嘤判愕墓ぞ撸鏤NIX天然的开发工具C语言及其延续C++就非常的优秀。但相对于它们来说,awk完成同样的功能要方便和简捷得多。这首先是因为awk提供了适应多种需要的解决方案:从解决简单问题的awk命令行到复杂而精巧的awk程序设计语言,这样做的好处是,你可以不必用复杂的方法去解决本来很简单的问题。例如,你可以用一个命令行解决简单的问题,而C不行,即使一个再简单的程序,C语言也必须经过编写、编译的全过程。其次,awk本身是解释执行的,这就使得awk程序不必经过编译的过程,同时,这也使得它与shell script程序能够很好的契合。最后,awk本身较C语言简单,虽然awk吸收了C语言很多优秀的成分,熟悉C语言会对学习awk有很大的帮助,但 awk本身不须要会使用C语言——一种功能强大但需要大量时间学习才能掌握其技巧的开发工具。

使用awk的第三个理由是awk是一个容易获得的工具。与C和C++语言不同,awk只有一个文件(/bin/awk),而且几乎每个版本的UNIX都提供各自版本的awk,你完全不必费心去想如何获得awk。但C语言却不是这样,虽然C语言是UNIX天然的开发工具,但这个开发工具却是单独发行的,换言之,你必须为你的UNIX版本的C语言开发工具单独付费(当然使用D版者除外),获得并安装它,然后你才可以使用它。

基于以上理由,再加上awk强大的功能,我们有理由说,如果你要处理与文本样式扫描相关的工作,awk应该是你的第一选择。在这里有一个可遵循的一般原则:如果你用普通的shell工具或shell script有困难的话,试试awk,如果awk仍不能解决问题,则便用C语言,如果C语言仍然失败,则移至C++。

三、awk的调用方式

前面曾经说过,awk提供了适应多种需要的不同解决方案,它们是:

1、 awk命令行,你可以象使用普通UNIX命令一样使用awk,在命令行中你也可以使用awk程序设计语言,虽然awk支持多行的录入,但是录入长长的命令行并保证其正确无误却是一件令人头疼的事,因此,这种方法一般只用于解决简单的问题。当然,你也可以在shell script程序中引用awk命令行甚至awk程序脚本。

2、使用-f选项调用awk程序。awk允许将一段awk程序写入一个文本文件,然后在awk命令行中用-f选项调用并执行这段程序。具体的方法我们将在后面的awk语法中讲到。

3、利用命令解释器调用awk程序:利用UNIX支持的命令解释器功能,我们可以将一段awk程序写入文本文件,然后在它的第一行加上:
#!/bin/awk -f
并赋予这个文本文件以执行的权限。这样做之后,你就可以在命令行中用类似于下面这样的方式调用并执行这段awk程序了。

$awk脚本文本名 待处理文件

awk的语法:

与其它UNIX命令一样,awk拥有自己的语法:

awk [ -F re] [parameter...] ['prog'] [-f progfile][in_file...]

参数说明:

-F re:允许awk更改其字段分隔符。

parameter: 该参数帮助为不同的变量赋值。

'prog': awk的程序语句段。这个语句段必须用单拓号:'和'括起,以防被shell解释。这个程序语句段的标准形式为:

'pattern {action}'

其中pattern参数可以是egrep正则表达式中的任何一个,它可以使用语法/re/再加上一些样式匹配技巧构成。与sed类似,你也可以使用","分开两样式以选择某个范围。关于匹配的细节,你可以参考附录,如果仍不懂的话,找本UNIX书学学grep和sed(本人是在学习ed时掌握匹配技术的)。 action参数总是被大括号包围,它由一系统awk语句组成,各语句之间用";"分隔。awk解释它们,并在pattern给定的样式匹配的记录上执行其操作。与shell类似,你也可以使用“#”作为注释符,它使“#”到行尾的内容成为注释,在解释执行时,它们将被忽略。你可以省略pattern和 action之一,但不能两者同时省略,当省略pattern时没有样式匹配,表示对所有行(记录)均执行操作,省略action时执行缺省的操作——在标准输出上显示。

-f progfile:允许awk调用并执行progfile指定有程序文件。progfile是一个文本文件,他必须符合awk的语法。

in_file:awk的输入文件,awk允许对多个输入文件进行处理。值得注意的是awk不修改输入文件。如果未指定输入文件,awk将接受标准输入,并将结果显示在标准输出上。awk支持输入输出重定向。

awk的记录、字段与内置变量:

前面说过,awk处理的工作与数据库的处理方式有相同之处,其相同处之一就是awk支持对记录和字段的处理,其中对字段的处理是grep和sed不能实现的,这也是awk优于二者的原因之一。在awk中,缺省的情况下总是将文本文件中的一行视为一个记录,而将一行中的某一部分作为记录中的一个字段。为了操作这些不同的字段,awk借用shell的方法,用$1,$2,$3...这样的方式来顺序地表示行(记录)中的不同字段。特殊地,awk用$0表示整个行(记录)。不同的字段之间是用称作分隔符的字符分隔开的。系统默认的分隔符是空格。awk允许在命令行中用-F re的形式来改变这个分隔符。事实上,awk用一个内置的变量FS来记忆这个分隔符。awk中有好几个这样的内置变量,例如,记录分隔符变量RS、当前工作的记录数NR等等,本文后面的附表列出了全部的内置变量。这些内置的变量可以在awk程序中引用或修改,例如,你可以利用NR变量在模式匹配中指定工作范围,也可以通过修改记录分隔符RS让一个特殊字符而不是换行符作为记录的分隔符。

例:显示文本文件myfile中第七行到第十五行中以字符%分隔的第一字段,第三字段和第七字段:

awk -F % 'NR==7,NR==15 {printf $1 $3 $7}'

四、awk的内置函数

awk 之所以成为一种优秀的程序设计语言的原因之一是它吸收了某些优秀的程序设计语言(例如C)语言的许多优点。这些优点之一就是内置函数的使用,awk定义并支持了一系列的内置函数,由于这些函数的使用,使得awk提供的功能更为完善和强大,例如,awk使用了一系列的字符串处理内置函数(这些函数看起来与C 语言的字符串处理函数相似,其使用方式与C语言中的函数也相差无几),正是由于这些内置函数的使用,使awk处理字符串的功能更加强大。本文后面的附录中列有一般的awk所提供的内置函数,这些内置函数也许与你的awk版本有些出入,因此,在使用之前,最好参考一下你的系统中的联机帮助。

作为内置函数的一个例子,我们将在这里介绍awk的printf函数,这个函数使得awk与c语言的输出相一致。实际上,awk中有许多引用形式都是从C语言借用过来的。如果你熟悉C语言,你也许会记得其中的printf函数,它提供的强大格式输出功能曾经带我们许多的方便。幸运的是,我们在awk中又和它重逢了。awk中printf几乎与C语言中一模一样,如果你熟悉C语言的话,你完全可以照C语言的模式使用awk中的printf。因此在这里,我们只给出一个例子,如果你不熟悉的话,请随便找一本C语言的入门书翻翻。

例:显示文件myfile中的行号和第3字段:

$awk '{printf"%03d%sn",NR,$1}' myfile

五、在命令行使用awk

按照顺序,我们应当讲解awk程序设计的内容了,但在讲解之前,我们将用一些例子来对前面的知识进行回顾,这些例子都是在命令行中使用的,由此我们可以知道在命令行中使用awk是多么的方便。这样做的原因一方面是为下面的内容作铺垫,另一方面是介绍一些解决简单问题的方法,我们完全没有必要用复杂的方法来解决简单的问题----既然awk提供了较为简单的方法的话。

例:显示文本文件mydoc匹配(含有)字符串"sun"的所有行。

$awk '/sun/{print}' mydoc

由于显示整个记录(全行)是awk的缺省动作,因此可以省略action项。

$awk '/sun/' mydoc

例:下面是一个较为复杂的匹配的示例:

$awk '/[Ss]un/,/[Mm]oon/ {print}' myfile

它将显示第一个匹配Sun或sun的行与第一个匹配Moon或moon的行之间的行,并显示到标准输出上。

例:下面的示例显示了内置变量和内置函数length()的使用:

$awk 'length($0)>80 {print NR}' myfile

该命令行将显示文本myfile中所有超过80个字符的行号,在这里,用$0表示整个记录(行),同时,内置变量NR不使用标志符'$'。

例:作为一个较为实际的例子,我们假设要对UNIX中的用户进行安全性检查,方法是考察/etc下的passwd文件,检查其中的passwd字段(第二字段)是否为"*",如不为"*",则表示该用户没有设置密码,显示出这些用户名(第一字段)。我们可以用如下语句实现:

#awk -F: '$2=="" {printf("%s no password!n",$1' /etc/passwd

在这个示例中,passwd文件的字段分隔符是“:”,因此,必须用-F:来更改默认的字段分隔符,这个示例中也涉及到了内置函数printf的使用。

六、awk的变量

如同其它程序设计语言一样,awk允许在程序语言中设置变量,事实上,提供变量的功能是程序设计语言的其本要求,不提供变量的程序设计语言本人还从未见过。

awk 提供两种变量,一种是awk内置的变量,这前面我们已经讲过,需要着重指出的是,与后面提到的其它变量不同的是,在awk程序中引用内置变量不需要使用标志符"$"(回忆一下前面讲过的NR的使用)。awk提供的另一种变量是自定义变量。awk允许用户在awk程序语句中定义并调用自已的变量。当然这种变量不能与内置变量及其它awk保留字相同,在awk中引用自定义变量必须在它前面加上标志符"$"。与C语言不同的是,awk中不需要对变量进行初始化, awk根据其在awk中第一次出现的形式和上下文确定其具体的数据类型。当变量类型不确定时,awk默认其为字符串类型。这里有一个技巧:如果你要让你的 awk程序知道你所使用的变量的明确类型,你应当在在程序中给它赋初值。在后面的实例中,我们将用到这一技巧。

七、运算与判断

作为一种程序设计语言所应具有的特点之一,awk支持多种运算,这些运算与C语言提供的几本相同:如+、-、*、/、%等等,同时,awk也支持C语言中类似++、--、+=、-=、=+、=-之类的功能,这给熟悉C语言的使用者编写awk程序带来了极大的方便。作为对运算功能的一种扩展,awk还提供了一系列内置的运算函数(如log、sqr、cos、sin等等)和一些用于对字符串进行操作(运算)的函数(如length、substr等等)。这些函数的引用大大的提高了awk的运算功能。

作为对条件转移指令的一部分,关系判断是每种程序设计语言都具备的功能,awk也不例外。 awk中允许进行多种测试,如常用的==(等于)、!=(不等于)、>(大于)、<(小于)、>=(大于等于)、>=(小于等于)等等,同时,作为样式匹配,还提供了~(匹配于)和!~(不匹配于)判断。

作为对测试的一种扩充,awk也支持用逻辑运算符:!(非)、&&(与)、||(或)和括号()进行多重判断,这大大增强了awk的功能。本文的附录中列出了awk所允许的运算、判断以及操作符的优先级。

八、awk的流程控制

流程控制语句是任何程序设计语言都不能缺少的部分。任何好的语言都有一些执行流程控制的语句。awk提供的完备的流程控制语句类似于C语言,这给我们编程带来了极大的方便。

1、BEGIN和END:

在awk 中两个特别的表达式,BEGIN和END,这两者都可用于pattern中(参考前面的awk语法),提供BEGIN和END的作用是给程序赋予初始状态和在程序结束之后执行一些扫尾的工作。任何在BEGIN之后列出的操作(在{}内)将在awk开始扫描输入之前执行,而END之后列出的操作将在扫描完全部的输入之后执行。因此,通常使用BEGIN来显示变量和预置(初始化)变量,使用END来输出最终结果。
例:累计销售文件xs中的销售金额(假设销售金额在记录的第三字段):

$awk
>'BEGIN { FS=":";print "统计销售金额";total=0}
>{print $3;total=total+$3;}
>END {printf "销售金额总计:%.2f",total}' sx
(注:>是shell提供的第二提示符,如要在shell程序awk语句和awk语言中换行,则需在行尾加反斜杠)

在这里,BEGIN预置了内部变量FS(字段分隔符)和自定义变量total,同时在扫描之前显示出输出行头。而END则在扫描完成后打印出总合计。

2、流程控制语句

awk提供了完备的流程控制语句,其用法与C语言类似。下面我们一一加以说明:

2.1、if...else语句:

格式:
if(表达式)
语句1
else
语句2

格式中"语句1"可以是多个语句,如果你为了方便awk判断也方便你自已阅读,你最好将多个语句用{}括起来。awk分枝结构允许嵌套,其格式为:

if(表达式1)
{if(表达式2)
语句1
else
语句2
}
语句3
else {if(表达式3)
语句4
else
语句5
}
语句6

当然实际操作过程中你可能不会用到如此复杂的分枝结构,这里只是为了给出其样式罢了。

2.2、while语句

格式为:

while(表达式)
语句

2.3、do-while语句

格式为:

do
{
语句
}while(条件判断语句)

2.4、for语句

格式为:

for(初始表达式;终止条件;步长表达式)
{语句}

在awk 的 while、do-while和for语句中允许使用break,continue语句来控制流程走向,也允许使用exit这样的语句来退出。break 中断当前正在执行的循环并跳到循环外执行下一条语句。continue从当前位置跳到循环开始处执行。对于exit的执行有两种情况:当exit语句不在 END中时,任何操作中的exit命令表现得如同到了文件尾,所有模式或操作执行将停止,END模式中的操作被执行。而出现在END中的exit将导致程序终止。

例:为了

九、awk中的自定义函数

定义和调用用户自己的函数是几乎每个高级语言都具有的功能,awk也不例外,但原始的awk并不提供函数功能,只有在nawk或较新的awk版本中才可以增加函数。

函数的使用包含两部分:函数的定义与函数调用。其中函数定义又包括要执行的代码(函数本身)和从主程序代码传递到该函数的临时调用。

awk函数的定义方法如下:

function 函数名(参数表){
函数体
}

在gawk中允许将function省略为func,但其它版本的awk不允许。函数名必须是一个合法的标志符,参数表中可以不提供参数(但在调用函数时函数名后的一对括号仍然是不可缺少的),也可以提供一个或多个参数。与C语言相似,awk的参数也是通过值来传递的。

在awk 中调用函数比较简单,其方法与C语言相似,但awk比C语言更为灵活,它不执行参数有效性检查。换句话说,在你调用函数时,可以列出比函数预计(函数定义中规定)的多或少的参数,多余的参数会被awk所忽略,而不足的参数,awk将它们置为缺省值0或空字符串,具体置为何值,将取决于参数的使用方式。

awk函数有两种返回方式:隐式返回和显式返回。当awk执行到函数的结尾时,它自动地返回到调用程序,这是函数是隐式返回的。如果需要在结束之前退出函数,可以明确地使用返回语句提前退出。方法是在函数中使用形如:return 返回值 格式的语句。

例:下面的例子演示了函数的使用。在这个示例中,定义了一个名为print_header的函数,该函数调用了两个参数FileName和PageNum, FileName参数传给函数当前使用的文件名,PageNum参数是当前页的页号。这个函数的功能是打印(显示)出当前文件的文件名,和当前页的页号。完成这个功能后,这个函数将返回下一页的页号。

nawk
>'BEGIN{pageno=1;file=FILENAME
>pageno=print_header(file,pageno);#调用函数print_header
>printf("当前页页号是:%dn",pageno);
>}

>#定义函数print_header
>function print_header(FileName,PageNum){
>printf("%s %dn",FileName,PageNum); >PageNum++;return PageNUm;
>}
>}' myfile


执行这个程序将显示如下内容:

myfile 1
当前页页号是:2

十、awk高级输入输出

1.读取下一条记录:

awk的next语句导致awk读取下一个记录并完成模式匹配,然后立即执行相应的操作。通常它用匹配的模式执行操作中的代码。next导致这个记录的任何额外匹配模式被忽略。
2.简单地读取一条记录

awk 的 getline语句用于简单地读取一条记录。如果用户有一个数据记录类似两个物理记录,那么getline将尤其有用。它完成一般字段的分离(设置字段变量$0 FNR NF NR)。如果成功则返回1,失败则返回0(到达文件尾)。如果需简单地读取一个文件,则可以编写以下代码:

例:示例getline的使用

{while(getline==1)
{
#process the inputted fields
}
}

也可以使getline保存输入数据在一个字段中,而不是通过使用getline variable的形式处理一般字段。当使用这种方式时,NF被置成0,FNR和NR被增值。

用户也可以使用getline<"filename"方式从一个给定的文件中输入数据,而不是从命令行所列内容输入数据。此时,getline将完成一般字段分离(设置字段变量$0和NF)。如果文件不存在,返回-1,成功,返回1,返回0表示失败。用户可以从给定文件中读取数据到一个变量中,也可以用stdin(标准输入设备)或一个包含这个文件名的变量代替filename。值得注意的是当使用这种方式时不修改FNR和NR。

另一种使用getline语句的方法是从UNIX命令接受输入,例如下面的例子:

例:示例从UNIX命令接受输入

{while("who -u"|getline)
{
#process each line from the who command
}
}

当然,也可以使用如下形式:

"command" | getline variable

3.关闭文件:

awk中允许在程序中关闭一个输入或输出文件,方法是使用awk的close语句。

close("filename"t

filename可以是getline打开的文件(也可以是stdin,包含文件名的变量或者getline使用的确切命令)。或一个输出文件(可以是stdout,包含文件名的变量或使用管道的确忻睿?

4.输出到一个文件:

awk中允许用如下方式将结果输出到一个文件:

printf("hello word!n"t>"datafile"
或
printf("hello word!n"t>>"datafile"

5.输出到一个命令

awk中允许用如下方式将结果输出到一个命令:

printf("hello word!n"t|"sort-t','"

十一、awk与shell script混合编程

因为awk可以作为一个shell命令使用,因此awk能与shell批处理程序很好的融合在一起,这给实现awk与shell程序的混合编程提供了可能。实现混合编程的关键是awk与shell script之间的对话,换言之,就是awk与shell script之间的信息交流:awk从shell script中获取所需的信息(通常是变量的值)、在awk中执行shell命令行、shell script将命令执行的结果送给awk处理以及shell script读取awk的执行结果等等。

1.awk读取Shell script程序变量

在awk中我们可以通过“'$变量名'”的方式读取sell scrpit程序中的变量。

例:在下面的示例中,我们将读取sell scrpit程序中的变量Name,该变量存放的是文本myfile的撰写者,awk将打印出这个人名。

$cat writename
:
# @(#)
#
.
.
.
Name="张三" nawk 'BEGIN {name="'Name'"; printf("t%st撰写者%sn",FILENAME,name"t;}
{...}END{...}' myfile
.
.
.

2.将shell命令的执行结果送给awk处理

作为信息传送的一种方法,我们可以将一条shell命令的结果通过管道线(|)传递给awk处理:

例:示例awk处理shell命令的执行结果

$who -u | awk '{printf("%s正在执行%sn",$2,$1)}'

该命令将打印出注册终端正在执行的程序名。

3.shell script程序读awk的执行结果

为了实现shell script程序读取awk执行的结果,我们可以采取一些特殊的方法,例如我们可以用变量名=`awk语句`的形式将awk执行的结果存放入一个 shell script变量。当然也可以用管道线的方法将awk执行结果传递给shell script程序处理。

例:作为传送消息的机制之一,UNIX提供了一个向其所有用户传送消息的命令wall(意思是write to all写给所有用户),该命令允许向所有工作中的用户(终端)发送消息。为此,我们可以通过一段shell批处理程序wall.shell来模拟这一程序(事实上比较老的版本中wall就是一段shell批处理程序:
$cat wall.shell
:
# @(#) wall.shell:发送消息给每个已注册终端
#
cat >/tmp/$$
#用户录入消息文本 who -u | awk '{print $2}' | while read tty
do
cat /tmp/$$>$tty
done

在这个程序里,awk接受who -u命令的执行结果,该命令打印出所有已注册终端的信息,其中第二个字段是已注册终端的设备名,因此用awk命令析出该设备名,然后用while read tty语句循环读出这些文件名到变量(shell script变量)tty中,作为信息传送的终结地址。

4.在awk中执行shell命令行----嵌入函数system()

system()是一个不适合字符或数字类型的嵌入函数,该函数的功能是处理作为参数传递给它的字符串。system对这个参数的处理就是将其作为命令处理,也就是说将其当作命令行一样加以执行。这使得用户在自己的awk程序需要时可以灵活地执行命令或脚本。

例:下面的程序将使用system嵌入函数打印用户编制好的报表文件,这个文件存放在名为myreport.txt的文件中。为简约起见,我们只列出了其END部分:

.
.
.
END {close("myreport.txt"t;system("lp myreport.txt"t;}

在这个示例中,我们首先使用close语句关闭了文件myreport.txt文件,然后使用system嵌入函数将myreport.txt送入打印机打印。

写到这里,我不得不跟朋友们说再见了,实在地说,这些内容仍然是awk的初步知识,电脑永远是前进的科学,awk也不例外,本篇所能做的只是在你前行的漫漫长途中铺平一段小小开端,剩下的路还得靠你自己去走。老实说,如果本文真能给你前行的路上带来些许的方便,那本人就知足了!

如对本篇有任何疑问,请E-mail To:Chizlong@yeah.net或到主页http://chizling.yeah.net中留言。


附录:

1.awk的常规表达式元字符

换码序列
^ 在字符串的开头开始匹配
$ 在字符串的结尾开始匹配
. 与任何单个字符串匹配
[ABC] 与[]内的任一字符匹配
[A-Ca-c] 与A-C及a-c范围内的字符匹配(按字母表顺序)
[^ABC] 与除[]内的所有字符以外的任一字符匹配
Desk|Chair 与Desk和Chair中的任一个匹配
[ABC][DEF] 关联。与A、B、C中的任一字符匹配,且其后要跟D、E、F中的任一个字符。
* 与A、B或C中任一个出现0次或多次的字符相匹配
+ 与A、B或C中任何一个出现1次或多次的字符相匹配
? 与一个空串或A、B或C在任何一个字符相匹配
(Blue|Black)berry 合并常规表达式,与Blueberry或Blackberry相匹配

2.awk算术运算符

运算符 用途
------------------
x^y x的y次幂
x**y 同上
x%y 计算x/y的余数(求模)
x+y x加y
x-y x减y
x*y x乘y
x/y x除y
-y 负y(y的开关符号);也称一目减
++y y加1后使用y(前置加)
y++ 使用y值后加1(后缀加)
--y y减1后使用y(前置减)
y-- 使用后y减1(后缀减)
x=y 将y的值赋给x
x+=y 将x+y的值赋给x
x-=y 将x-y的值赋给x
x*=y 将x*y的值赋给x
x/=y 将x/y的值赋给x x%=y 将x%y的值赋给x
x^=y 将x^y的值赋给x
x**=y 将x**y的值赋给x

3.awk允许的测试:

操作符 含义

x==y x等于y
x!=y x不等于y
x>y x大于y
x>=y x大于或等于y
xx<=y x小于或等于y?
x~re x匹配正则表达式re?
x!~re x不匹配正则表达式re?

4.awk的操作符(按优先级升序排列)

= 、+=、 -=、 *= 、/= 、 %=
||
&&
> >= < <= == != ~ !~
xy (字符串连结,'x''y'变成"xy")
+ -
* / %
++ --

5.awk内置变量(预定义变量)

说明:表中v项表示第一个支持变量的工具(下同):A=awk,N=nawk,P=POSIX awk,G=gawk

V 变量 含义 缺省值
--------------------------------------------------------
N ARGC 命令行参数个数
G ARGIND 当前被处理文件的ARGV标志符
N ARGV 命令行参数数组
G CONVFMT 数字转换格式 %.6g
P ENVIRON UNIX环境变量
N ERRNO UNIX系统错误消息
G FIELDWIDTHS 输入字段宽度的空白分隔字符串
A FILENAME 当前输入文件的名字
P FNR 当前记录数
A FS 输入字段分隔符 空格
G IGNORECASE 控制大小写敏感0(大小写敏感)
A NF 当前记录中的字段个数
A NR 已经读出的记录数
A OFMT 数字的输出格式 %.6g
A OFS 输出字段分隔符 空格
A ORS 输出的记录分隔符 新行
A RS 输入的记录他隔符 新行
N RSTART 被匹配函数匹配的字符串首
N RLENGTH 被匹配函数匹配的字符串长度
N SUBSEP 下标分隔符 "34"

6.awk的内置函数

V 函数 用途或返回值
------------------------------------------------
N gsub(reg,string,target) 每次常规表达式reg匹配时替换target中的string
N index(search,string) 返回string中search串的位置
A length(string) 求串string中的字符个数
N match(string,reg) 返回常规表达式reg匹配的string中的位置
N printf(format,variable) 格式化输出,按format提供的格式输出变量variable。
N split(string,store,delim) 根据分界符delim,分解string为store的数组元素
N sprintf(format,variable) 返回一个包含基于format的格式化数据,variables是要放到串中的数据
G strftime(format,timestamp) 返回一个基于format的日期或者时间串,timestmp是systime()函数返回的时间
N sub(reg,string,target) 第一次当常规表达式reg匹配,替换target串中的字符串
A substr(string,position,len) 返回一个以position开始len个字符的子串
P totower(string) 返回string中对应的小写字符
P toupper(string) 返回string中对应的大写字符
A atan(x,y) x的余切(弧度)
N cos(x) x的余弦(弧度)
A exp(x) e的x幂
A int(x) x的整数部分
A log(x) x的自然对数值
N rand() 0-1之间的随机数
N sin(x) x的正弦(弧度)
A sqrt(x) x的平方根
A srand(x) 初始化随机数发生器。如果忽略x,则使用system()
G system() 返回自1970年1月1日以来经过的时间(按秒计算

Thursday, 10 May 2007

Border;Comb_box;Menu

Use Borders
Every JComponent can have one or more borders.
To put a border around a JComponent, you use its setBorder method. You can use the BorderFactory class to create most of the borders that Swing provides.
Here is an example of code that creates a bordered container:
JPanel pane = new JPanel();
pane.setBorder(BorderFactory.createLineBorder(Color.black));
titled borders. Using a titled border, you can convert any border into one that displays a text description.

Border blackline;
blackline = BorderFactory.createLineBorder(Color.black);
jComp1.setBorder(blackline);
TitledBorder title;
title = BorderFactory.createTitledBorder("title");
jComp8.setBorder(title);



Use Combo Boxes
A JComboBox, which lets the user choose one of several choices, can have two very different forms. The default form is the uneditable combo box, which features a button and a drop-down list of values. The second form, called the editable combo box, features a text field with a small button abutting it. The user can type a value in the text field or click the button to display a drop-down list.

String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
//Create the combo box, select item at index 4.
//Indices start at 0, so 4 specifies the pig.
JComboBox petList = new JComboBox(petStrings);
petList.setSelectedIndex(4);
petList.addActionListener(this);

or

String[] patternExamples = {
"dd MMMMM yyyy",
"dd.MM.yy",
"MM/dd/yy",
"yyyy.MM.dd G 'at' hh:mm:ss z",
"EEE, MMM d, ''yy",
"h:mm a",
"H:mm:ss:SSS",
"K:mm a,z",
"yyyy.MMMMM.dd GGG hh:mm aaa"
};
. . .
JComboBox patternList = new JComboBox(patternExamples);
patternList.setEditable(true);
patternList.addActionListener(this);



Use Menus

//Where the GUI is created:
JMenuBar menuBar;
JMenu menu, submenu;
JMenuItem menuItem;
JRadioButtonMenuItem rbMenuItem;
JCheckBoxMenuItem cbMenuItem;

//Create the menu bar.
menuBar = new JMenuBar();

//Build the first menu.
menu = new JMenu("A Menu");
menu.setMnemonic(KeyEvent.VK_A);
menu.getAccessibleContext().setAccessibleDescription(
"The only menu in this program that has menu items");
menuBar.add(menu);

//a group of JMenuItems
menuItem = new JMenuItem("A text-only menu item",
KeyEvent.VK_T);
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_1, ActionEvent.ALT_MASK));
menuItem.getAccessibleContext().setAccessibleDescription(
"This doesn't really do anything");
menu.add(menuItem);

menuItem = new JMenuItem("Both text and icon",
new ImageIcon("images/middle.gif"));
menuItem.setMnemonic(KeyEvent.VK_B);
menu.add(menuItem);

menuItem = new JMenuItem(new ImageIcon("images/middle.gif"));
menuItem.setMnemonic(KeyEvent.VK_D);
menu.add(menuItem);

//a group of radio button menu items
menu.addSeparator();
ButtonGroup group = new ButtonGroup();
rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
rbMenuItem.setSelected(true);
rbMenuItem.setMnemonic(KeyEvent.VK_R);
group.add(rbMenuItem);
menu.add(rbMenuItem);

rbMenuItem = new JRadioButtonMenuItem("Another one");
rbMenuItem.setMnemonic(KeyEvent.VK_O);
group.add(rbMenuItem);
menu.add(rbMenuItem);

//a group of check box menu items
menu.addSeparator();
cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
cbMenuItem.setMnemonic(KeyEvent.VK_C);
menu.add(cbMenuItem);

cbMenuItem = new JCheckBoxMenuItem("Another one");
cbMenuItem.setMnemonic(KeyEvent.VK_H);
menu.add(cbMenuItem);

//a submenu
menu.addSeparator();
submenu = new JMenu("A submenu");
submenu.setMnemonic(KeyEvent.VK_S);

menuItem = new JMenuItem("An item in the submenu");
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_2, ActionEvent.ALT_MASK));
submenu.add(menuItem);

menuItem = new JMenuItem("Another item");
submenu.add(menuItem);
menu.add(submenu);

//Build second menu in the menu bar.
menu = new JMenu("Another Menu");
menu.setMnemonic(KeyEvent.VK_N);
menu.getAccessibleContext().setAccessibleDescription(
"This menu does nothing");
menuBar.add(menu);

...
frame.setJMenuBar(theJMenuBar);
Use Borders
Every JComponent can have one or more borders.
To put a border around a JComponent, you use its setBorder method. You can use the BorderFactory class to create most of the borders that Swing provides.
Here is an example of code that creates a bordered container:
JPanel pane = new JPanel();
pane.setBorder(BorderFactory.createLineBorder(Color.black));
titled borders. Using a titled border, you can convert any border into one that displays a text description.

Border blackline;
blackline = BorderFactory.createLineBorder(Color.black);
jComp1.setBorder(blackline);
TitledBorder title;
title = BorderFactory.createTitledBorder("title");
jComp8.setBorder(title);



Use Combo Boxes

Wednesday, 9 May 2007

normalization

update anomalies:
insertion anomalies
deletion anomalies
modification anomalize

functional dependency: describles the relationship between attributes in a relation. for example, if A and B are attribute of reltion R, B is functionally dependent on A (denoted A->B), if each value of A is associated with eactly one value of B (A and B may each consist of one or more attributes.)
B is functionally dependent on B
A functionally determines B

functional dependency is specified as a constraint between the attributes.

determinant: refers to the attribute, or group of attributes, on the left_hand side of the arrow of a functional dependency.

full functional dependency: indicates that if A and B are attributes of a relation, B is fully functionally dependent on A if B is functionally dependent on A, but not on any proper subset of A.
partially dependency: if there is some attribute that can be removed from A and yet the dependency still holds.

there are two kind of functional dependency:
one-to-one relationship: full functional dependency
many-to-one relationship: partially dependecy

transitive dependency: a condition where A, B and C are attributes of a relation such that if A->B and B->C, then C is transitively dependent on A via B

the main purpose of identifying a set of functional dependencies for a relation is to specify the set of intergrity constraints that must hold on a relation.

hence, we see that an essential characteristic for a candidate key of relation is that the attribute of a determinant either individually or working together must be able to functionally determine all the other attribute in the relation.

the concepts of functional dependencies and keys are central to the process of normalization.
normalization is a formal technique for analyzing relations based on their primary key(or candidate keys) and functional dependencies.

UNF: a table that contains one or more repeating groups

1NF: a relation in which the intersection of each row and column contains one and only one value.

2NF: a relation that is in 1NF and every non_cabdidate_key attribute is fully functionally dependent on the candidate key.
if a partial dependency exists, we remove the partially dependent attributes from the relation by placing them in a new relation along with a copy of their determinant.

3NF: a relation that is in 1NF and 2NF and in which no non-candidate-key attribute is candidate dependent on the primary key.
if a transitive dependency exists, we remove the transitively dependent attributes from the relation by placing the attributes in a new relation along with a copy of the determinant.

redendancy is often caused by a functional dependency. each normal form has fewer FDs than the last. since FDs represent redundancy, each normal form has less redundancy than the last.

properties of FDs
the primary key FDs any set of attributes in that relation. same for candidate key.
any set of attributes is FD on itself.

relues for FDs
reflexivity: if B is a subset of A then: A->B
augmentation: if A->B then: A U C -> B U C
transitivity: if A->B and B->C then A->C

removing FDs:
suppose we have a relation R with scheme S and the FD A->B where A^B ={}
let C = S - (A U B): all other attributes not in A and B
it turns out that we can split R into two parts: R1, with scheme C U A ; R2, with scheme A U B
the orginal relation can be recovered as the natural join of R1 and R2: R=R1 NATURAL JOIN R2.
self-determination: A->A
Decomposition: if A->B,C, then A->B and A->C
Union: if A->B and A->C, then A->B,C
Composition: if A->B and C->D then A,C->B,D

a set of functional dependency X is minimal if it satisfy the following conditions:
every dependency in X has a single attribute on its right-hand side.
We can not replace any dependency A->B in X with dependency C->B, where C is a proper subset of A, and still have a set of dependencies that is equivalent to X
we cannot remove any dependency from X and still have a set of dependencies that is equivalent to x.

transitive FDs
a FD, A->C is a transitive FD, if there is some set B such that A->B and B->C are non-trivial FDs.
A->B non-trivial means: B is not a subset of A

to normalise a relation, we used projection. if R(A,B,C) satisfies A->B then we can project it on A,B and A,C without losing information.

when is decomposition is not lossless: no FD

BCNF: a relation in BCNF if for every FD A->B either B is contained in A(the FD is trivial), or A contains a candidate key of the relation. in other words: every determinant in a non-trivial dependency is a (super) key. If there is only one cadidate key then 3NF and BCNF are the same one.

normalisation to 3NF is always lossless and dependency preserving.
normalisation to BCNF is lossless, may not preserve dependency.

Physical DB Issues

LECTURE_13

E/R modelling helps find the requirements of a database
Normalisation helps to refine a design by removing data redundancy
Physical design Concerned with storing and accessing the data

RAID - redundant array of independent (inexpensive) disks
Storing information across more than one physical disk
Speed - can access more than one disk
Robustness - if one disk fails it is OK

RAID Level 0 : Files are split across several disks
For a system with n disks, each file is split into n parts, one part stored on each disk
Improves speed, but no redundancy

RAID Level 1: As RAID 0 but with redundancy
Files are split over multiple disks
Each disk is mirrored
For n disks, split files into n/2 parts, each stored on 2 disks
Improves speed, has redundancy(in two disks), but needs lots of disks

Parity Checking: for a set of data in binary form we count the number of 1s for each bit across the data. If this is even the parity is 0, if odd then it is 1. We can use parity checking to reduce the number of disks ---------????????how to reduce the number of disk
Recovery With Parity: If one of our pieces of data is lost we can recover it.

RAID Level 3: Data is striped over disks, and a parity disk for redundancy
For n disks, we split the data in n-1 parts
Each part is stored on a disk
The final disk stores parity information for recovery

Indexes:
Types of indexes
Primary or clustered indexes affect the order that the data is stored in a file
Secondary indexes give a look-up table into the file
Only one primary index, but many secondary ones

Choosing Indexes: only have one primary index. The most frequently looked-up value is often the best choice. Some DBMSs assume the primary key is the primary index, as it is usually used to refer to rows
Don’t create too many indexes: They can speed up queries, but they slow down inserts, updates and deletes. Whenever the data is changed, the index may need to change

Creating Indexes:

Query Processing:

Three main stages

Parsing and translation - the query is put into an internal form

relational operators: PRODUCT,SELECTION, PROJECTION,

Optimisation - changes are made for efficiency
Evaluation - the optimised query is applied to the DB

----------P31??????????????????, why 15 operantions


Monday, 7 May 2007

When There Was Me And You

lyric:
It's funny when you find yourself
Looking from the outside
I'm standing here but all I want
Is to be over there
Why did I let myself believe
Miracles could happen
Cause now I have to pretend
That I don't really care

I thought you were my fairytale
A dream when I'm not sleeping
A wish upon a star
Thats coming true
But everybody else could tell
That I confused my feelings with the truth
When there was me and you

I swore I knew the melody
That I heard you singing
And when you smiled
You made me feel
Like I could sing along
But then you went and changed the words
Now my heart is empty
I'm only left with used-to-be's
Once upon a song

Now I know your not a fairytale
And dreams were meant for sleeping
And wishes on a star
Just don't come true
Cause now even I tell
That I confused my feelings with the truth
Cause I liked the view
When there was me and you

I can't believe that
I could be so blind
It's like you were floating
While I was falling
And I didn't mind

Cause I liked the view
Thought you felt it too
When there was me and you


计世网论坛

计世网论坛,里面的文章还是不错的
http://www3.ccw.com.cn/forumdisplay.php?fid=9&page=1