Monday, 14 May 2007

Pointers and References, Arrays and Strings,Heap and Memory Management

References in Java
A reference is essentially an object’s memory address

Variables containing address are often termed ‘pointers’
A pointer can be thought of as a low-level reference
‘Pointer arithmetic’ – e.g. add offsets, indexing
A pointer is just another type, like an int or a float
Everything stored in memory, pointers included, has an
address: another pointer can even point to it

Arrays
Usually a block of consecutive elements in memory
All same size (s bytes); same offset from one to the next
The i th element is at offset i × s bytes from beginning
Looking up an element of the array is termed ‘indexing’
Assembly equivalent of an int[] in Java would be. . .
a consecutive block of word-sized signed integers
represented by its starting address and length

static data: Contents may change, but size and location doesn’t
In Java, "hello" + "world" contatenates two strings, But neither of the original strings are modified. Instead a new string is created on the heap
The heap is a much larger pool of memory than the stack
Java allocates storage on the heap with the new keyword
All Java objects live on the heap; only primitive types –ints, floats, doubles and references – on the stack
Storage allocated on the heap persist across procedures. Caller can’t access stack storage//-----?????????????

Lecture 10: MIPS Procedure Calling Convention and Recursion

A portion of code within larger program, typically called:
procedures or subroutines in imperative languages like C
methods in OO languages like Java
and functions in functional languages such as Haskell
Functions usually return a value; procedures don’t
Procedures can call other procedures; even themselves

What happens when we call a procedure?
Control hands over to the callee; the caller is suspended
Callee performs requested task
Callee returns control to the caller

Calling Procedures in MIPS Assembly
jal label – jump and link
$ra := PC + 4; PC := [label]-----??????????
Calls procedure at address label
jr src – jump register
PC := src
Issuing j $ra is the assembly equivalent of return

Register $ra contains the return address of the caller
Arguments are passed in registers $a0 to $a3
Results are left in registers $v0 and $v1

The Stack
The stack provides last-in, first out (LIFO) storage
Register $sp points to the topmost word on the stack
By convention, the stack grows downwards
Placing words onto the stack is termed pushing
Taking words off the stack is called popping

Calling Convention
Caller

Push any of $a0-3, $v0-1 and $t0-9 needed later
Place arguments in $a0 to $a3, and stack if necessary
Make the call using jal callee; result in $v0 and $v1
Pop saved registers and/or extra arguments off stack
Callee
Push any of $ra, $s0-$s1 that may be overwritten
Perform desired task; place result in $v0 and $v1
Pop above registers off the stack
Return to caller with jr $ra

The main label is just another procedure


Local Variables
Solution: save initial value of $sp in $fp //---------?????????
Hence local variables always have the same $fp-offset
Note callee must preserve previous value of $fp!

杀人游戏

An occasional chance wake me to search something about Mafia-game, because it seems to be not fashion as a teenage if you do not know it or you can not play。 So, wiki again can tell me much about it even I have no chance to through.


Mafia (game)

For the video game, see Mafia: The City of Lost Heaven.
Mafia

Players 4 or more
Age range 9 and up
Setup time < 6 minutes
Playing time 15-60 minutes2
Random chance Low
Skills required Strategic thought
Team play
Social skills
Roleplay
See Basic gameplay below.
Varies greatly with setting; see online play.
Mafia (also known under the variant Werewolf or Village) is a party game modeling a battle between an informed minority and an uninformed majority. Mafia is usually played in groups with at least five players. During a basic game, players are divided into two teams: 'Mafia members', who know each other; and 'honest people', who know only the number of Mafia amongst them. The goal of both teams is to eliminate each other; in more complicated games with multiple factions, this generally becomes "last side standing".

History
Mafia was created by Dimma Davidoff at the Psychological Department of Moscow State University, in spring of 1986, and the first players were playing in classrooms, dorms, and summer camps of Moscow University. The game become popular in other Soviet colleges and schools and in the 1990s it began to be played in Europe (Hungary, Poland, England, Norway) and then the United States. Mafia is considered to be one of "the 50 most historically and culturally significant games published since 1800" by about.com.

Andrew Plotkin gave the rules a Werewolf theme in 1997 [1] - Looney Labs have sold this version of the game as Are You a Werewolf?, as have Asmodée Éditions under the title Werewolves of Millers Hollow.

David and Jon Huston created another version in the theme of H. P. Lovecraft's Cthulhu Mythos called Do You Worship Cthulhu, published by Toy Vault, Inc. The main card art was completed by Ron Spencer and Walt Howington designed the Instruction graphics.

A variation of Mafia was used in the movie Cry_Wolf. The game involves one wolf, one shepherd, and a number of sheep, with no day and night phases.

Adam Gopnik devotes a chapter to describing the game in "Through the The Children's Gate: at home in New York" (Knopf, 2006).


Basic gameplay

Roles

Players make themselves comfortable in a space such that every player can see every other player. Roles are assigned by a method which is both confidential and verifiable, often by dealing cards; a red or black card signifies the role as either:

Mafia (alternatively, Werewolves or Worshipers)
Innocents (alternatively, Villagers, Townspeople, or Citizens).
Other roles are possible (see Variants).

Generally, gameplay also requires a Narrator (alternatively, Dealer, Don, God, Host, Mayor, Moderator, Proctor, or Storyteller), a person not playing, but moderating the game. The Narrator knows the roles of each of the players and effectively narrates gameplay. However it is possible to have the first dead player become the Narrator when starting with the day phase.


Night
The Narrator tells everyone to close their eyes and lower their heads ("Go to sleep...", "It is now nighttime and all the villagers are asleep...", etc.). This can optionally be accompanied by all players tapping gently to mask the sounds of player movement. On the first night, the Narrator tells the Mafia to open their eyes and acknowledge their fellow Mafia members. Variations at this point:

The Mafia may have a chance to kill off one of the Innocents by show of hands.
On the first night, the Mafia may "kill" the Narrator so that every Innocent gets a chance to participate in at least one execution decision. The Narrator then says in the Morning that he was killed and gameplay continues as usual.
After the first night, Mafia members must secretly communicate during the daytime and then unanimously agree to kill someone during the nighttime without opening their eyes to communicate (i.e., Narrator calls out the names of each player and Mafia must raise a hand to signify a kill). This rule is optional; if it's not included, the Mafia may kill an Innocent in the same method as they did the first night.
In large groups, each Mafia member can kill one person per night.
Other variant characters may have turns to open their eyes to do "business" during the night also (before or after the Mafia).


Day
The Narrator tells everyone to wake up and announces the Mafia's victim. Usually this involves the Narrator telling a story about the murder scene that the remaining players wake up to, and/or a story of how the victim was killed. For example, "The police chief said, 'Bob was shot seven times, stabbed three times and drowned in the river. This is the worst case of suicide I've ever seen.'" This player is "dead" and may no longer participate in the game in any way, and is thus permitted to keep their eyes open at night.

Depending on the variant, The Narrator may reveal the identity of dead players, dead players may reveal themselves by flipping their cards face up (most common version), or the identity of dead players may be left unrevealed. Typically, prematurely revealing one's identity by flipping one's card face up while still alive is considered suicide; in single-execution-per-day variants, this may count as the execution for that day.

During the daytime phase, the players deliberate over which suspected Mafia member they wish to nominate for execution. The Innocents want to execute a Mafia member but all players are allowed to vote. Generally, The Narrator will administer the election, the nominee may be given a chance to defend themselves and a majority is required for the execution to be carried out, although voting variants abound. The same rules apply to players who are executed as to players killed by the Mafia. In some variants, multiple players may be killed during the same day.


Win condition
The game ends either when the last Mafia member is killed (Innocent victory) or the Mafia members gain a majority during the day (Mafia victory). Ties go to the Mafia. The innocents have no way of voting off mafia members at this point, but the mafia can still kill each night. Other variants have different victory conditions.

Note that in a situation of Mafia and Innocent left after a lynching or a morning, the Mafia character usually automatically wins.


Number of Mafia
A game with just one more innocent player than Mafia players during the day phase can still be won by the innocent players (if you start with a night kill, you need two more innocent players than mafia). However, if they make any mistake (i.e. killing an innocent player during the day), they lose.

So the number of "extra villagers" needs to be adjusted to how many mistakes the innocent players are allowed to make during the game. If you have highly skilled players, play with a small difference, if your players tend to just kill random people during the day, increase it. For large parties, kills tend to be much more random, too.

You can start playing mafia with just 3 players, one of which is Mafia (4 if you kill in the first night). This situation however is extremely hard to play lacking any previous knowledge. If the mafia player convinces one of the other two players he wins (draw rule), if he makes both of them suspect him, he loses.

A 5 player setup with just 1 mafia (6 if you kill in the first night) is a bit more interesting. If the innocent players don't happen to identify the mafia player in the first day (which isn't easy), they end up with the same 3 player setup as explained above (or win, if they managed to identify the mafia player), but the remaining players do now have extra information from the behaviour in that previous round.

Empiric values such as 1/3 or 1/4 of players being mafia are common, but again, this depends on the skill of your players. Other players recommend certain combinations such as 2 mafia and 4-5 innocent players, 3 mafia and 6-8 innocent players (and/or discourage larger rounds). There is no mathematically sound 'optimal' value except above "n mafia, n+1 innocent players during the day can still be won by the innocent players" statement.

(Mathematically speaking, this game is not fair. Assuming that all players could read minds, the mafia only wins if they are at least 1/2 of the players in the game. Fortunately, most people can't read minds; but they do usually perform better than a randomizer.)

Variant character roles and rules can change this setup significantly and usually increase or reduce the need for having extra innocent players. But others are targeted at giving the players more data for the 1 mafia vs. 2 innocent "end game"; this data doesn't need to be reliable, but just to give the players more information to base their judgement upon. So when playing with variant character roles, you might or might not have to modify your game parameters.


Variations
Over the years, players have created Mafia variants which utilize alternative names for characters, additional characters, and different methods for conducting deliberation, voting and killing.


Optional roles
Due to the informal nature of the game, roles can be named differently due to cultural differences, thematic flavor, or other reasons. What follows is a general list of types of roles that can be found in Mafia and Werewolf games; it is by nature non-exhaustive.

Protective roles - "Guardian Angel", "Doctor", "Healer", "Archangel", "Bodyguard", "Sorcerer", "Priest", "Protector", "Highlander", "Nurse", etc.
Allied with the Innocents, this person can protect other roles at night. Depending on the variant, they may know the identities of the Mafia and may attempt to persuade the townspeople to kill the members of the mafia rather than another innocent. Sometimes they are allowed to protect themselves. In some games the Nurse obtains the Doctor's abilities if that role dies. Another variant is the "Bulletproof" innocent, who cannot be killed at night by anyone. (In Werewolf, for example, this person could have wolfsbane.)
Investigative roles - "Detective", "Commandant/Super Commandant", "Cop", "Seer", "Spy", "Angel", "Sheriff", "Psychic", "Inspector", "Cattani", "Devil", "Tracker", "Prophet", "Little Girl", etc.
Allied with the Innocents, this person can detect the alignment of other players at night. Occasionally the role will be themed to reveal the role, instead of the alignment. In some variants, the Narrator may lie to the Detective by showing all players as Innocent, all as Guilty, giving reversed results, or random information; these can be termed as "Naïve", "Paranoid", "Insane", or "Random" respectively. A "Tracker" may see what someone's night action was, or the target of their action, and have to deduce information from that. When the Devil exists, he works for the Mafia/Werewolves, trying to discover Innocents with night actions (usually the Angel/investigative roles). The Commandant is equivalent to the detective, though the Super Commandant has an additional protective feature which allows the inspected person (who can be the Commandant, himself) to survive an attempted Mafia killing in the night. The Little Girl in Werewolf is allowed to secretly peek and watch as the werewolves choose their victim.
Killing roles - "Vigilante", "Rambo", "Crazy Veteran", "Bomb", "Terrorist", "Gravedigger", "Hunter", "Village Bicycle", etc.
Aside from Mafia, Werewolves, and Serial Killers (solitary guilty parties), the Innocents may have some roles with the ability to kill at night. The method varies: the Vigilante may have one or more "bullets" for the entire game, or the Bomb/Crazy Vet may only trigger if targeted at night (not necessarily for death) by another role. Variants exist where this person can kill during the daytime cycle (e.g., the Terrorist / Gravedigger), sometimes only if executed during the daytime (eg. the Hunter / Village Bicycle).
Alignment roles - "Miller", "Godfather", "Alpha Wolf", "Traitor", "Village Idiot", "Undercover Cop", "Rat", etc.
Some roles can fool investigations to determine their alignments: the Miller is an Innocent who appears guilty (usually because they are an outsider); the Godfather, on the other hand, appears innocent despite being the leader of the Mafia. The Alpha Wolf is analogous to the Godfather, while the Traitor works with their vote during the day cycle to protect Mafia and hamper the town. The Village Idiot's objective is to get the town to kill him. The Rat or Undercover Cop is a mole within the Mafia group.
Role manipulators - "Role-blocker", "Godfather", "Prostitute", "National Guardsman", "Switcher", "Bus Driver", "Thief", "Witch", "Sorcerer", "Barman", etc.
These roles can stop or alter the night actions of others; for instance, they may prevent a protection or investigation from occurring, or they may change the target. Not all of these roles will be on the side of the Innocents. The Thief may remove the person's role entirely (for instance, by stealing a Vigilante's gun). The Godfather has the ability to recruit innocent players to become Mafia under certain circumstances. This role differs from the Alignment Role of Godfather above.
Association roles - "Freemasons (Masons)", "Siblings", "Cult Leader and Followers", "Cupid", "Lovers" etc.
These roles, usually on the side of the Innocents, know who each other are and what their roles are. Freemasons (Masons) may talk at night, and confirm each other should one become the target of a murder. Siblings typically consist of one Mafia and one Innocent who are related by blood; if one dies, the other commits suicide shortly thereafter. Cult Leaders can recruit at night instead of kill; therefore they act as an independent faction from both the Innocents and Mafia, usually with the ability to talk at night. Cupid can create a Sibling-like relationship between two random players of his/her choosing (called the Lovers) the first night of the game. In this variant, the Lovers can also win the game (regardless of whether they are Mafia, Innocents, or both) by being the last two standing.
Power roles - "Mayor", "Judge", etc.
This role is taken in addition to the assigned role, and it endows the character with additional power over the game (particularly during the daytime). The character could be chosen by random or selected by vote (which could take place before or after roles are assigned). For instance, a Mayor could possess two votes, or a Judge could moderate discussion in parliamentary fashion (to the advantage of their "team"). If the Power character is also an Innocent (and particularly if they have a helpful role), they aid the town. If they are Mafia, this character aids the Mafia.
Additional variations exist, sometimes with even more specialized or complicated abilities.


Optional rules
Mafia killing methods - some variants require all Mafia members to choose the same victim independently for a kill to succeed. Theoretically, this requires them to "communicate" in some way during the daytime and thus increases the chances of detection. This can be achieved either by waking the Mafia members up separately or by having them write their kills. Under this variant, Innocent players write the word 'honest' on a piece of paper; Mafia members write down the name of a player for elimination. If all the mafia notes have the same name on them, that player is considered killed by the Mafia. In some online versions of the game, a particular player (the Godfather, or a designated member of the group) must send in or execute the kill.
Voting variants - some variants have a more complicated process of selecting players to be executed. One variant allows multiple simultaneous nominations and only requires a plurality. Another requires the vote to be unanimous but allows multiple players to be added to the execution queue to ensure unanimity.
"No lynch" or "No kill" - sometimes the Innocents are allowed to vote not to kill anyone on a particular daytime cycle. In general, although the Townspeople will often feel they do not have enough information to kill someone, this is a bad choice because the Townspeople are more likely to vote off a Mafia member than the Mafia are to kill a Mafia member. Furthermore, because a player's role is generally revealed when that player is executed, it provides the Townspeople with reliable and irrefutable information. However, when there are an even number of Townspeople, this can be a good choice. For example, when there are four Townspeople remaining (including one Mafia), voting not to kill someone will result in a 1/3 chance to kill the Mafia the next day as opposed to a 1/4 chance. Note that voting incorrectly in either situation will end the game (resulting in a 1 Mafia/1 Innocent standoff, which is almost always resolved by the Narrator in favor of the Mafia).
Random narrator - to eliminate the inconvenience (especially in large games) of being killed on the first day, this variant has the Innocent who is killed on the first night become the Narrator. The Mafia, of course, has to find a way of informing this person that they are dead without revealing their identities. The writing variant works best. Some players complain that this variant is biased toward eliminating those who are skilled at narrating. This also works the other way round -- there is no kill in the first night (or a fictious player such as the Major or Kenny is killed), but the mafia still wakes up just to learn their identies; the player killed at day becomes the real narrator.
Multiple families - this variant has multiple Mafia families (or a Mafia group and a Werewolf group) who act and win independently of each other. This allows more kills and thus a faster gameplay and also creates the potential for "cross-fire" between the factions.
Imprisonment - this variant allows players to be sent to prison as an alternative to execution. Depending on the variant they can either be sent there by vote or at the discretion of an optional character. Players in prison exist in the separate room possibly with a separate narrator. Murders can happen in prison and certain roles or events have the ability to bring characters back from prison.
Kidnapping - like imprisonment, this variant allows for a Kidnapper character to remove individuals from the game temporarily. If the kidnapper is killed (or, in some cases, investigated by an Investigative role), all kidnapped individuals (whether Mafia or Innocent) return to the game. While kidnapped, characters are considered "dead." However, they can not watch nighttime events because of the possibility of returning.
Wrath of God - this variant allows the Narrator to select in a random and verifiable manner one or more Innocents, (depending on how many total players are in the game) to carry a cost for their death(s). If for example, the Mafia selects said Innocent during the night round, then the Mafia who selected the "protected" player will also die as a result. If during the day round any player leads an accusation towards the "protected" player and that player is voted out, then the original accusor shall die as well. This variant adds to the confusion by allowing players to claim "divine protection" and also makes selecting players to die during the day or night a much more cautious process.
Plague - this variant allows the Narrator to select in a random and verifiable manner one player who dies of plague in the morning. This can occur at set time intervals, or at random, and the player killed in this manner is revealed at the beginning of the next day. A player who targets the plagued player at night may then become plagued as a result of the contact.
Punishment - this variant is generally used as a drinking or risk based game. When a person is killed in the game they are made to take a punishment. In Drinking circles this may be a shot of a spirit such as Gin or Vodka. The punishment is usually decided at the start of the game. A Final punishment could also be added for the losing team too.

Online play
Although Mafia is usually played face to face, playing it online is also common. This adds a new dimension to the game, making it last longer and allowing people to have a record of what others have said and how they have voted. There are many forms of online play: as part for the promotion of the film Cry_Wolf a website was set up to play a similar game using AIM Instant Messenger, pitching wolves against sheep.

Online forum play was first known to be run on the Internet forum Grey Labyrinth by a regular poster from that site. The game requires 1 or 2 moderators to control. A sign up thread is created announcing the game. The game usually starts in the night phase with players messaging the moderator with their choices, and the mafia teams communicating via email before submitting their kill. The moderator will process the choices, write the appropriate death scene for those that were eliminated, and post a dawn scene. Then the players will vote for who they think is mafia. Generally speaking the first day of the online game is very random in nature, but as the game progresses the lynching becomes more strategic and planned.

Themes are the most common method of online play. Any group of well known characters or groups will work. The Simpsons, Hanna Barbera, The Lord of the Rings for example have been used because of their extensive character sets. In themed games, Roles tend to be more creative and relate to the scenes in which they are set. It is not uncommon for major characters to be left out of the balance of roles to allow the mafia teams to lie about who they are. Themes can also be Types - such as a Werewolf-themed game, or more extreme such as Time Travel Mafia or Deep South (a variant with no night phase).

Moderating online play generally requires you to attempt to balance the game well so any team or group has an even chance of winning. This is even more pertinent when using powerful creative roles. The balance is usually 25% mafia - so a 12 player game would entail 3 or 4 mafia depending on the balance of the remainder of the game. A brief listing of the known online variants follows (some would be near impossible to play in real life).

Deep South Mafia - also known as nightless mafia. The game is broken into choice blocks which last a set amount of real life time. During a choice block, players can vote to lynch and/or submit their choices to the moderator. The moderator will action them at a set time. If a player is lynched during that time, the choice block will end immediately, and all votes are nullified and the next block begins. Choices are always made first as part of an update, and then voting. Some moderators may care to flip this rule around. Choices are made in the order received. Common roles for this variant are "Lie Detector" who can detect a lie in a role claim by a player. "Mafia/Serial Killers" who kill during the day at any time. "Advance doctors" who can protect one choice block in advance. "Chef" who can call lunch and end a choice block once.
Grey Labyrinth's Designer Mafia is to have all prospective players invent a role and submit it to the moderator. The moderator tones the roles down to make them playable and then shuffles them up amongst the players.
Location-based games often have maps involved in which players have to travel to different destinations.
MafiaScum.net's Time Travel mafia allows players to alter history with their night choices. Roles are not revealed on death in this variation because players can be brought back to life at any stage. Time travelling roles are usually restricted to prevent chaos. Standard roles are "Coroner" who can investigate a corpse at night. "Blocker" who can prevent a player time travelling. "Serial Killer" who can travel back 1 or 2 nights to kill someone. One of the major changes in Time Travel mafia is that the person with the most votes at the end of a set time is lynched. This means that if a player votes and then dies on a previous night due to a history change, the vote is effectively nullified.
Romanian Mafia Club's Ebony and Ivory mafia games give every player a black ebony ball and a white ivory ball which stand for votes, and the players can effectively work towards lynching or saving others, because every white ball (a vote in favor of that player) takes out a black ball (a vote against him) that he received. The end of the day brings death to the role that has the most black votes.
Mafiascum is an Internet forum where registered members can play a game of Mafia with other people over a message board. Mafiascum has been around since March 2002 and is a direct descendant of the Grey Labyrinth, an Internet forum dedicated to all types of puzzles and games; when Mafia began to dominate the site's traffic and player base, one of the administrators set up a separate forum specifically for those games. Since its creation, membership has grown and diversified, with games now played under different rulesets, in different languages, and at different skill levels. Recently the gamesite moved to an independent server to accommodate these levels of growth. Players have also contributed to a Mafia-specific wiki about game play, strategy, roles, and local players.




http://www.psytopic.com/mag/post/513.html关键词:谎言

杀人游戏最饱受质疑的地方,就是谎言。想在游戏中获胜,关键是不管真话假话,都要说得“理直气壮”。你不能相信其他任何玩家,必须不断制造谎言或者戳穿谎言。

杀手说:一位从事警察工作的玩家对其体会是三个字:可信度。他说,就是简简单单的三个字,可它却成为如今人与人之间最难以把握和捉摸的一种情愫。而“杀人”游戏虽然明里是一个人骗人的游戏,而实则是在教我们如何学会信任。

关键词:友情

“和朋友,可以喝酒,可以旅行,可以逛街,可以结死党,可以相互吹吹牛,拍拍马……但就是不能一起玩‘杀人游戏’。因为,‘杀人游戏’就是一个凶险江湖缩影,一不小心,就暴露了你隐藏很深的底牌,得不偿失。”这是很多人都信奉的一句话。

杀手说:很多圈中人“每次去杀人吧,像回到了家”。他们在游戏中达成默契,结下友谊。这些互为“老朋友”的人,也许不会主动询问你的职业、你的手机号,甚至对你的姓名和年龄都一无所知,但是需要的时候,会给予热情的帮助。

关键词:沉迷

湖南师范大学社会学教授陈成文指出,这类游戏属于心理暗示游戏,游戏者追求游戏的快感和刺激程度往往容易沉迷其中,这对培养一个健康的心态是非常不利,过分沉迷此类游戏必将对身心带来损害。

杀手说:杀手们通常丝豪不掩饰自己对杀人吧的狂热,大部分人都是“一玩就爱上了。这种感觉可能就像吸鸦片。”杀手吴新说:“我知道这样对工作和身体都不好,但就是欲罢不能。”

关键词:过瘾

社会学家仇立平认为,在杀人游戏的过程中,玩家需要根据不同角色或自我辩白或诬陷他人,它让人们有机会在虚拟的游戏世界里扮演“杀手”,过上一把坏人的瘾。

杀手说:徐小姐坦言“喜欢做杀手的感觉,可以主宰其他人的命运,然而,在现实中这是不可能的。”也有人认为,游戏就是游戏,这种模式在现实生活不具备可移植性。“如果像讨伐小学生玩电游一样,批判这个游戏群体,无异于把高理性群体降低成感性人群。”

游戏是一个客观的东西,关键在于游戏者的自控能力。杀人吧受到高知识层的青睐,毕竟对社会危害性不大,存在有合理性,但是也不能排除,游戏过度会产生的心理问题,大脑长期处于兴奋状态,容易造成失衡。
也许,杀人吧的充实,正好填补了现实生活的虚无……

来源: 国际在线
“杀人游戏” 超越游戏

据说“杀人游戏”的雏形源自格林童话:很久以前,一群骑士通过玩纸牌来决定命运,胜者过关,负者葬身毒龙口中。后来,硅谷人由此创立了游戏,并把它作为一种培训工具,用来测评人的心理素质与潜能,培养团队精神。一些敏感的同行们往往只知道这游戏由“海归”们带回,却不知它正是网络人套搬国外商业模式的产物。这个游戏往往能在新员工培训和客户交往时收到奇效,因为它迅速地把陌生的人们挤压到一个封闭的圈子里,让他们休戚与共,大家能迅速熟悉,并了解每个人的个性。虽然它强大的娱乐性掩盖了工具的本质,但究其根源,我们不难理解这种对心理素质和判断力的考验,决不仅仅是在虚拟世界中“发泄”、“减压”那么简单。

“杀人游戏”的参与者面对的是一个信息残缺,虚实难辨的局面,敌友与将来都存在不可预知性,由此,参与者人性的本质和弱点也会不自觉的暴露出来。人的行为模式表现为金字塔形,而塔底则是主导行为的心理动机。据此我们可以把参与游戏者分为这几种类型:

权力型:力图保持权威,充当意见领袖者;

协作型,缺乏主见,追随意见领袖;

控制型:无论成功与否,只求游戏继续,乐于操盘;

成就型,把游戏当作工作,苛求成功,从中获得成就感。

当然还有一种,不擅言辞,容易紧张,往往惨遭错杀者,我们称之“无辜型”。

回头看看,人们在游戏中的表现不正与事业中的表现相符吗?现代人力资源理论认为,苛求人不断发现自己的弱点并不断克服是事业误区,人只有找到自己的核心竞争力并集中发展才不会造成资源浪费。据统计,即便美国也只有1/3受过高等教育的人能找准自己的定位,能通过简单的游戏为人生定位提供参考,游戏的意义早已超越了游戏本身。

林林总总“游戏民”

既然有“股民”、“彩民”世象百态,“游戏民”也不例外。一旦你成为“游戏民”,你就会发现,原来自己如此多疑,记者冷眼旁观了一番“游戏民”们的种种表现。

先看看我们的同行,记者们接近于SOHO一族的生活方式和定题采访的工作习惯造就了强烈的主观意识。他们玩游戏时往往先设立出假想敌,不停搜集素材佐证自己的判断,直觉往往让他们忽略了一些真实的信息。有口舌伶俐的本钱,他们还很容易成为意见领袖,这种领袖往往会误导无辜者,实战中记者就在“老陆”和“老孙”两位胖同行身上证实了这一点。

相比而言技术人员就可信得多,与机器常打交道令他们理性思维极佳,判断时很少感情色彩,“冷酷无情”,评判均衡,误差较小。另外一种IT人则全然把它当作工作,属于成就型,拼命想当法官,而当了良民往往“闹情绪”,常被当奸细“干掉”。

公司领导和下属一同玩游戏不是好事,领导往往会不自觉的成为下属们的意见领袖。尤其是对于规模不大的私企,盲从比率异常的高,而大公司则好得多,“斗争” 也会更有趣。最后给您提供一点秘技:老练的杀手虽然很冷静,少有小动作,但眼神多少会有些惶恐不安或志得意满,盯着他们的眼睛吧,成功率超过60%。

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){//若所输入的值不是整数,则不作任何的操作.

}
}
}
}