Monday, 14 May 2007

Minutes To Midnight

these days, I am enjoying from Linkin Park's new album Minutes to Midnight. from its introduction, I learn a new phrase named Doomsday Clock
, then I search the web and catch some brief intr from WikiPedia. the singer in introduction was said to be changed but I can not find, however, it is easy to chack out there are several soft songs, it is great different from former ones.



Doomsday Clock
From Wikipedia, the free encyclopedia
(Redirected from Doomsday clock)
The Doomsday Clock now stands at five minutes to midnight.The Doomsday Clock is a symbolic clockface maintained since 1947 by the Board of Directors of the Bulletin of the Atomic Scientists at the University of Chicago. It uses the analogy of the human race being at a time that is "minutes to midnight" where midnight represents destruction by nuclear war. Since its introduction, the clock has appeared on the cover of each issue of the Bulletin of the Atomic Scientists. The first representation of the clock was produced in 1947, when artist Martyl Langsdorf, the wife of physicist, Alexander Langsdorf, Jr., who worked on the Manhattan Project, was asked by magazine cofounder Hyman Goldsmith to design a cover for the June issue.

The number of minutes before midnight, a measure of the degree of nuclear, environmental, and technological threats, is updated periodically. The clock is currently set to five minutes to midnight, having been advanced by two minutes on January 17, 2007.
Time changes
The clock was started at seven minutes to midnight during the Cold War in 1947, and has subsequently been advanced or rewound at intervals, depending on the state of the world and the prospects for nuclear war. Its setting is relatively arbitrary, set by the Board of Directors at the Bulletin of the Atomic Scientists in response to global affairs. The setting of the clock has not always been fast enough to cope with the speed of global events, either; one of the closest periods to nuclear war, the Cuban Missile Crisis in 1962, reached its head and resolution in a number of weeks, and the clock either could not be changed or was not changed to reflect any of this at the time. Nevertheless, the changing of the clock usually does provoke attention.

The clock's hands have been moved 19 times in response to international events since its initial start at seven minutes to midnight in 1947:

1949 - The Soviet Union tests its first atomic bomb. Clock changed to three minutes to midnight (four minutes closer to midnight).
1953 - The United States and the Soviet Union test thermonuclear devices within nine months of one another. Clock changed to two minutes to midnight (one minute closer, its closest approach to midnight to date).
1960 - In response to a perception of increased scientific cooperation and public understanding of the dangers of nuclear weapons, clock is changed to seven minutes to midnight (five minutes further from midnight).
1963 - The United States and Soviet Union sign the Partial Test Ban Treaty, limiting atmospheric nuclear testing. Clock changed to twelve minutes to midnight (another five minutes further).
1968 - France and China acquire and test nuclear weapons (1960 and 1964 respectively), wars rage on in the Middle East, Indian subcontinent, and Vietnam. Clock changed to seven minutes to midnight (five minutes closer to midnight).
1969 - The U.S. Senate ratifies the Nuclear Non-Proliferation Treaty. Clock changed to ten minutes to midnight (three minutes further from midnight).
1972 - The United States and the Soviet Union sign the SALT I (Strategic Arms Limitation Treaty) and the Anti-Ballistic Missile Treaty. Clock changed to twelve minutes to midnight (two minutes further).
1974 - India tests a nuclear device (Smiling Buddha), SALT II talks stall. Clock changed to nine minutes to midnight (three minutes closer to midnight).
1980 - Further deadlock in US-USSR talks, increase in nationalist wars and terrorist actions. Clock changed to seven minutes to midnight (two minutes closer).
1981 - Arms race escalates, conflicts in Afghanistan, South Africa, and Poland
Cover of a 2002 Bulletin of the Atomic Scientists with the famous Doomsday Clock set at seven minutes to midnight. The clock can be seen in the "o" of Atomic in the title.add to world tension. Clock changed to four minutes to midnight (three minutes closer).
1984 - Further escalation of the arms race under the U.S. policies of Ronald Reagan. Clock changed to three minutes to midnight (one minute closer).
1988 - The U.S. and the Soviet Union sign treaty to eliminate intermediate-range nuclear forces, relations improve. Clock changed to six minutes to midnight (three minutes further from midnight).
1990 - Fall of the Berlin Wall, success of anti-communist movements in Eastern Europe, Cold War nearing an end. Clock changed to ten minutes to midnight (four minutes further).
1991 - United States and Soviet Union sign the Strategic Arms Reduction Treaty. Clock changed to seventeen minutes to midnight (seven minutes further, its greatest distance from midnight so far).
1995 - Global military spending continues at Cold War levels; concerns about post-Soviet nuclear proliferation of weapons and brainpower. Clock changed to fourteen minutes to midnight (three minutes closer to midnight).
1998 - Both India and Pakistan test nuclear weapons in a tit-for-tat show of aggression; the United States and Russia run into difficulties in further reducing stockpiles. Clock changed to nine minutes to midnight (five minutes closer).
2002 - Little progress on global nuclear disarmament; United States rejects a series of arms control treaties and announces its intentions to withdraw from the Anti-Ballistic Missile Treaty; terrorists seek to acquire nuclear weapons. Clock changed to seven minutes to midnight (two minutes closer).
2007 - North Korea’s recent test of a nuclear weapon, Iran’s nuclear ambitions, a renewed U.S. emphasis on the military utility of nuclear weapons, the failure to adequately secure nuclear materials, and the continued presence of some 26,000 nuclear weapons in the United States and Russia.[1] Experts assessing the dangers posed to civilization have added climate change to the prospect of nuclear annihilation as the greatest threats to humankind. Clock changed to five minutes to midnight (two minutes closer).
The official announcement of the most recent change to five minutes to midnight took place on January 17, 2007 at 14:30 hours GMT.


In popular culture

In fiction
The Doomsday Clock is referenced in Piers Anthony's novel, Wielding A Red Sword, in which the mythical Incarnation of War can control the position of the hands up to midnight and thereby bring about World War III.
The clock illustrations used in the Watchmen graphic novel series is a reference to The Doomsday Clock. On page 18 of issue #1, a newspaper on Adrian Veidt's desk bears the headline "Nuclear Doomsday Clock Stands At Five To Twelve, Warn Experts".
The Doomsday Clock was used in the game Empire Earth II during a United States mission, featuring a battle on the Bering Sea. The Soviet Union was provoking America to war by attacking Alaska, while the United States was doing everything possible to prevent the clock from reaching midnight.
A similar game, Rise of Nations, has an Armageddon counter that goes down with every nuclear launch. All players will receive an Armageddon ending (automatic lose) if the counter reaches zero.
In the video game Duke Nukem: Zero Hour for the Nintendo 64 the name Zero Hour refers to the Doomsday Clock.
In the book by John Bellairs, The House with a Clock in Its Walls, the mystery involves a clock that is ticking down toward doomsday.
In the comic "Stormwatch PHD". In issue #4 it is explained that the "original" clock gained magical powers, and if the hands were forcefully turned to 12, it would cause nuclear war.

In music
The Doomsday Clock is alluded to throughout "2 Minutes to Midnight", a single from Iron Maiden's album Powerslave. In the cover of the band's single, the mascot Eddie is sitting in chair, with nuclear explosion behind his back.
The song "Def. Con. One." by the band Pop Will Eat Itself includes the lyric "Ten to doomsday, moving fast... Heads up! Mind that blast. No time to sleep, it's Def. Con. One. Can't get no sleep as the ticking ticks on."
The song "Why Did I Fall For That" by The Who has the lines "Four minutes to midnight on a sunny day/Maybe if we smile the clock'll fade away/Maybe we can force the hands to just reverse/'Maybe' is a word, maybe 'maybe's' a curse... We simply believe that we'd remain intact/But history is asking why did you fall for that."
The song "Easy/Lucky/Free" by Bright Eyes contains the lyrics, "I set my watch to the atomic clock. I hear the crowd count down 'til the bomb gets dropped. I always figured there'd be time enough; I never let it get me down."
The Doomsday Clock is directly mentioned in the Ozzy Osbourne song "Thank God for the Bomb" on the album The Ultimate Sin. It is, however, cited in a manner that is inconsistent with the clock's purpose. "The face of the doomsday clock / Has launched a thousand wars / As we near the final hour / Time is the only foe we have."
Australian band Midnight Oil discuss the Doomsday Clock and the threat of nuclear war in their song "Minutes to Midnight" from the album Red Sails in the Sunset. The album cover depicted the disturbing scene of the city of Sydney after a fictional nuclear attack.
"Midnight in a Perfect World" by DJ Shadow, featuring Gift of Gab (from group Blackalicious), alludes to nuclear war and that we are "now approaching midnight", especially in the full lyrical "Gab Mix" off the Endtroducing..... reissue from 2005.
The song "Five Minutes to Midnight" by Boys Like Girls may be a reference to the Doomsday Clock.
On the cover of American band Alive's album 11:59, the Trinity test's rising fireball can be seen with the text "It's later than we thought..." written at the bottom.
Chaos Theory by Jumpsteady makes mention of the Doomsday Clock in the opening song "Outcha Mouth", saying "I'm the last second, sound of doomsday clock, like an open box of anthrax...".
Industrial band Funker Vogt refers heavily to the Doomsday Clock during the chorus of their track "History", a single from the album Survivor, which follows the themes of apocalyptic warfare. Specifically with the lines "The war will soon begin. It's already ten to twelve".
In the music video for "Russians" by Sting, the Doomsday Clock is represented by the clock ticking over the main doorway.
In ABC's music video "S.O.S", the Doomsday Clock was used as the main theme throughout the video.
Linkin Park's album Minutes to Midnight is said to be a reference to the Doomsday Clock.[4]
Zeitgeist, an upcoming Smashing Pumpkins album, includes a song entitled "Doomsday Clock".

In television
Gummi Bears Season 4 Episode 4 "A Knight to Remember" The ghost of a Gummi knight helps Cubbi destroy the mysterious Doomsday Clock.
Glenn Beck had a large Doomsday Clock on the set of his CNN Headline News television show, and he would occasionally adjust the time based on the news of the day.
The title of the Venture Brothers episode "Twenty Years to Midnight" is a reference to the Doomsday clock.
The eighth episode of the series Heroes is titled "Seven Minutes to Midnight", which was the time on the clock at the release of the episode. Also, the villain Sylar wears a watch that stopped at seven minutes to midnight. The series was filmed and began to air prior to the 2007 adjustment of the Doomsday clock, which until then did indeed read seven minutes to midnight.
Adult Swim's night time lineup recently gave reference to the Doomsday clock, by saying sarcastically how we now have five more minutes to do what we want till we die...giving further reference to the recent clock change to five minutes till midnight.
The Doctor Who episode "Four to Doomsday" was first aired in 1982, when the clock was at four minutes to midnight.

In games
In Magic the Gathering 4th edition, there is an artifact called Armageddon Clock that deals increasing damage to each player, speeding up the game's current outcome if left unattended.

Inner Class 嵌套式类

什么是嵌套式类?

顾名思义,Java 语言中的嵌套式类 是在另一个类中声明的类。以下是一个简单的例子:


public class EnclosingClass {
...
public class NestedClass {
...
}
}

通常,好的编程人员会在嵌套式类只在封闭类的上下文中有意义的时候定义嵌套式类。常见的一些例子如下所示:

* UI 类中的事件处理程序。
* 用于组件中的那些 UI 组件的辅助类。
* 适配器类,将某一个类的内部结构转换成其他一些用于该类的用户的形式。

可以将嵌套式类定义为 public、private 或 protected。还可以将嵌套式类定义为 final(以便保护它,使它免受更改)、abstract(意味着它不能被继承)或 static。

当在另一个类中创建 static 类时,将相应地创建一个称为嵌套式类的类。嵌套式类是在另一个类中定义的,但它可以存在于封闭类的实例之外。如果嵌套式类不是 static,那么它只能存在于封闭类的实例中,并且它有一个更适当的称呼,称为内部类。换句话说,所有内部类都是嵌套式类,但并不是所有的嵌套式类都是内部类。在您的工作中遇到的大多数嵌套式类都将是内部类,而不是只是嵌套式类。

任何嵌套式类都可以访问封闭类的所有成员,即使没有将它们声明为 private 也是如此。



定义嵌套式类

定义嵌套式类就像定义非嵌套式类那样,但这项操作是在封闭类中完成的。举一个稍微有点假的例子:在 Adult 内部定义一个 Wallet 类。尽管除了 Adult 之外,实际上还可以拥有一个 Wallet 类,但它并不总是一直有用,所以让每个 Adult 拥有一个 Wallet(或者至少有一个地方存放钱,MoneyContainer 听起来有点怪)是很有道理的。Wallet 并没有存在于 Person 之上也是有一定道理的,因为 Baby 不需要用钱包,如果 Person 上存在 Wallet,那么 Person 的所有子类都将继承它。

这里的 Wallet 将非常简单,因为只有服务器说明了嵌套式类的定义:


protected class Wallet {
protected ArrayList bills = new ArrayList();

protected void addBill(int aBill) {
bills.add(new Integer(aBill));
}

protected int getMoneyTotal() {
int total = 0;
for (Iterator i = bills.iterator(); i.hasNext(); ) {
Integer wrappedBill = (Integer) i.next();
int bill = wrappedBill.intValue();
total += bill;
}
return total;
}
}

我们将定义 Adult 中的类,如下所示:


public class Adult extends Person {
protected Wallet wallet = new Wallet();
public Adult() {
}
public void talk() {
System.out.println("Spoke.");
}
public void acceptMoney(int aBill) {
this.wallet.addBill(aBill);
}
public int moneyTotal() {
return this.wallet.getMoneyTotal();
}
protected class Wallet {
...
}
}

注意,我们添加了 acceptMoney() 来允许 Adult 接受更多的钱。(也可以随意地扩展这个例子,强迫 Adult 给出一些钱,这在现实生活中是很常见的事。)

一旦拥有了自己的嵌套式类和新的 acceptMoney() 方法,就可以使用它们,如下所示:


Adult anAdult = new Adult();
anAdult.acceptMoney(5);
System.out.println("I have this much money: " + anAdult.moneyTotal());

执行以下代码应该报告说 anAdult 的总钱数为 5。



过分简单事件的处理

Java 语言定义了一个事件处理方法,该方法包含相关的类,它允许您创建和处理自己的事件。但事件处理可能比这更简单。实际上,所有您需要的只是一些生成“事件” 的逻辑(该逻辑事实上根本不必是事件类),以及监听该事件并随后相应地给出响应的逻辑。例如,假设无论何时移动 Person,系统都会生成(或者激活)一个 MoveEvent,我们可以选择是处理这个事件,还是不处理这个事件。这要求对系统做一些更改。必须进行以下操作:

* 创建一个“应用程序”类来启动系统,并使用匿名内部类进行说明。
* 创建一个应用程序可以实现的 MotionListener,然后在监听器中处理事件。
* 添加一个监听器的 List 到 Adult 中。
* 添加一个 addMotionListener() 方法到 Adult 中,以便注册一个监听器。
* 添加一个 fireMoveEvent() 方法到 Adult中,这样就可以告诉监听器何时处理事件。
* 添加代码到应用程序中,以便创建一个 Adult 并将其注册为处理程序。

所有这些都很简单。以下是包含新的材料的 Adult:


public class Adult extends Person {
protected Wallet wallet = new Wallet();
protected ArrayList listeners = new ArrayList();
public Adult() {
}
public void move() {
super.move(); fireMoveEvent();
}
...
public void addMotionListener(MotionListener aListener) {
listeners.add(aListener);
}
protected void fireMoveEvent() {
Iterator iterator = listeners.iterator();
while(iterator.hasNext()) {
MotionListener listener = (MotionListener) iterator.next();
listener.handleMove(this);
}
}
protected class Wallet {
...
}
}

注意,我们现在要重写 move(),先调用 Person 上的 move(),然后调用 fireMoveEvent() 告诉监听器作出响应。我们还添加了一个 addMotionListener(),以便将 MotionListener 添加到监听器的运行列表中。以下是一个 MotionListener:


public interface MotionListener {
public void handleMove(Adult eventSource);
}

所有剩下要做的事就是创建应用程序类:


public class CommunityApplication implements MotionListener {
public void handleMove(Adult eventSource) {
System.out.println("This Adult moved:
" + eventSource.toString());
}
public static void main(String[] args) {
CommunityApplication application = new CommunityApplication();
Adult anAdult = new Adult();
anAdult.addMotionListener(application);
anAdult.move();
}
}

这个类实现了 MotionListener 接口,这意味着它实现了 handleMove()。在这里,我们要做的所有事情就是输出一条消息,以说明事件是何时激发的。



匿名内部类

匿名内部类允许在适当的位置定义一个类,而不用命名这个类,以便提供一些特定于上下文的行为。在用户界面中,这是一种用于处理程序的常见方法,这个主题超出了本教程的讨论范围。我们甚至可以在过于简单的事件处理示例中使用匿名内部类。

通过更改对 CommunityApplication.main() 中 addMotionListener() 的调用,可以将前面使用的例子转换成使用匿名内部类,如下所示:


anAdult.addMotionListener(new MotionListener() {
public void handleMove(Adult eventSource) {
System.out.println("This Adult moved:
" + eventSource.toString());
}
});

我们宁愿让 CommunityApplication 实现 MotionListener,也不愿意声明类型 MotionListener 的未指定(因而匿名)的内部类,并为它提供 handleMove() 的实现。事实上,MotionListener 是一个接口,而不是一个类,但是没关系,无论哪种情况都可以接受。

这个代码产生的结果与前面版本产生的结果完全相同,但它使用了一个更常见的并且人们期望使用的方法。几乎总是可以看见用匿名内部类实现的事件处理程序。



使用嵌套式类


嵌套式类可能非常有用,但它们也可能会带来一些痛苦。

当在封闭类之外定义类不那么合理的时候,可以使用嵌套式类。在这个例子中,我们可以拥有在 Adult 之外定义的 Wallet,感觉不错。但是,请设想一下 Personality 这样的类。您曾经有一个位于 Person 实例之外的类吗?没有吧,所以,将这个类定义为嵌套式类是很合理的。一条好的经验法则是:除非显然应该将类定义为嵌套式类,然后重构这个类来实现其嵌套,否则应该将该类定义为非嵌套式类。

匿名内部类是用于事件处理程序的标准方法,因此,可以将它们用于这些方面。在其他情况下,要小心使用它们。除非匿名内部类很小、很集中并且是人们惯用的,否则这些类会弄乱代码。它们还会使调试更加困难,虽然 Eclipse IDE 有助于减轻这种痛苦。通常,除了对事件处理程序使用匿名内部类,绝对不要尝试在其他情况下使用匿名内部类。

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 );
}
}