第十三章 创建窗口和程序片
在Java 1.0中,图形用户接口(GUI)库最初的设计目标是让程序员构建一个通用的GUI,使其在所有平台上都能正常显示。
但遗憾的是,这个目标并未达到。事实上,Java 1.0版的“抽象Windows工具包”(AWT)产生的是在各系统看来都同样欠佳的图形用户接口。除此之外,它还限制我们只能使用四种字体,并且不能访问操作系统中现有的高级GUI元素。同时,Jave1.0版的AWT编程模型也不是面向对象的,极不成熟。这类情况在Java1.1版的AWT事件模型中得到了很好的改进,例如:更加清晰、面向对象的编程、遵循Java
Beans的范例,以及一个可轻松创建可视编程环境的编程组件模型。Java1.2为老的Java
1.0 AWT添加了Java基础类(AWT),这是一个被称为“Swing”的GUI的一部分。丰富的、易于使用和理解的Java
Beans能经过拖放操作(像手工编程一样的好),创建出能使程序员满意的GUI。软件业的“3次修订版”规则看来对于程序设计语言也是成立的(一个产品除非经过第3次修订,否则不会尽如人意)。
Java的主要设计目的之一是建立程序片,也就是建立运行在WEB
浏览器上的小应用程序。由于它们必须是安全的,所以程序片在运行时必须加以限制。无论怎样,它们都是支持客户端编程的强有力的工具,一个重要的应用便是在Web上。
在一个程序片中编程会受到很多的限制,我们一般说它“在沙箱内”,这是由于Java运行时一直会有某个东西——即Java运行期安全系统——在监视着我们。Jave
1.1为程序片提供了数字签名,所以可选出能信赖的程序片去访问主机。不过,我们也能跳出沙箱的限制写出可靠的程序。在这种情况下,我们可访问操作系统中的其他功能。在这本书中我们自始至终编写的都是可靠的程序,但它们成为了没有图形组件的控制台程序。AWT也能用来为可靠的程序建立GUI接口。
在这一章中我们将先学习使用老的AWT工具,我们会与许多支持和使用AWT的代码程序样本相遇。尽管这有一些困难,但却是必须的,因为我们必须用老的AWT来维护和阅读传统的Java代码。有时甚至需要我们编写AWT代码去支持不能从Java1.0升级的环境。在本章第二部分,我们将学习Java
1.1版中新的AWT结构并会看到它的事件模型是如此的优秀(如果能掌握的话,那么在编制新的程序时就可使用这最新的工具。最后,我们将学习新的能像类库一样加入到Java
1.1版中的JFC/Swing组件,这意味着不需要升级到Java 1.2便能使用这一类库。
大多数的例程都将展示程序片的建立,这并不仅仅是因为这非常的容易,更因为这是AWT的主要作用。另外,当用AWT创建一个可靠的程序时,我们将看到处理程序的不同之处,以及怎样创建能在命令行和浏览器中运行的程序。
请注意的是这不是为了描述类的所有程序的综合解释。这一章将带领我们从摘要开始。当我们查找更复杂的内容时,请确定我们的信息浏览器通过查找类和方法来解决编程中的问题(如果我们正在使用一个开发环境,信息浏览器也许是内建的;如果我们使用的是SUN公司的JDK则这时我们要使用WEB浏览器并在Java根目录下面开始)。附录F列出了用于深入学习库知识的其他一些参考资料。
13.1 为何要用AWT?
对于本章要学习的“老式”AWT,它最严重的缺点就是它无论在面向对象设计方面,还是在GUI开发包设计方面,都有不尽如人意的表现。它使我们回到了程序设计的黑暗年代(换成其他话就是“拙劣的”、“可怕的”、“恶劣的”等等)。必须为执行每一个事件编写代码,包括在其他环境中利用“资源”即可轻松完成的一些任务。
许多象这样的问题在Java 1.1里都得到了缓解或排除,因为:
(1)Java 1.1的新型AWT是一个更好的编程模型,并向更好的库设计迈出了可喜的一步。而Java
Beans则是那个库的框架。
(2)“GUI构建器”(可视编程环境)将适用于所有开发系统。在我们用图形化工具将组件置入窗体的时候,Java
Beans和新的AWT使GUI构建器能帮我们自动完成代码。其它组件技术如ActiveX等也将以相同的形式支持。
既然如此,为什么还要学习使用老的AWT呢?原因很简单,因为它的存在是个事实。就目前来说,这个事实对我们来说显得有些不利,它涉及到面向对象库设计的一个宗旨:一旦我们在库中公布一个组件,就再不能去掉它。如去掉它,就会损害别人已存在的代码。另外,当我们学习Java和所有使用老AWT的程序时,会发现有许多原来的代码使用的都是老式AWT。
AWT必须能与固有操作系统的GUI组件打交通,这意味着它需要执行一个程序片不可能做到的任务。一个不被信任的程序片在操作系统中不能作出任何直接调用,否则它会对用户的机器做出不恰当的事情。一个不被信任的程序片不能访问重要的功能。例如,“在屏幕上画一个窗口”的唯一方法是通过调用拥有特殊接口和安全检查的标准Java库。Sun公司的原始模型创建的信任库将仅仅供给Web浏览器中的Java系统信任关系自动授权器使用,自动授权器将控制怎样进入到库中去。
但当我们想增加操作系统中访问新组件的功能时该怎么办?等待Sun来决定我们的扩展被合并到标准的Java库中,但这不一定会解决我们的问题。Java
1.1版中的新模型是“信任代码”或“签名代码”,因此一个特殊服务器将校验我们下载的、由规定的开发者使用的公共密钥加密系统的代码。这样我们就可知道代码从何而来,那真的是Bob的代码,还是由某人伪装成Bob的代码。这并不能阻止Bob犯错误或作某些恶意的事,但能防止Bob逃避匿名制造计算机病毒的责任。一个数字签名的程序片——“被信任的程序片”——在Java
1.1版能进入我们的机器并直接控制它,正像一些其它的应用程序从信任关系自动授权机中得到“信任”并安装在我们的机器上。
这是老AWT的所有特点。老的AWT代码将一直存在,新的Java编程者在从旧的书本中学习时将会遇到老的AWT代码。同样,老的AWT也是值得去学习的,例如在一个只有少量库的例程设计中。老的AWT所包括的范围在不考虑深度和枚举每一个程序和类,取而代之的是给了我们一个老AWT设计的概貌。
13.2 基本程序片
库通常按照它们的功能来进行组合。一些库,例如使用过的,便中断搁置起来。标准的Java库字符串和矢量类就是这样的一个例子。其他的库被特殊地设计,例如构建块去建立其它的库。库中的某些类是应用程序的框架,其目的是协助我们构建应用程序,在提供类或类集的情况下产生每个特定应用程序的基本活动状况。然后,为我们定制活动状况,必须继承应用程序类并且废弃程序的权益。应用程序框架的默认控制结构将在特定的时间调用我们废弃的程序。应用程序的框架是“分离、改变和中止事件”的好例子,因为它总是努力去尝试集中在被废弃的所有特殊程序段。
程序片利用应用程序框架来建立。我们从类中继承程序片,并且废弃特定的程序。大多数时间我们必须考虑一些不得不运行的使程序片在WEB页面上建立和使用的重要方法。这些方法是:
|
Method |
Operation |
|---|---|
|
init( ) |
Called when the applet is first
created to perform first-time initialization of the applet |
|
start( ) |
Called every time the applet moves
into sight on the Web browser to allow the applet to start up its normal
operations (especially those that are shut off by stop( )). Also
called after init( ). |
|
paint( ) |
Part of the base class
Component (three levels of inheritance up). Called as part of an
update( ) to perform special painting on the canvas of an
applet. |
|
stop( ) |
Called every time the applet moves
out of sight on the Web browser to allow the applet to shut off expensive
operations. Also called right before destroy( ). |
|
destroy( ) |
Called when the applet is being
unloaded from the page to perform final release of resources when the applet is
no longer used |
//: Applet1.java
// Very simple applet
package c13;
import java.awt.*;
import java.applet.*;
public class Applet1 extends Applet {
public void paint(Graphics g) {
g.drawString("First applet", 10, 10);
}
} ///:~
<applet code=Applet1 width=200 height=200> </applet>
//: Applet2.java
// Easy graphics
import java.awt.*;
import java.applet.*;
public class Applet2 extends Applet {
public void paint(Graphics g) {
g.drawString("Second applet", 10, 15);
g.draw3DRect(0, 0, 100, 20, true);
}
} ///:~
//: Applet3.java
// Shows init(), start() and stop() activities
import java.awt.*;
import java.applet.*;
public class Applet3 extends Applet {
String s;
int inits = 0;
int starts = 0;
int stops = 0;
public void init() { inits++; }
public void start() { starts++; }
public void stop() { stops++; }
public void paint(Graphics g) {
s = "inits: " + inits +
", starts: " + starts +
", stops: " + stops;
g.drawString(s, 10, 10);
}
} ///:~
//: Button1.java
// Putting buttons on an applet
import java.awt.*;
import java.applet.*;
public class Button1 extends Applet {
Button
b1 = new Button("Button 1"),
b2 = new Button("Button 2");
public void init() {
add(b1);
add(b2);
}
} ///:~
//: Button2.java
// Capturing button presses
import java.awt.*;
import java.applet.*;
public class Button2 extends Applet {
Button
b1 = new Button("Button 1"),
b2 = new Button("Button 2");
public void init() {
add(b1);
add(b2);
}
public boolean action(Event evt, Object arg) {
if(evt.target.equals(b1))
getAppletContext().showStatus("Button 1");
else if(evt.target.equals(b2))
getAppletContext().showStatus("Button 2");
// Let the base class handle it:
else
return super.action(evt, arg);
return true; // We've handled it here
}
} ///:~
//: Button3.java
// Matching events on button text
import java.awt.*;
import java.applet.*;
public class Button3 extends Applet {
Button
b1 = new Button("Button 1"),
b2 = new Button("Button 2");
public void init() {
add(b1);
add(b2);
}
public boolean action (Event evt, Object arg) {
if(arg.equals("Button 1"))
getAppletContext().showStatus("Button 1");
else if(arg.equals("Button 2"))
getAppletContext().showStatus("Button 2");
// Let the base class handle it:
else
return super.action(evt, arg);
return true; // We've handled it here
}
} ///:~
//: TextField1.java
// Using the text field control
import java.awt.*;
import java.applet.*;
public class TextField1 extends Applet {
Button
b1 = new Button("Get Text"),
b2 = new Button("Set Text");
TextField
t = new TextField("Starting text", 30);
String s = new String();
public void init() {
add(b1);
add(b2);
add(t);
}
public boolean action (Event evt, Object arg) {
if(evt.target.equals(b1)) {
getAppletContext().showStatus(t.getText());
s = t.getSelectedText();
if(s.length() == 0) s = t.getText();
t.setEditable(true);
}
else if(evt.target.equals(b2)) {
t.setText("Inserted by Button 2: " + s);
t.setEditable(false);
}
// Let the base class handle it:
else
return super.action(evt, arg);
return true; // We've handled it here
}
} ///:~
//: TextArea1.java
// Using the text area control
import java.awt.*;
import java.applet.*;
public class TextArea1 extends Applet {
Button b1 = new Button("Text Area 1");
Button b2 = new Button("Text Area 2");
Button b3 = new Button("Replace Text");
Button b4 = new Button("Insert Text");
TextArea t1 = new TextArea("t1", 1, 30);
TextArea t2 = new TextArea("t2", 4, 30);
public void init() {
add(b1);
add(t1);
add(b2);
add(t2);
add(b3);
add(b4);
}
public boolean action (Event evt, Object arg) {
if(evt.target.equals(b1))
getAppletContext().showStatus(t1.getText());
else if(evt.target.equals(b2)) {
t2.setText("Inserted by Button 2");
t2.appendText(": " + t1.getText());
getAppletContext().showStatus(t2.getText());
}
else if(evt.target.equals(b3)) {
String s = " Replacement ";
t2.replaceText(s, 3, 3 + s.length());
}
else if(evt.target.equals(b4))
t2.insertText(" Inserted ", 10);
// Let the base class handle it:
else
return super.action(evt, arg);
return true; // We've handled it here
}
} ///:~
//: Label1.java
// Using labels
import java.awt.*;
import java.applet.*;
public class Label1 extends Applet {
TextField t1 = new TextField("t1", 10);
Label labl1 = new Label("TextField t1");
Label labl2 = new Label(" ");
Label labl3 = new Label(" ",
Label.RIGHT);
Button b1 = new Button("Test 1");
Button b2 = new Button("Test 2");
public void init() {
add(labl1); add(t1);
add(b1); add(labl2);
add(b2); add(labl3);
}
public boolean action (Event evt, Object arg) {
if(evt.target.equals(b1))
labl2.setText("Text set into Label");
else if(evt.target.equals(b2)) {
if(labl3.getText().trim().length() == 0)
labl3.setText("labl3");
if(labl3.getAlignment() == Label.LEFT)
labl3.setAlignment(Label.CENTER);
else if(labl3.getAlignment()==Label.CENTER)
labl3.setAlignment(Label.RIGHT);
else if(labl3.getAlignment() == Label.RIGHT)
labl3.setAlignment(Label.LEFT);
}
else
return super.action(evt, arg);
return true;
}
} ///:~
//: CheckBox1.java
// Using check boxes
import java.awt.*;
import java.applet.*;
public class CheckBox1 extends Applet {
TextArea t = new TextArea(6, 20);
Checkbox cb1 = new Checkbox("Check Box 1");
Checkbox cb2 = new Checkbox("Check Box 2");
Checkbox cb3 = new Checkbox("Check Box 3");
public void init() {
add(t); add(cb1); add(cb2); add(cb3);
}
public boolean action (Event evt, Object arg) {
if(evt.target.equals(cb1))
trace("1", cb1.getState());
else if(evt.target.equals(cb2))
trace("2", cb2.getState());
else if(evt.target.equals(cb3))
trace("3", cb3.getState());
else
return super.action(evt, arg);
return true;
}
void trace(String b, boolean state) {
if(state)
t.appendText("Box " + b + " Set\n");
else
t.appendText("Box " + b + " Cleared\n");
}
} ///:~
//: RadioButton1.java
// Using radio buttons
import java.awt.*;
import java.applet.*;
public class RadioButton1 extends Applet {
TextField t =
new TextField("Radio button 2", 30);
CheckboxGroup g = new CheckboxGroup();
Checkbox
cb1 = new Checkbox("one", g, false),
cb2 = new Checkbox("two", g, true),
cb3 = new Checkbox("three", g, false);
public void init() {
t.setEditable(false);
add(t);
add(cb1); add(cb2); add(cb3);
}
public boolean action (Event evt, Object arg) {
if(evt.target.equals(cb1))
t.setText("Radio button 1");
else if(evt.target.equals(cb2))
t.setText("Radio button 2");
else if(evt.target.equals(cb3))
t.setText("Radio button 3");
else
return super.action(evt, arg);
return true;
}
} ///:~
//: Choice1.java
// Using drop-down lists
import java.awt.*;
import java.applet.*;
public class Choice1 extends Applet {
String[] description = { "Ebullient", "Obtuse",
"Recalcitrant", "Brilliant", "Somnescent",
"Timorous", "Florid", "Putrescent" };
TextField t = new TextField(30);
Choice c = new Choice();
Button b = new Button("Add items");
int count = 0;
public void init() {
t.setEditable(false);
for(int i = 0; i < 4; i++)
c.addItem(description[count++]);
add(t);
add(c);
add(b);
}
public boolean action (Event evt, Object arg) {
if(evt.target.equals(c))
t.setText("index: " + c.getSelectedIndex()
+ " " + (String)arg);
else if(evt.target.equals(b)) {
if(count < description.length)
c.addItem(description[count++]);
}
else
return super.action(evt, arg);
return true;
}
} ///:~
//: List1.java
// Using lists with action()
import java.awt.*;
import java.applet.*;
public class List1 extends Applet {
String[] flavors = { "Chocolate", "Strawberry",
"Vanilla Fudge Swirl", "Mint Chip",
"Mocha Almond Fudge", "Rum Raisin",
"Praline Cream", "Mud Pie" };
// Show 6 items, allow multiple selection:
List lst = new List(6, true);
TextArea t = new TextArea(flavors.length, 30);
Button b = new Button("test");
int count = 0;
public void init() {
t.setEditable(false);
for(int i = 0; i < 4; i++)
lst.addItem(flavors[count++]);
add(t);
add(lst);
add(b);
}
public boolean action (Event evt, Object arg) {
if(evt.target.equals(lst)) {
t.setText("");
String[] items = lst.getSelectedItems();
for(int i = 0; i < items.length; i++)
t.appendText(items[i] + "\n");
}
else if(evt.target.equals(b)) {
if(count < flavors.length)
lst.addItem(flavors[count++], 0);
}
else
return super.action(evt, arg);
return true;
}
} ///:~
//: List2.java
// Using lists with handleEvent()
import java.awt.*;
import java.applet.*;
public class List2 extends Applet {
String[] flavors = { "Chocolate", "Strawberry",
"Vanilla Fudge Swirl", "Mint Chip",
"Mocha Almond Fudge", "Rum Raisin",
"Praline Cream", "Mud Pie" };
// Show 6 items, allow multiple selection:
List lst = new List(6, true);
TextArea t = new TextArea(flavors.length, 30);
Button b = new Button("test");
int count = 0;
public void init() {
t.setEditable(false);
for(int i = 0; i < 4; i++)
lst.addItem(flavors[count++]);
add(t);
add(lst);
add(b);
}
public boolean handleEvent(Event evt) {
if(evt.id == Event.LIST_SELECT ||
evt.id == Event.LIST_DESELECT) {
if(evt.target.equals(lst)) {
t.setText("");
String[] items = lst.getSelectedItems();
for(int i = 0; i < items.length; i++)
t.appendText(items[i] + "\n");
}
else
return super.handleEvent(evt);
}
else
return super.handleEvent(evt);
return true;
}
public boolean action(Event evt, Object arg) {
if(evt.target.equals(b)) {
if(count < flavors.length)
lst.addItem(flavors[count++], 0);
}
else
return super.action(evt, arg);
return true;
}
} ///:~
//: FlowLayout1.java
// Demonstrating the FlowLayout
import java.awt.*;
import java.applet.*;
public class FlowLayout1 extends Applet {
public void init() {
setLayout(new FlowLayout());
for(int i = 0; i < 20; i++)
add(new Button("Button " + i));
}
} ///:~
//: BorderLayout1.java
// Demonstrating the BorderLayout
import java.awt.*;
import java.applet.*;
public class BorderLayout1 extends Applet {
public void init() {
int i = 0;
setLayout(new BorderLayout());
add("North", new Button("Button " + i++));
add("South", new Button("Button " + i++));
add("East", new Button("Button " + i++));
add("West", new Button("Button " + i++));
add("Center", new Button("Button " + i++));
}
} ///:~
//: GridLayout1.java
// Demonstrating the GridLayout
import java.awt.*;
import java.applet.*;
public class GridLayout1 extends Applet {
public void init() {
setLayout(new GridLayout(7,3));
for(int i = 0; i < 20; i++)
add(new Button("Button " + i));
}
} ///:~
//: CardLayout1.java
// Demonstrating the CardLayout
import java.awt.*;
import java.applet.Applet;
class ButtonPanel extends Panel {
ButtonPanel(String id) {
setLayout(new BorderLayout());
add("Center", new Button(id));
}
}
public class CardLayout1 extends Applet {
Button
first = new Button("First"),
second = new Button("Second"),
third = new Button("Third");
Panel cards = new Panel();
CardLayout cl = new CardLayout();
public void init() {
setLayout(new BorderLayout());
Panel p = new Panel();
p.setLayout(new FlowLayout());
p.add(first);
p.add(second);
p.add(third);
add("North", p);
cards.setLayout(cl);
cards.add("First card",
new ButtonPanel("The first one"));
cards.add("Second card",
new ButtonPanel("The second one"));
cards.add("Third card",
new ButtonPanel("The third one"));
add("Center", cards);
}
public boolean action(Event evt, Object arg) {
if (evt.target.equals(first)) {
cl.first(cards);
}
else if (evt.target.equals(second)) {
cl.first(cards);
cl.next(cards);
}
else if (evt.target.equals(third)) {
cl.last(cards);
}
else
return super.action(evt, arg);
return true;
}
} ///:~
//: AutoEvent.java
// Alternatives to action()
import java.awt.*;
import java.applet.*;
import java.util.*;
class MyButton extends Canvas {
AutoEvent parent;
Color color;
String label;
MyButton(AutoEvent parent,
Color color, String label) {
this.label = label;
this.parent = parent;
this.color = color;
}
public void paint(Graphics g) {
g.setColor(color);
int rnd = 30;
g.fillRoundRect(0, 0, size().width,
size().height, rnd, rnd);
g.setColor(Color.black);
g.drawRoundRect(0, 0, size().width,
size().height, rnd, rnd);
FontMetrics fm = g.getFontMetrics();
int width = fm.stringWidth(label);
int height = fm.getHeight();
int ascent = fm.getAscent();
int leading = fm.getLeading();
int horizMargin = (size().width - width)/2;
int verMargin = (size().height - height)/2;
g.setColor(Color.white);
g.drawString(label, horizMargin,
verMargin + ascent + leading);
}
public boolean keyDown(Event evt, int key) {
TextField t =
(TextField)parent.h.get("keyDown");
t.setText(evt.toString());
return true;
}
public boolean keyUp(Event evt, int key) {
TextField t =
(TextField)parent.h.get("keyUp");
t.setText(evt.toString());
return true;
}
public boolean lostFocus(Event evt, Object w) {
TextField t =
(TextField)parent.h.get("lostFocus");
t.setText(evt.toString());
return true;
}
public boolean gotFocus(Event evt, Object w) {
TextField t =
(TextField)parent.h.get("gotFocus");
t.setText(evt.toString());
return true;
}
public boolean
mouseDown(Event evt,int x,int y) {
TextField t =
(TextField)parent.h.get("mouseDown");
t.setText(evt.toString());
return true;
}
public boolean
mouseDrag(Event evt,int x,int y) {
TextField t =
(TextField)parent.h.get("mouseDrag");
t.setText(evt.toString());
return true;
}
public boolean
mouseEnter(Event evt,int x,int y) {
TextField t =
(TextField)parent.h.get("mouseEnter");
t.setText(evt.toString());
return true;
}
public boolean
mouseExit(Event evt,int x,int y) {
TextField t =
(TextField)parent.h.get("mouseExit");
t.setText(evt.toString());
return true;
}
public boolean
mouseMove(Event evt,int x,int y) {
TextField t =
(TextField)parent.h.get("mouseMove");
t.setText(evt.toString());
return true;
}
public boolean mouseUp(Event evt,int x,int y) {
TextField t =
(TextField)parent.h.get("mouseUp");
t.setText(evt.toString());
return true;
}
}
public class AutoEvent extends Applet {
Hashtable h = new Hashtable();
String[] event = {
"keyDown", "keyUp", "lostFocus",
"gotFocus", "mouseDown", "mouseUp",
"mouseMove", "mouseDrag", "mouseEnter",
"mouseExit"
};
MyButton
b1 = new MyButton(this, Color.blue, "test1"),
b2 = new MyButton(this, Color.red, "test2");
public void init() {
setLayout(new GridLayout(event.length+1,2));
for(int i = 0; i < event.length; i++) {
TextField t = new TextField();
t.setEditable(false);
add(new Label(event[i], Label.CENTER));
add(t);
h.put(event[i], t);
}
add(b1);
add(b2);
}
} ///:~
//: Menu1.java
// Menus work only with Frames.
// Shows submenus, checkbox menu items
// and swapping menus.
import java.awt.*;
public class Menu1 extends Frame {
String[] flavors = { "Chocolate", "Strawberry",
"Vanilla Fudge Swirl", "Mint Chip",
"Mocha Almond Fudge", "Rum Raisin",
"Praline Cream", "Mud Pie" };
TextField t = new TextField("No flavor", 30);
MenuBar mb1 = new MenuBar();
Menu f = new Menu("File");
Menu m = new Menu("Flavors");
Menu s = new Menu("Safety");
// Alternative approach:
CheckboxMenuItem[] safety = {
new CheckboxMenuItem("Guard"),
new CheckboxMenuItem("Hide")
};
MenuItem[] file = {
new MenuItem("Open"),
new MenuItem("Exit")
};
// A second menu bar to swap to:
MenuBar mb2 = new MenuBar();
Menu fooBar = new Menu("fooBar");
MenuItem[] other = {
new MenuItem("Foo"),
new MenuItem("Bar"),
new MenuItem("Baz"),
};
Button b = new Button("Swap Menus");
public Menu1() {
for(int i = 0; i < flavors.length; i++) {
m.add(new MenuItem(flavors[i]));
// Add separators at intervals:
if((i+1) % 3 == 0)
m.addSeparator();
}
for(int i = 0; i < safety.length; i++)
s.add(safety[i]);
f.add(s);
for(int i = 0; i < file.length; i++)
f.add(file[i]);
mb1.add(f);
mb1.add(m);
setMenuBar(mb1);
t.setEditable(false);
add("Center", t);
// Set up the system for swapping menus:
add("North", b);
for(int i = 0; i < other.length; i++)
fooBar.add(other[i]);
mb2.add(fooBar);
}
public boolean handleEvent(Event evt) {
if(evt.id == Event.WINDOW_DESTROY)
System.exit(0);
else
return super.handleEvent(evt);
return true;
}
public boolean action(Event evt, Object arg) {
if(evt.target.equals(b)) {
MenuBar m = getMenuBar();
if(m == mb1) setMenuBar(mb2);
else if (m == mb2) setMenuBar(mb1);
}
else if(evt.target instanceof MenuItem) {
if(arg.equals("Open")) {
String s = t.getText();
boolean chosen = false;
for(int i = 0; i < flavors.length; i++)
if(s.equals(flavors[i])) chosen = true;
if(!chosen)
t.setText("Choose a flavor first!");
else
t.setText("Opening "+ s +". Mmm, mm!");
}
else if(evt.target.equals(file[1]))
System.exit(0);
// CheckboxMenuItems cannot use String
// matching; you must match the target:
else if(evt.target.equals(safety[0]))
t.setText("Guard the Ice Cream! " +
"Guarding is " + safety[0].getState());
else if(evt.target.equals(safety[1]))
t.setText("Hide the Ice Cream! " +
"Is it cold? " + safety[1].getState());
else
t.setText(arg.toString());
}
else
return super.action(evt, arg);
return true;
}
public static void main(String[] args) {
Menu1 f = new Menu1();
f.resize(300,200);
f.show();
}
} ///:~
//: ToeTest.java
// Demonstration of dialog boxes
// and creating your own components
import java.awt.*;
class ToeButton extends Canvas {
int state = ToeDialog.BLANK;
ToeDialog parent;
ToeButton(ToeDialog parent) {
this.parent = parent;
}
public void paint(Graphics g) {
int x1 = 0;
int y1 = 0;
int x2 = size().width - 1;
int y2 = size().height - 1;
g.drawRect(x1, y1, x2, y2);
x1 = x2/4;
y1 = y2/4;
int wide = x2/2;
int high = y2/2;
if(state == ToeDialog.XX) {
g.drawLine(x1, y1, x1 + wide, y1 + high);
g.drawLine(x1, y1 + high, x1 + wide, y1);
}
if(state == ToeDialog.OO) {
g.drawOval(x1, y1, x1+wide/2, y1+high/2);
}
}
public boolean
mouseDown(Event evt, int x, int y) {
if(state == ToeDialog.BLANK) {
state = parent.turn;
parent.turn= (parent.turn == ToeDialog.XX ?
ToeDialog.OO : ToeDialog.XX);
}
else
state = (state == ToeDialog.XX ?
ToeDialog.OO : ToeDialog.XX);
repaint();
return true;
}
}
class ToeDialog extends Dialog {
// w = number of cells wide
// h = number of cells high
static final int BLANK = 0;
static final int XX = 1;
static final int OO = 2;
int turn = XX; // Start with x's turn
public ToeDialog(Frame parent, int w, int h) {
super(parent, "The game itself", false);
setLayout(new GridLayout(w, h));
for(int i = 0; i < w * h; i++)
add(new ToeButton(this));
resize(w * 50, h * 50);
}
public boolean handleEvent(Event evt) {
if(evt.id == Event.WINDOW_DESTROY)
dispose();
else
return super.handleEvent(evt);
return true;
}
}
public class ToeTest extends Frame {
TextField rows = new TextField("3");
TextField cols = new TextField("3");
public ToeTest() {
setTitle("Toe Test");
Panel p = new Panel();
p.setLayout(new GridLayout(2,2));
p.add(new Label("Rows", Label.CENTER));
p.add(rows);
p.add(new Label("Columns", Label.CENTER));
p.add(cols);
add("North", p);
add("South", new Button("go"));
}
public boolean handleEvent(Event evt) {
if(evt.id == Event.WINDOW_DESTROY)
System.exit(0);
else
return super.handleEvent(evt);
return true;
}
public boolean action(Event evt, Object arg) {
if(arg.equals("go")) {
Dialog d = new ToeDialog(
this,
Integer.parseInt(rows.getText()),
Integer.parseInt(cols.getText()));
d.show();
}
else
return super.action(evt, arg);
return true;
}
public static void main(String[] args) {
Frame f = new ToeTest();
f.resize(200,100);
f.show();
}
} ///:~
//: FileDialogTest.java
// Demonstration of File dialog boxes
import java.awt.*;
public class FileDialogTest extends Frame {
TextField filename = new TextField();
TextField directory = new TextField();
Button open = new Button("Open");
Button save = new Button("Save");
public FileDialogTest() {
setTitle("File Dialog Test");
Panel p = new Panel();
p.setLayout(new FlowLayout());
p.add(open);
p.add(save);
add("South", p);
directory.setEditable(false);
filename.setEditable(false);
p = new Panel();
p.setLayout(new GridLayout(2,1));
p.add(filename);
p.add(directory);
add("North", p);
}
public boolean handleEvent(Event evt) {
if(evt.id == Event.WINDOW_DESTROY)
System.exit(0);
else
return super.handleEvent(evt);
return true;
}
public boolean action(Event evt, Object arg) {
if(evt.target.equals(open)) {
// Two arguments, defaults to open file:
FileDialog d = new FileDialog(this,
"What file do you want to open?");
d.setFile("*.java"); // Filename filter
d.setDirectory("."); // Current directory
d.show();
String openFile;
if((openFile = d.getFile()) != null) {
filename.setText(openFile);
directory.setText(d.getDirectory());
} else {
filename.setText("You pressed cancel");
directory.setText("");
}
}
else if(evt.target.equals(save)) {
FileDialog d = new FileDialog(this,
"What file do you want to save?",
FileDialog.SAVE);
d.setFile("*.java");
d.setDirectory(".");
d.show();
String saveFile;
if((saveFile = d.getFile()) != null) {
filename.setText(saveFile);
directory.setText(d.getDirectory());
} else {
filename.setText("You pressed cancel");
directory.setText("");
}
}
else
return super.action(evt, arg);
return true;
}
public static void main(String[] args) {
Frame f = new FileDialogTest();
f.resize(250,110);
f.show();
}
} ///:~
//: Button2New.java
// Capturing button presses
import java.awt.*;
import java.awt.event.*; // Must add this
import java.applet.*;
public class Button2New extends Applet {
Button
b1 = new Button("Button 1"),
b2 = new Button("Button 2");
public void init() {
b1.addActionListener(new B1());
b2.addActionListener(new B2());
add(b1);
add(b2);
}
class B1 implements ActionListener {
public void actionPerformed(ActionEvent e) {
getAppletContext().showStatus("Button 1");
}
}
class B2 implements ActionListener {
public void actionPerformed(ActionEvent e) {
getAppletContext().showStatus("Button 2");
}
}
/* The old way:
public boolean action(Event evt, Object arg) {
if(evt.target.equals(b1))
getAppletContext().showStatus("Button 1");
else if(evt.target.equals(b2))
getAppletContext().showStatus("Button 2");
// Let the base class handle it:
else
return super.action(evt, arg);
return true; // We've handled it here
}
*/
} ///:~
|
Event, listener interface and add-
and remove-methods |
Components supporting this
event |
|---|---|
|
ActionEvent |
Button, List,
TextField, MenuItem, and its derivatives including CheckboxMenuItem,
Menu, and PopupMenu |
|
AdjustmentEvent |
Scrollbar |
|
ComponentEvent |
Component and its
derivatives, including Button, Canvas, Checkbox,
Choice, Container, Panel, Applet, ScrollPane,
Window, Dialog, FileDialog, Frame, Label,
List, Scrollbar, TextArea, and
TextField |
|
ContainerEvent |
Container and its
derivatives, including Panel, Applet, ScrollPane,
Window, Dialog, FileDialog, and
Frame |
|
FocusEvent |
Component and its
derivatives, including Button, Canvas, Checkbox,
Choice, Container, Panel, Applet, ScrollPane,
Window, Dialog, FileDialog, Frame Label,
List, Scrollbar, TextArea, and
TextField |
|
KeyEvent |
Component and its
derivatives, including Button, Canvas, Checkbox,
Choice, Container, Panel, Applet, ScrollPane,
Window, Dialog, FileDialog, Frame, Label,
List, Scrollbar, TextArea, and
TextField |
|
MouseEvent (for both clicks
and
motion) |
Component and its
derivatives, including Button, Canvas, Checkbox,
Choice, Container, Panel, Applet, ScrollPane,
Window, Dialog, FileDialog, Frame, Label,
List, Scrollbar, TextArea, and
TextField |
|
MouseEvent[55]
(for both clicks and
motion) |
Component and its
derivatives, including Button, Canvas, Checkbox,
Choice, Container, Panel, Applet, ScrollPane,
Window, Dialog, FileDialog, Frame, Label,
List, Scrollbar, TextArea, and
TextField |
|
WindowEvent |
Window and its derivatives,
including Dialog, FileDialog, and Frame |
|
ItemEvent |
Checkbox,
CheckboxMenuItem, Choice, List, and anything that
implements the ItemSelectable interface |
|
TextEvent |
Anything derived from
TextComponent, including TextArea and
TextField |
|
Component type |
Events supported by this
component |
|---|---|
|
Adjustable |
AdjustmentEvent |
|
Applet |
ContainerEvent, FocusEvent,
KeyEvent, MouseEvent, ComponentEvent |
|
Button |
ActionEvent, FocusEvent,
KeyEvent, MouseEvent, ComponentEvent |
|
Canvas |
FocusEvent, KeyEvent,
MouseEvent, ComponentEvent |
|
Checkbox |
ItemEvent, FocusEvent, KeyEvent,
MouseEvent, ComponentEvent |
|
CheckboxMenuItem |
ActionEvent,
ItemEvent |
|
Choice |
ItemEvent, FocusEvent, KeyEvent,
MouseEvent, ComponentEvent |
|
Component |
FocusEvent, KeyEvent,
MouseEvent, ComponentEvent |
|
Container |
ContainerEvent, FocusEvent,
KeyEvent, MouseEvent, ComponentEvent |
|
Dialog |
ContainerEvent, WindowEvent,
FocusEvent, KeyEvent, MouseEvent, ComponentEvent |
|
FileDialog |
ContainerEvent, WindowEvent,
FocusEvent, KeyEvent, MouseEvent, ComponentEvent |
|
Frame |
ContainerEvent, WindowEvent,
FocusEvent, KeyEvent, MouseEvent, ComponentEvent |
|
Label |
FocusEvent, KeyEvent,
MouseEvent, ComponentEvent |
|
List |
ActionEvent, FocusEvent,
KeyEvent, MouseEvent, ItemEvent, ComponentEvent |
|
Menu |
ActionEvent |
|
MenuItem |
ActionEvent |
|
Panel |
ContainerEvent, FocusEvent,
KeyEvent, MouseEvent, ComponentEvent |
|
PopupMenu |
ActionEvent |
|
Scrollbar |
AdjustmentEvent, FocusEvent,
KeyEvent, MouseEvent, ComponentEvent |
|
ScrollPane |
ContainerEvent, FocusEvent,
KeyEvent, MouseEvent, ComponentEvent |
|
TextArea |
TextEvent, FocusEvent, KeyEvent,
MouseEvent, ComponentEvent |
|
TextComponent |
TextEvent, FocusEvent, KeyEvent,
MouseEvent, ComponentEvent |
|
TextField |
ActionEvent, TextEvent,
FocusEvent, KeyEvent, MouseEvent, ComponentEvent |
|
Window |
ContainerEvent, WindowEvent,
FocusEvent, KeyEvent, MouseEvent, ComponentEvent |
|
Listener
interface |
Methods in
interface |
|---|---|
|
ActionListener |
actionPerformed(ActionEvent) |
|
AdjustmentListener |
adjustmentValueChanged( |
|
ComponentListener |
componentHidden(ComponentEvent) |
|
ContainerListener |
componentAdded(ContainerEvent) |
|
FocusListener |
focusGained(FocusEvent) |
|
KeyListener |
keyPressed(KeyEvent) |
|
MouseListener |
mouseClicked(MouseEvent) |
|
MouseMotionListener |
mouseDragged(MouseEvent) |
|
WindowListener |
windowOpened(WindowEvent) |
|
ItemListener |
itemStateChanged(ItemEvent) |
|
TextListener |
textValueChanged(TextEvent) |
class MyWindowListener extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
class MyWindowListener extends WindowAdapter {
public void WindowClosing(WindowEvent e) {
System.exit(0);
}
}
//: Button2NewB.java
// An application and an applet
import java.awt.*;
import java.awt.event.*; // Must add this
import java.applet.*;
public class Button2NewB extends Applet {
Button
b1 = new Button("Button 1"),
b2 = new Button("Button 2");
TextField t = new TextField(20);
public void init() {
b1.addActionListener(new B1());
b2.addActionListener(new B2());
add(b1);
add(b2);
add(t);
}
class B1 implements ActionListener {
public void actionPerformed(ActionEvent e) {
t.setText("Button 1");
}
}
class B2 implements ActionListener {
public void actionPerformed(ActionEvent e) {
t.setText("Button 2");
}
}
// To close the application:
static class WL extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
// A main() for the application:
public static void main(String[] args) {
Button2NewB applet = new Button2NewB();
Frame aFrame = new Frame("Button2NewB");
aFrame.addWindowListener(new WL());
aFrame.add(applet, BorderLayout.CENTER);
aFrame.setSize(300,200);
applet.init();
applet.start();
aFrame.setVisible(true);
}
} ///:~
aFrame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});