第十三章 创建窗口和程序片
在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); } });
<head><title>Button2NewB Example Applet </title></head> <body> <applet code="Button2NewB.class" archive="Button2NewB.jar" width=200 height=150> </applet> </body>
//: TextNew.java // Text fields with Java 1.1 events import java.awt.*; import java.awt.event.*; import java.applet.*; public class TextNew extends Applet { Button b1 = new Button("Get Text"), b2 = new Button("Set Text"); TextField t1 = new TextField(30), t2 = new TextField(30), t3 = new TextField(30); String s = new String(); public void init() { b1.addActionListener(new B1()); b2.addActionListener(new B2()); t1.addTextListener(new T1()); t1.addActionListener(new T1A()); t1.addKeyListener(new T1K()); add(b1); add(b2); add(t1); add(t2); add(t3); } class T1 implements TextListener { public void textValueChanged(TextEvent e) { t2.setText(t1.getText()); } } class T1A implements ActionListener { private int count = 0; public void actionPerformed(ActionEvent e) { t3.setText("t1 Action Event " + count++); } } class T1K extends KeyAdapter { public void keyTyped(KeyEvent e) { String ts = t1.getText(); if(e.getKeyChar() == KeyEvent.VK_BACK_SPACE) { // Ensure it's not empty: if( ts.length() > 0) { ts = ts.substring(0, ts.length() - 1); t1.setText(ts); } } else t1.setText( t1.getText() + Character.toUpperCase( e.getKeyChar())); t1.setCaretPosition( t1.getText().length()); // Stop regular character from appearing: e.consume(); } } class B1 implements ActionListener { public void actionPerformed(ActionEvent e) { s = t1.getSelectedText(); if(s.length() == 0) s = t1.getText(); t1.setEditable(true); } } class B2 implements ActionListener { public void actionPerformed(ActionEvent e) { t1.setText("Inserted by Button 2: " + s); t1.setEditable(false); } } public static void main(String[] args) { TextNew applet = new TextNew(); Frame aFrame = new Frame("TextNew"); aFrame.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); aFrame.add(applet, BorderLayout.CENTER); aFrame.setSize(300,200); applet.init(); applet.start(); aFrame.setVisible(true); } } ///:~
class T1 implements TextListener { public void textValueChanged(TextEvent e) { t2.setText(t1.getText()); } }
//: TextAreaNew.java // Controlling scrollbars with the TextArea // component in Java 1.1 import java.awt.*; import java.awt.event.*; import java.applet.*; public class TextAreaNew 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); TextArea t3 = new TextArea("t3", 1, 30, TextArea.SCROLLBARS_NONE); TextArea t4 = new TextArea("t4", 10, 10, TextArea.SCROLLBARS_VERTICAL_ONLY); TextArea t5 = new TextArea("t5", 4, 30, TextArea.SCROLLBARS_HORIZONTAL_ONLY); TextArea t6 = new TextArea("t6", 10, 10, TextArea.SCROLLBARS_BOTH); public void init() { b1.addActionListener(new B1L()); add(b1); add(t1); b2.addActionListener(new B2L()); add(b2); add(t2); b3.addActionListener(new B3L()); add(b3); b4.addActionListener(new B4L()); add(b4); add(t3); add(t4); add(t5); add(t6); } class B1L implements ActionListener { public void actionPerformed(ActionEvent e) { t5.append(t1.getText() + "\n"); } } class B2L implements ActionListener { public void actionPerformed(ActionEvent e) { t2.setText("Inserted by Button 2"); t2.append(": " + t1.getText()); t5.append(t2.getText() + "\n"); } } class B3L implements ActionListener { public void actionPerformed(ActionEvent e) { String s = " Replacement "; t2.replaceRange(s, 3, 3 + s.length()); } } class B4L implements ActionListener { public void actionPerformed(ActionEvent e) { t2.insert(" Inserted ", 10); } } public static void main(String[] args) { TextAreaNew applet = new TextAreaNew(); Frame aFrame = new Frame("TextAreaNew"); aFrame.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); aFrame.add(applet, BorderLayout.CENTER); aFrame.setSize(300,725); applet.init(); applet.start(); aFrame.setVisible(true); } } ///:~
//: RadioCheckNew.java // Radio buttons and Check Boxes in Java 1.1 import java.awt.*; import java.awt.event.*; import java.applet.*; public class RadioCheckNew extends Applet { TextField t = new TextField(30); Checkbox[] cb = { new Checkbox("Check Box 1"), new Checkbox("Check Box 2"), new Checkbox("Check Box 3") }; CheckboxGroup g = new CheckboxGroup(); Checkbox cb4 = new Checkbox("four", g, false), cb5 = new Checkbox("five", g, true), cb6 = new Checkbox("six", g, false); public void init() { t.setEditable(false); add(t); ILCheck il = new ILCheck(); for(int i = 0; i < cb.length; i++) { cb[i].addItemListener(il); add(cb[i]); } cb4.addItemListener(new IL4()); cb5.addItemListener(new IL5()); cb6.addItemListener(new IL6()); add(cb4); add(cb5); add(cb6); } // Checking the source: class ILCheck implements ItemListener { public void itemStateChanged(ItemEvent e) { for(int i = 0; i < cb.length; i++) { if(e.getSource().equals(cb[i])) { t.setText("Check box " + (i + 1)); return; } } } } // vs. an individual class for each item: class IL4 implements ItemListener { public void itemStateChanged(ItemEvent e) { t.setText("Radio button four"); } } class IL5 implements ItemListener { public void itemStateChanged(ItemEvent e) { t.setText("Radio button five"); } } class IL6 implements ItemListener { public void itemStateChanged(ItemEvent e) { t.setText("Radio button six"); } } public static void main(String[] args) { RadioCheckNew applet = new RadioCheckNew(); Frame aFrame = new Frame("RadioCheckNew"); aFrame.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); aFrame.add(applet, BorderLayout.CENTER); aFrame.setSize(300,200); applet.init(); applet.start(); aFrame.setVisible(true); } } ///:~
//: ChoiceNew.java // Drop-down lists with Java 1.1 import java.awt.*; import java.awt.event.*; import java.applet.*; public class ChoiceNew extends Applet { String[] description = { "Ebullient", "Obtuse", "Recalcitrant", "Brilliant", "Somnescent", "Timorous", "Florid", "Putrescent" }; TextField t = new TextField(100); 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); c.addItemListener(new CL()); b.addActionListener(new BL()); } class CL implements ItemListener { public void itemStateChanged(ItemEvent e) { t.setText("index: " + c.getSelectedIndex() + " " + e.toString()); } } class BL implements ActionListener { public void actionPerformed(ActionEvent e) { if(count < description.length) c.addItem(description[count++]); } } public static void main(String[] args) { ChoiceNew applet = new ChoiceNew(); Frame aFrame = new Frame("ChoiceNew"); aFrame.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); aFrame.add(applet, BorderLayout.CENTER); aFrame.setSize(750,100); applet.init(); applet.start(); aFrame.setVisible(true); } } ///:~
//: ListNew.java // Java 1.1 Lists are easier to use import java.awt.*; import java.awt.event.*; import java.applet.*; public class ListNew 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); lst.addItemListener(new LL()); b.addActionListener(new BL()); } class LL implements ItemListener { public void itemStateChanged(ItemEvent e) { t.setText(""); String[] items = lst.getSelectedItems(); for(int i = 0; i < items.length; i++) t.append(items[i] + "\n"); } } class BL implements ActionListener { public void actionPerformed(ActionEvent e) { if(count < flavors.length) lst.addItem(flavors[count++], 0); } } public static void main(String[] args) { ListNew applet = new ListNew(); Frame aFrame = new Frame("ListNew"); aFrame.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); aFrame.add(applet, BorderLayout.CENTER); aFrame.setSize(300,200); applet.init(); applet.start(); aFrame.setVisible(true); } } ///:~
//: MenuNew.java // Menus in Java 1.1 import java.awt.*; import java.awt.event.*; public class MenuNew 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 = { // No menu shortcut: new MenuItem("Open"), // Adding a menu shortcut is very simple: new MenuItem("Exit", new MenuShortcut(KeyEvent.VK_E)) }; // 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"), }; // Initialization code: { ML ml = new ML(); CMIL cmil = new CMIL(); safety[0].setActionCommand("Guard"); safety[0].addItemListener(cmil); safety[1].setActionCommand("Hide"); safety[1].addItemListener(cmil); file[0].setActionCommand("Open"); file[0].addActionListener(ml); file[1].setActionCommand("Exit"); file[1].addActionListener(ml); other[0].addActionListener(new FooL()); other[1].addActionListener(new BarL()); other[2].addActionListener(new BazL()); } Button b = new Button("Swap Menus"); public MenuNew() { FL fl = new FL(); for(int i = 0; i < flavors.length; i++) { MenuItem mi = new MenuItem(flavors[i]); mi.addActionListener(fl); m.add(mi); // 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(t, BorderLayout.CENTER); // Set up the system for swapping menus: b.addActionListener(new BL()); add(b, BorderLayout.NORTH); for(int i = 0; i < other.length; i++) fooBar.add(other[i]); mb2.add(fooBar); } class BL implements ActionListener { public void actionPerformed(ActionEvent e) { MenuBar m = getMenuBar(); if(m == mb1) setMenuBar(mb2); else if (m == mb2) setMenuBar(mb1); } } class ML implements ActionListener { public void actionPerformed(ActionEvent e) { MenuItem target = (MenuItem)e.getSource(); String actionCommand = target.getActionCommand(); if(actionCommand.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(actionCommand.equals("Exit")) { dispatchEvent( new WindowEvent(MenuNew.this, WindowEvent.WINDOW_CLOSING)); } } } class FL implements ActionListener { public void actionPerformed(ActionEvent e) { MenuItem target = (MenuItem)e.getSource(); t.setText(target.getLabel()); } } // Alternatively, you can create a different // class for each different MenuItem. Then you // Don't have to figure out which one it is: class FooL implements ActionListener { public void actionPerformed(ActionEvent e) { t.setText("Foo selected"); } } class BarL implements ActionListener { public void actionPerformed(ActionEvent e) { t.setText("Bar selected"); } } class BazL implements ActionListener { public void actionPerformed(ActionEvent e) { t.setText("Baz selected"); } } class CMIL implements ItemListener { public void itemStateChanged(ItemEvent e) { CheckboxMenuItem target = (CheckboxMenuItem)e.getSource(); String actionCommand = target.getActionCommand(); if(actionCommand.equals("Guard")) t.setText("Guard the Ice Cream! " + "Guarding is " + target.getState()); else if(actionCommand.equals("Hide")) t.setText("Hide the Ice Cream! " + "Is it cold? " + target.getState()); } } public static void main(String[] args) { MenuNew f = new MenuNew(); f.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); f.setSize(300,200); f.setVisible(true); } } ///:~
//: ToeTestNew.java // Demonstration of dialog boxes // and creating your own components import java.awt.*; import java.awt.event.*; public class ToeTestNew extends Frame { TextField rows = new TextField("3"); TextField cols = new TextField("3"); public ToeTestNew() { 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(p, BorderLayout.NORTH); Button b = new Button("go"); b.addActionListener(new BL()); add(b, BorderLayout.SOUTH); } static final int BLANK = 0; static final int XX = 1; static final int OO = 2; class ToeDialog extends Dialog { // w = number of cells wide // h = number of cells high int turn = XX; // Start with x's turn public ToeDialog(int w, int h) { super(ToeTestNew.this, "The game itself", false); setLayout(new GridLayout(w, h)); for(int i = 0; i < w * h; i++) add(new ToeButton()); setSize(w * 50, h * 50); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e){ dispose(); } }); } class ToeButton extends Canvas { int state = BLANK; ToeButton() { addMouseListener(new ML()); } public void paint(Graphics g) { int x1 = 0; int y1 = 0; int x2 = getSize().width - 1; int y2 = getSize().height - 1; g.drawRect(x1, y1, x2, y2); x1 = x2/4; y1 = y2/4; int wide = x2/2; int high = y2/2; if(state == XX) { g.drawLine(x1, y1, x1 + wide, y1 + high); g.drawLine(x1, y1 + high, x1 + wide, y1); } if(state == OO) { g.drawOval(x1, y1, x1 + wide/2, y1 + high/2); } } class ML extends MouseAdapter { public void mousePressed(MouseEvent e) { if(state == BLANK) { state = turn; turn = (turn == XX ? OO : XX); } else state = (state == XX ? OO : XX); repaint(); } } } } class BL implements ActionListener { public void actionPerformed(ActionEvent e) { Dialog d = new ToeDialog( Integer.parseInt(rows.getText()), Integer.parseInt(cols.getText())); d.show(); } } public static void main(String[] args) { Frame f = new ToeTestNew(); f.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); f.setSize(200,100); f.setVisible(true); } } ///:~
//: FileDialogNew.java // Demonstration of File dialog boxes import java.awt.*; import java.awt.event.*; public class FileDialogNew extends Frame { TextField filename = new TextField(); TextField directory = new TextField(); Button open = new Button("Open"); Button save = new Button("Save"); public FileDialogNew() { setTitle("File Dialog Test"); Panel p = new Panel(); p.setLayout(new FlowLayout()); open.addActionListener(new OpenL()); p.add(open); save.addActionListener(new SaveL()); p.add(save); add(p, BorderLayout.SOUTH); directory.setEditable(false); filename.setEditable(false); p = new Panel(); p.setLayout(new GridLayout(2,1)); p.add(filename); p.add(directory); add(p, BorderLayout.NORTH); } class OpenL implements ActionListener { public void actionPerformed(ActionEvent e) { // Two arguments, defaults to open file: FileDialog d = new FileDialog( FileDialogNew.this, "What file do you want to open?"); d.setFile("*.java"); d.setDirectory("."); // Current directory d.show(); String yourFile = "*.*"; if((yourFile = d.getFile()) != null) { filename.setText(yourFile); directory.setText(d.getDirectory()); } else { filename.setText("You pressed cancel"); directory.setText(""); } } } class SaveL implements ActionListener { public void actionPerformed(ActionEvent e) { FileDialog d = new FileDialog( FileDialogNew.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(""); } } } public static void main(String[] args) { Frame f = new FileDialogNew(); f.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); f.setSize(250,110); f.setVisible(true); } } ///:~
//: DynamicEvents.java // The new Java 1.1 event model allows you to // change event behavior dynamically. Also // demonstrates multiple actions for an event. import java.awt.*; import java.awt.event.*; import java.util.*; public class DynamicEvents extends Frame { Vector v = new Vector(); int i = 0; Button b1 = new Button("Button 1"), b2 = new Button("Button 2"); public DynamicEvents() { setLayout(new FlowLayout()); b1.addActionListener(new B()); b1.addActionListener(new B1()); b2.addActionListener(new B()); b2.addActionListener(new B2()); add(b1); add(b2); } class B implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("A button was pressed"); } } class CountListener implements ActionListener { int index; public CountListener(int i) { index = i; } public void actionPerformed(ActionEvent e) { System.out.println( "Counted Listener " + index); } } class B1 implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("Button 1 pressed"); ActionListener a = new CountListener(i++); v.addElement(a); b2.addActionListener(a); } } class B2 implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("Button 2 pressed"); int end = v.size() -1; if(end >= 0) { b2.removeActionListener( (ActionListener)v.elementAt(end)); v.removeElementAt(end); } } } public static void main(String[] args) { Frame f = new DynamicEvents(); f.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e){ System.exit(0); } }); f.setSize(300,200); f.show(); } } ///:~
//: Separation.java // Separating GUI logic and business objects import java.awt.*; import java.awt.event.*; import java.applet.*; class BusinessLogic { private int modifier; BusinessLogic(int mod) { modifier = mod; } public void setModifier(int mod) { modifier = mod; } public int getModifier() { return modifier; } // Some business operations: public int calculation1(int arg) { return arg * modifier; } public int calculation2(int arg) { return arg + modifier; } } public class Separation extends Applet { TextField t = new TextField(20), mod = new TextField(20); BusinessLogic bl = new BusinessLogic(2); Button calc1 = new Button("Calculation 1"), calc2 = new Button("Calculation 2"); public void init() { add(t); calc1.addActionListener(new Calc1L()); calc2.addActionListener(new Calc2L()); add(calc1); add(calc2); mod.addTextListener(new ModL()); add(new Label("Modifier:")); add(mod); } static int getValue(TextField tf) { try { return Integer.parseInt(tf.getText()); } catch(NumberFormatException e) { return 0; } } class Calc1L implements ActionListener { public void actionPerformed(ActionEvent e) { t.setText(Integer.toString( bl.calculation1(getValue(t)))); } } class Calc2L implements ActionListener { public void actionPerformed(ActionEvent e) { t.setText(Integer.toString( bl.calculation2(getValue(t)))); } } class ModL implements TextListener { public void textValueChanged(TextEvent e) { bl.setModifier(getValue(mod)); } } public static void main(String[] args) { Separation applet = new Separation(); Frame aFrame = new Frame("Separation"); aFrame.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); aFrame.add(applet, BorderLayout.CENTER); aFrame.setSize(200,200); applet.init(); applet.start(); aFrame.setVisible(true); } } ///:~
//: GoodIdea.java // The best way to design classes using the new // Java 1.1 event model: use an inner class for // each different event. This maximizes // flexibility and modularity. import java.awt.*; import java.awt.event.*; import java.util.*; public class GoodIdea extends Frame { Button b1 = new Button("Button 1"), b2 = new Button("Button 2"); public GoodIdea() { setLayout(new FlowLayout()); b1.addActionListener(new B1L()); b2.addActionListener(new B2L()); add(b1); add(b2); } public class B1L implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("Button 1 pressed"); } } public class B2L implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("Button 2 pressed"); } } public static void main(String[] args) { Frame f = new GoodIdea(); f.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e){ System.out.println("Window Closing"); System.exit(0); } }); f.setSize(300,200); f.setVisible(true); } } ///:~
//: BadIdea1.java // Some literature recommends this approach, // but it's missing the point of the new event // model in Java 1.1 import java.awt.*; import java.awt.event.*; import java.util.*; public class BadIdea1 extends Frame implements ActionListener, WindowListener { Button b1 = new Button("Button 1"), b2 = new Button("Button 2"); public BadIdea1() { setLayout(new FlowLayout()); addWindowListener(this); b1.addActionListener(this); b2.addActionListener(this); add(b1); add(b2); } public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if(source == b1) System.out.println("Button 1 pressed"); else if(source == b2) System.out.println("Button 2 pressed"); else System.out.println("Something else"); } public void windowClosing(WindowEvent e) { System.out.println("Window Closing"); System.exit(0); } public void windowClosed(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} public void windowOpened(WindowEvent e) {} public static void main(String[] args) { Frame f = new BadIdea1(); f.setSize(300,200); f.setVisible(true); } } ///:~
//: BadIdea2.java // An improvement over BadIdea1.java, since it // uses the WindowAdapter as an inner class // instead of implementing all the methods of // WindowListener, but still misses the // valuable modularity of inner classes import java.awt.*; import java.awt.event.*; import java.util.*; public class BadIdea2 extends Frame implements ActionListener { Button b1 = new Button("Button 1"), b2 = new Button("Button 2"); public BadIdea2() { setLayout(new FlowLayout()); addWindowListener(new WL()); b1.addActionListener(this); b2.addActionListener(this); add(b1); add(b2); } public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if(source == b1) System.out.println("Button 1 pressed"); else if(source == b2) System.out.println("Button 2 pressed"); else System.out.println("Something else"); } class WL extends WindowAdapter { public void windowClosing(WindowEvent e) { System.out.println("Window Closing"); System.exit(0); } } public static void main(String[] args) { Frame f = new BadIdea2(); f.setSize(300,200); f.setVisible(true); } } ///:~
//: GoodTechnique.java // Your first choice when overriding components // should be to install listeners. The code is // much safer, more modular and maintainable. import java.awt.*; import java.awt.event.*; class Display { public static final int EVENT = 0, COMPONENT = 1, MOUSE = 2, MOUSE_MOVE = 3, FOCUS = 4, KEY = 5, ACTION = 6, LAST = 7; public String[] evnt; Display() { evnt = new String[LAST]; for(int i = 0; i < LAST; i++) evnt[i] = new String(); } public void show(Graphics g) { for(int i = 0; i < LAST; i++) g.drawString(evnt[i], 0, 10 * i + 10); } } class EnabledPanel extends Panel { Color c; int id; Display display = new Display(); public EnabledPanel(int i, Color mc) { id = i; c = mc; setLayout(new BorderLayout()); add(new MyButton(), BorderLayout.SOUTH); addComponentListener(new CL()); addFocusListener(new FL()); addKeyListener(new KL()); addMouseListener(new ML()); addMouseMotionListener(new MML()); } // To eliminate flicker: public void update(Graphics g) { paint(g); } public void paint(Graphics g) { g.setColor(c); Dimension s = getSize(); g.fillRect(0, 0, s.width, s.height); g.setColor(Color.black); display.show(g); } // Don't need to enable anything for this: public void processEvent(AWTEvent e) { display.evnt[Display.EVENT]= e.toString(); repaint(); super.processEvent(e); } class CL implements ComponentListener { public void componentMoved(ComponentEvent e){ display.evnt[Display.COMPONENT] = "Component moved"; repaint(); } public void componentResized(ComponentEvent e) { display.evnt[Display.COMPONENT] = "Component resized"; repaint(); } public void componentHidden(ComponentEvent e) { display.evnt[Display.COMPONENT] = "Component hidden"; repaint(); } public void componentShown(ComponentEvent e){ display.evnt[Display.COMPONENT] = "Component shown"; repaint(); } } class FL implements FocusListener { public void focusGained(FocusEvent e) { display.evnt[Display.FOCUS] = "FOCUS gained"; repaint(); } public void focusLost(FocusEvent e) { display.evnt[Display.FOCUS] = "FOCUS lost"; repaint(); } } class KL implements KeyListener { public void keyPressed(KeyEvent e) { display.evnt[Display.KEY] = "KEY pressed: "; showCode(e); } public void keyReleased(KeyEvent e) { display.evnt[Display.KEY] = "KEY released: "; showCode(e); } public void keyTyped(KeyEvent e) { display.evnt[Display.KEY] = "KEY typed: "; showCode(e); } void showCode(KeyEvent e) { int code = e.getKeyCode(); display.evnt[Display.KEY] += KeyEvent.getKeyText(code); repaint(); } } class ML implements MouseListener { public void mouseClicked(MouseEvent e) { requestFocus(); // Get FOCUS on click display.evnt[Display.MOUSE] = "MOUSE clicked"; showMouse(e); } public void mousePressed(MouseEvent e) { display.evnt[Display.MOUSE] = "MOUSE pressed"; showMouse(e); } public void mouseReleased(MouseEvent e) { display.evnt[Display.MOUSE] = "MOUSE released"; showMouse(e); } public void mouseEntered(MouseEvent e) { display.evnt[Display.MOUSE] = "MOUSE entered"; showMouse(e); } public void mouseExited(MouseEvent e) { display.evnt[Display.MOUSE] = "MOUSE exited"; showMouse(e); } void showMouse(MouseEvent e) { display.evnt[Display.MOUSE] += ", x = " + e.getX() + ", y = " + e.getY(); repaint(); } } class MML implements MouseMotionListener { public void mouseDragged(MouseEvent e) { display.evnt[Display.MOUSE_MOVE] = "MOUSE dragged"; showMouse(e); } public void mouseMoved(MouseEvent e) { display.evnt[Display.MOUSE_MOVE] = "MOUSE moved"; showMouse(e); } void showMouse(MouseEvent e) { display.evnt[Display.MOUSE_MOVE] += ", x = " + e.getX() + ", y = " + e.getY(); repaint(); } } } class MyButton extends Button { int clickCounter; String label = ""; public MyButton() { addActionListener(new AL()); } public void paint(Graphics g) { g.setColor(Color.green); Dimension s = getSize(); g.fillRect(0, 0, s.width, s.height); g.setColor(Color.black); g.drawRect(0, 0, s.width - 1, s.height - 1); drawLabel(g); } private void drawLabel(Graphics g) { FontMetrics fm = g.getFontMetrics(); int width = fm.stringWidth(label); int height = fm.getHeight(); int ascent = fm.getAscent(); int leading = fm.getLeading(); int horizMargin = (getSize().width - width)/2; int verMargin = (getSize().height - height)/2; g.setColor(Color.red); g.drawString(label, horizMargin, verMargin + ascent + leading); } class AL implements ActionListener { public void actionPerformed(ActionEvent e) { clickCounter++; label = "click #" + clickCounter + " " + e.toString(); repaint(); } } } public class GoodTechnique extends Frame { GoodTechnique() { setLayout(new GridLayout(2,2)); add(new EnabledPanel(1, Color.cyan)); add(new EnabledPanel(2, Color.lightGray)); add(new EnabledPanel(3, Color.yellow)); } public static void main(String[] args) { Frame f = new GoodTechnique(); f.setTitle("Good Technique"); f.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e){ System.out.println(e); System.out.println("Window Closing"); System.exit(0); } }); f.setSize(700,700); f.setVisible(true); } } ///:~
//: BadTechnique.java // It's possible to override components this way, // but the listener approach is much better, so // why would you? import java.awt.*; import java.awt.event.*; class Display { public static final int EVENT = 0, COMPONENT = 1, MOUSE = 2, MOUSE_MOVE = 3, FOCUS = 4, KEY = 5, ACTION = 6, LAST = 7; public String[] evnt; Display() { evnt = new String[LAST]; for(int i = 0; i < LAST; i++) evnt[i] = new String(); } public void show(Graphics g) { for(int i = 0; i < LAST; i++) g.drawString(evnt[i], 0, 10 * i + 10); } } class EnabledPanel extends Panel { Color c; int id; Display display = new Display(); public EnabledPanel(int i, Color mc) { id = i; c = mc; setLayout(new BorderLayout()); add(new MyButton(), BorderLayout.SOUTH); // Type checking is lost. You can enable and // process events that the component doesn't // capture: enableEvents( // Panel doesn't handle these: AWTEvent.ACTION_EVENT_MASK | AWTEvent.ADJUSTMENT_EVENT_MASK | AWTEvent.ITEM_EVENT_MASK | AWTEvent.TEXT_EVENT_MASK | AWTEvent.WINDOW_EVENT_MASK | // Panel can handle these: AWTEvent.COMPONENT_EVENT_MASK | AWTEvent.FOCUS_EVENT_MASK | AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.CONTAINER_EVENT_MASK); // You can enable an event without // overriding its process method. } // To eliminate flicker: public void update(Graphics g) { paint(g); } public void paint(Graphics g) { g.setColor(c); Dimension s = getSize(); g.fillRect(0, 0, s.width, s.height); g.setColor(Color.black); display.show(g); } public void processEvent(AWTEvent e) { display.evnt[Display.EVENT]= e.toString(); repaint(); super.processEvent(e); } public void processComponentEvent(ComponentEvent e) { switch(e.getID()) { case ComponentEvent.COMPONENT_MOVED: display.evnt[Display.COMPONENT] = "Component moved"; break; case ComponentEvent.COMPONENT_RESIZED: display.evnt[Display.COMPONENT] = "Component resized"; break; case ComponentEvent.COMPONENT_HIDDEN: display.evnt[Display.COMPONENT] = "Component hidden"; break; case ComponentEvent.COMPONENT_SHOWN: display.evnt[Display.COMPONENT] = "Component shown"; break; default: } repaint(); // Must always remember to call the "super" // version of whatever you override: super.processComponentEvent(e); } public void processFocusEvent(FocusEvent e) { switch(e.getID()) { case FocusEvent.FOCUS_GAINED: display.evnt[Display.FOCUS] = "FOCUS gained"; break; case FocusEvent.FOCUS_LOST: display.evnt[Display.FOCUS] = "FOCUS lost"; break; default: } repaint(); super.processFocusEvent(e); } public void processKeyEvent(KeyEvent e) { switch(e.getID()) { case KeyEvent.KEY_PRESSED: display.evnt[Display.KEY] = "KEY pressed: "; break; case KeyEvent.KEY_RELEASED: display.evnt[Display.KEY] = "KEY released: "; break; case KeyEvent.KEY_TYPED: display.evnt[Display.KEY] = "KEY typed: "; break; default: } int code = e.getKeyCode(); display.evnt[Display.KEY] += KeyEvent.getKeyText(code); repaint(); super.processKeyEvent(e); } public void processMouseEvent(MouseEvent e) { switch(e.getID()) { case MouseEvent.MOUSE_CLICKED: requestFocus(); // Get FOCUS on click display.evnt[Display.MOUSE] = "MOUSE clicked"; break; case MouseEvent.MOUSE_PRESSED: display.evnt[Display.MOUSE] = "MOUSE pressed"; break; case MouseEvent.MOUSE_RELEASED: display.evnt[Display.MOUSE] = "MOUSE released"; break; case MouseEvent.MOUSE_ENTERED: display.evnt[Display.MOUSE] = "MOUSE entered"; break; case MouseEvent.MOUSE_EXITED: display.evnt[Display.MOUSE] = "MOUSE exited"; break; default: } display.evnt[Display.MOUSE] += ", x = " + e.getX() + ", y = " + e.getY(); repaint(); super.processMouseEvent(e); } public void processMouseMotionEvent(MouseEvent e) { switch(e.getID()) { case MouseEvent.MOUSE_DRAGGED: display.evnt[Display.MOUSE_MOVE] = "MOUSE dragged"; break; case MouseEvent.MOUSE_MOVED: display.evnt[Display.MOUSE_MOVE] = "MOUSE moved"; break; default: } display.evnt[Display.MOUSE_MOVE] += ", x = " + e.getX() + ", y = " + e.getY(); repaint(); super.processMouseMotionEvent(e); } } class MyButton extends Button { int clickCounter; String label = ""; public MyButton() { enableEvents(AWTEvent.ACTION_EVENT_MASK); } public void paint(Graphics g) { g.setColor(Color.green); Dimension s = getSize(); g.fillRect(0, 0, s.width, s.height); g.setColor(Color.black); g.drawRect(0, 0, s.width - 1, s.height - 1); drawLabel(g); } private void drawLabel(Graphics g) { FontMetrics fm = g.getFontMetrics(); int width = fm.stringWidth(label); int height = fm.getHeight(); int ascent = fm.getAscent(); int leading = fm.getLeading(); int horizMargin = (getSize().width - width)/2; int verMargin = (getSize().height - height)/2; g.setColor(Color.red); g.drawString(label, horizMargin, verMargin + ascent + leading); } public void processActionEvent(ActionEvent e) { clickCounter++; label = "click #" + clickCounter + " " + e.toString(); repaint(); super.processActionEvent(e); } } public class BadTechnique extends Frame { BadTechnique() { setLayout(new GridLayout(2,2)); add(new EnabledPanel(1, Color.cyan)); add(new EnabledPanel(2, Color.lightGray)); add(new EnabledPanel(3, Color.yellow)); // You can also do it for Windows: enableEvents(AWTEvent.WINDOW_EVENT_MASK); } public void processWindowEvent(WindowEvent e) { System.out.println(e); if(e.getID() == WindowEvent.WINDOW_CLOSING) { System.out.println("Window Closing"); System.exit(0); } } public static void main(String[] args) { Frame f = new BadTechnique(); f.setTitle("Bad Technique"); f.setSize(700,700); f.setVisible(true); } } ///:~
//: PrintDemo.java // Printing with Java 1.1 import java.awt.*; import java.awt.event.*; public class PrintDemo extends Frame { Button printText = new Button("Print Text"), printGraphics = new Button("Print Graphics"); TextField ringNum = new TextField(3); Choice faces = new Choice(); Graphics g = null; Plot plot = new Plot3(); // Try different plots Toolkit tk = Toolkit.getDefaultToolkit(); public PrintDemo() { ringNum.setText("3"); ringNum.addTextListener(new RingL()); Panel p = new Panel(); p.setLayout(new FlowLayout()); printText.addActionListener(new TBL()); p.add(printText); p.add(new Label("Font:")); p.add(faces); printGraphics.addActionListener(new GBL()); p.add(printGraphics); p.add(new Label("Rings:")); p.add(ringNum); setLayout(new BorderLayout()); add(p, BorderLayout.NORTH); add(plot, BorderLayout.CENTER); String[] fontList = tk.getFontList(); for(int i = 0; i < fontList.length; i++) faces.add(fontList[i]); faces.select("Serif"); } class PrintData { public PrintJob pj; public int pageWidth, pageHeight; PrintData(String jobName) { pj = getToolkit().getPrintJob( PrintDemo.this, jobName, null); if(pj != null) { pageWidth = pj.getPageDimension().width; pageHeight= pj.getPageDimension().height; g = pj.getGraphics(); } } void end() { pj.end(); } } class ChangeFont { private int stringHeight; ChangeFont(String face, int style,int point){ if(g != null) { g.setFont(new Font(face, style, point)); stringHeight = g.getFontMetrics().getHeight(); } } int stringWidth(String s) { return g.getFontMetrics().stringWidth(s); } int stringHeight() { return stringHeight; } } class TBL implements ActionListener { public void actionPerformed(ActionEvent e) { PrintData pd = new PrintData("Print Text Test"); // Null means print job canceled: if(pd == null) return; String s = "PrintDemo"; ChangeFont cf = new ChangeFont( faces.getSelectedItem(), Font.ITALIC,72); g.drawString(s, (pd.pageWidth - cf.stringWidth(s)) / 2, (pd.pageHeight - cf.stringHeight()) / 3); s = "A smaller point size"; cf = new ChangeFont( faces.getSelectedItem(), Font.BOLD, 48); g.drawString(s, (pd.pageWidth - cf.stringWidth(s)) / 2, (int)((pd.pageHeight - cf.stringHeight())/1.5)); g.dispose(); pd.end(); } } class GBL implements ActionListener { public void actionPerformed(ActionEvent e) { PrintData pd = new PrintData("Print Graphics Test"); if(pd == null) return; plot.print(g); g.dispose(); pd.end(); } } class RingL implements TextListener { public void textValueChanged(TextEvent e) { int i = 1; try { i = Integer.parseInt(ringNum.getText()); } catch(NumberFormatException ex) { i = 1; } plot.rings = i; plot.repaint(); } } public static void main(String[] args) { Frame pdemo = new PrintDemo(); pdemo.setTitle("Print Demo"); pdemo.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); pdemo.setSize(500, 500); pdemo.setVisible(true); } } class Plot extends Canvas { public int rings = 3; } class Plot1 extends Plot { // Default print() calls paint(): public void paint(Graphics g) { int w = getSize().width; int h = getSize().height; int xc = w / 2; int yc = w / 2; int x = 0, y = 0; for(int i = 0; i < rings; i++) { if(x < xc && y < yc) { g.drawOval(x, y, w, h); x += 10; y += 10; w -= 20; h -= 20; } } } } class Plot2 extends Plot { // To fit the picture to the page, you must // know whether you're printing or painting: public void paint(Graphics g) { int w, h; if(g instanceof PrintGraphics) { PrintJob pj = ((PrintGraphics)g).getPrintJob(); w = pj.getPageDimension().width; h = pj.getPageDimension().height; } else { w = getSize().width; h = getSize().height; } int xc = w / 2; int yc = w / 2; int x = 0, y = 0; for(int i = 0; i < rings; i++) { if(x < xc && y < yc) { g.drawOval(x, y, w, h); x += 10; y += 10; w -= 20; h -= 20; } } } } class Plot3 extends Plot { // Somewhat better. Separate // printing from painting: public void print(Graphics g) { // Assume it's a PrintGraphics object: PrintJob pj = ((PrintGraphics)g).getPrintJob(); int w = pj.getPageDimension().width; int h = pj.getPageDimension().height; doGraphics(g, w, h); } public void paint(Graphics g) { int w = getSize().width; int h = getSize().height; doGraphics(g, w, h); } private void doGraphics( Graphics g, int w, int h) { int xc = w / 2; int yc = w / 2; int x = 0, y = 0; for(int i = 0; i < rings; i++) { if(x < xc && y < yc) { g.drawOval(x, y, w, h); x += 10; y += 10; w -= 20; h -= 20; } } } } ///:~
//: PrintDemoApplet.java // Creating a Frame from within an Applet import java.applet.*; import java.awt.*; import java.awt.event.*; public class PrintDemoApplet extends Applet { public void init() { Button b = new Button("Run PrintDemo"); b.addActionListener(new PDL()); add(b); } class PDL implements ActionListener { public void actionPerformed(ActionEvent e) { final PrintDemo pd = new PrintDemo(); pd.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e){ pd.dispose(); } }); pd.setSize(500, 500); pd.show(); } } } ///:~
//: CutAndPaste.java // Using the clipboard from Java 1.1 import java.awt.*; import java.awt.event.*; import java.awt.datatransfer.*; public class CutAndPaste extends Frame { MenuBar mb = new MenuBar(); Menu edit = new Menu("Edit"); MenuItem cut = new MenuItem("Cut"), copy = new MenuItem("Copy"), paste = new MenuItem("Paste"); TextArea text = new TextArea(20,20); Clipboard clipbd = getToolkit().getSystemClipboard(); public CutAndPaste() { cut.addActionListener(new CutL()); copy.addActionListener(new CopyL()); paste.addActionListener(new PasteL()); edit.add(cut); edit.add(copy); edit.add(paste); mb.add(edit); setMenuBar(mb); add(text, BorderLayout.CENTER); } class CopyL implements ActionListener { public void actionPerformed(ActionEvent e) { String selection = text.getSelectedText(); StringSelection clipString = new StringSelection(selection); clipbd.setContents(clipString, clipString); } } class CutL implements ActionListener { public void actionPerformed(ActionEvent e) { String selection = text.getSelectedText(); StringSelection clipString = new StringSelection(selection); clipbd.setContents(clipString, clipString); text.replaceRange("", text.getSelectionStart(), text.getSelectionEnd()); } } class PasteL implements ActionListener { public void actionPerformed(ActionEvent e) { Transferable clipData = clipbd.getContents(CutAndPaste.this); try { String clipString = (String)clipData. getTransferData( DataFlavor.stringFlavor); text.replaceRange(clipString, text.getSelectionStart(), text.getSelectionEnd()); } catch(Exception ex) { System.out.println("not String flavor"); } } } public static void main(String[] args) { CutAndPaste cp = new CutAndPaste(); cp.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); cp.setSize(300,200); cp.setVisible(true); } } ///:~
//: Frog.java // A trivial Java Bean package frogbean; import java.awt.*; import java.awt.event.*; class Spots {} public class Frog { private int jumps; private Color color; private Spots spots; private boolean jmpr; public int getJumps() { return jumps; } public void setJumps(int newJumps) { jumps = newJumps; } public Color getColor() { return color; } public void setColor(Color newColor) { color = newColor; } public Spots getSpots() { return spots; } public void setSpots(Spots newSpots) { spots = newSpots; } public boolean isJumper() { return jmpr; } public void setJumper(boolean j) { jmpr = j; } public void addActionListener( ActionListener l) { //... } public void removeActionListener( ActionListener l) { // ... } public void addKeyListener(KeyListener l) { // ... } public void removeKeyListener(KeyListener l) { // ... } // An "ordinary" public method: public void croak() { System.out.println("Ribbet!"); } } ///:~
//: BeanDumper.java // A method to introspect a Bean import java.beans.*; import java.lang.reflect.*; public class BeanDumper { public static void dump(Class bean){ BeanInfo bi = null; try { bi = Introspector.getBeanInfo( bean, java.lang.Object.class); } catch(IntrospectionException ex) { System.out.println("Couldn't introspect " + bean.getName()); System.exit(1); } PropertyDescriptor[] properties = bi.getPropertyDescriptors(); for(int i = 0; i < properties.length; i++) { Class p = properties[i].getPropertyType(); System.out.println( "Property type:\n " + p.getName()); System.out.println( "Property name:\n " + properties[i].getName()); Method readMethod = properties[i].getReadMethod(); if(readMethod != null) System.out.println( "Read method:\n " + readMethod.toString()); Method writeMethod = properties[i].getWriteMethod(); if(writeMethod != null) System.out.println( "Write method:\n " + writeMethod.toString()); System.out.println("===================="); } System.out.println("Public methods:"); MethodDescriptor[] methods = bi.getMethodDescriptors(); for(int i = 0; i < methods.length; i++) System.out.println( methods[i].getMethod().toString()); System.out.println("======================"); System.out.println("Event support:"); EventSetDescriptor[] events = bi.getEventSetDescriptors(); for(int i = 0; i < events.length; i++) { System.out.println("Listener type:\n " + events[i].getListenerType().getName()); Method[] lm = events[i].getListenerMethods(); for(int j = 0; j < lm.length; j++) System.out.println( "Listener method:\n " + lm[j].getName()); MethodDescriptor[] lmd = events[i].getListenerMethodDescriptors(); for(int j = 0; j < lmd.length; j++) System.out.println( "Method descriptor:\n " + lmd[j].getMethod().toString()); Method addListener = events[i].getAddListenerMethod(); System.out.println( "Add Listener Method:\n " + addListener.toString()); Method removeListener = events[i].getRemoveListenerMethod(); System.out.println( "Remove Listener Method:\n " + removeListener.toString()); System.out.println("===================="); } } // Dump the class of your choice: public static void main(String[] args) { if(args.length < 1) { System.err.println("usage: \n" + "BeanDumper fully.qualified.class"); System.exit(0); } Class c = null; try { c = Class.forName(args[0]); } catch(ClassNotFoundException ex) { System.err.println( "Couldn't find " + args[0]); System.exit(0); } dump(c); } } ///:~
class name: Frog Property type: Color Property name: color Read method: public Color getColor() Write method: public void setColor(Color) ==================== Property type: Spots Property name: spots Read method: public Spots getSpots() Write method: public void setSpots(Spots) ==================== Property type: boolean Property name: jumper Read method: public boolean isJumper() Write method: public void setJumper(boolean) ==================== Property type: int Property name: jumps Read method: public int getJumps() Write method: public void setJumps(int) ==================== Public methods: public void setJumps(int) public void croak() public void removeActionListener(ActionListener) public void addActionListener(ActionListener) public int getJumps() public void setColor(Color) public void setSpots(Spots) public void setJumper(boolean) public boolean isJumper() public void addKeyListener(KeyListener) public Color getColor() public void removeKeyListener(KeyListener) public Spots getSpots() ====================== Event support: Listener type: KeyListener Listener method: keyTyped Listener method: keyPressed Listener method: keyReleased Method descriptor: public void keyTyped(KeyEvent) Method descriptor: public void keyPressed(KeyEvent) Method descriptor: public void keyReleased(KeyEvent) Add Listener Method: public void addKeyListener(KeyListener) Remove Listener Method: public void removeKeyListener(KeyListener) ==================== Listener type: ActionListener Listener method: actionPerformed Method descriptor: public void actionPerformed(ActionEvent) Add Listener Method: public void addActionListener(ActionListener) Remove Listener Method: public void removeActionListener(ActionListener) ====================
//: BangBean.java // A graphical Bean package bangbean; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; public class BangBean extends Canvas implements Serializable { protected int xm, ym; protected int cSize = 20; // Circle size protected String text = "Bang!"; protected int fontSize = 48; protected Color tColor = Color.red; protected ActionListener actionListener; public BangBean() { addMouseListener(new ML()); addMouseMotionListener(new MML()); } public int getCircleSize() { return cSize; } public void setCircleSize(int newSize) { cSize = newSize; } public String getBangText() { return text; } public void setBangText(String newText) { text = newText; } public int getFontSize() { return fontSize; } public void setFontSize(int newSize) { fontSize = newSize; } public Color getTextColor() { return tColor; } public void setTextColor(Color newColor) { tColor = newColor; } public void paint(Graphics g) { g.setColor(Color.black); g.drawOval(xm - cSize/2, ym - cSize/2, cSize, cSize); } // This is a unicast listener, which is // the simplest form of listener management: public void addActionListener ( ActionListener l) throws TooManyListenersException { if(actionListener != null) throw new TooManyListenersException(); actionListener = l; } public void removeActionListener( ActionListener l) { actionListener = null; } class ML extends MouseAdapter { public void mousePressed(MouseEvent e) { Graphics g = getGraphics(); g.setColor(tColor); g.setFont( new Font( "TimesRoman", Font.BOLD, fontSize)); int width = g.getFontMetrics().stringWidth(text); g.drawString(text, (getSize().width - width) /2, getSize().height/2); g.dispose(); // Call the listener's method: if(actionListener != null) actionListener.actionPerformed( new ActionEvent(BangBean.this, ActionEvent.ACTION_PERFORMED, null)); } } class MML extends MouseMotionAdapter { public void mouseMoved(MouseEvent e) { xm = e.getX(); ym = e.getY(); repaint(); } } public Dimension getPreferredSize() { return new Dimension(200, 200); } // Testing the BangBean: public static void main(String[] args) { BangBean bb = new BangBean(); try { bb.addActionListener(new BBL()); } catch(TooManyListenersException e) {} Frame aFrame = new Frame("BangBean Test"); aFrame.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); aFrame.add(bb, BorderLayout.CENTER); aFrame.setSize(300,300); aFrame.setVisible(true); } // During testing, send action information // to the console: static class BBL implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("BangBean action"); } } } ///:~
//: JButtonDemo.java // Looks like Java 1.1 but with J's added package c13.swing; import java.awt.*; import java.awt.event.*; import java.applet.*; import javax.swing.*; public class JButtonDemo extends Applet { JButton b1 = new JButton("JButton 1"), b2 = new JButton("JButton 2"); JTextField t = new JTextField(20); public void init() { ActionListener al = new ActionListener() { public void actionPerformed(ActionEvent e){ String name = ((JButton)e.getSource()).getText(); t.setText(name + " Pressed"); } }; b1.addActionListener(al); add(b1); b2.addActionListener(al); add(b2); add(t); } public static void main(String args[]) { JButtonDemo applet = new JButtonDemo(); JFrame frame = new JFrame("TextAreaNew"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e){ System.exit(0); } }); frame.getContentPane().add( applet, BorderLayout.CENTER); frame.setSize(300,100); applet.init(); applet.start(); frame.setVisible(true); } } ///:~
//: Show.java // Tool for displaying Swing demos package c13.swing; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Show { public static void inFrame(JPanel jp, int width, int height) { String title = jp.getClass().toString(); // Remove the word "class": if(title.indexOf("class") != -1) title = title.substring(6); JFrame frame = new JFrame(title); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e){ System.exit(0); } }); frame.getContentPane().add( jp, BorderLayout.CENTER); frame.setSize(width, height); frame.setVisible(true); } } ///:~
//: Borders.java // Different Swing borders package c13.swing; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; public class Borders extends JPanel { static JPanel showBorder(Border b) { JPanel jp = new JPanel(); jp.setLayout(new BorderLayout()); String nm = b.getClass().toString(); nm = nm.substring(nm.lastIndexOf('.') + 1); jp.add(new JLabel(nm, JLabel.CENTER), BorderLayout.CENTER); jp.setBorder(b); return jp; } public Borders() { setLayout(new GridLayout(2,4)); add(showBorder(new TitledBorder("Title"))); add(showBorder(new EtchedBorder())); add(showBorder(new LineBorder(Color.blue))); add(showBorder( new MatteBorder(5,5,30,30,Color.green))); add(showBorder( new BevelBorder(BevelBorder.RAISED))); add(showBorder( new SoftBevelBorder(BevelBorder.LOWERED))); add(showBorder(new CompoundBorder( new EtchedBorder(), new LineBorder(Color.red)))); } public static void main(String args[]) { Show.inFrame(new Borders(), 500, 300); } } ///:~
//: Buttons.java // Various Swing buttons package c13.swing; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.plaf.basic.*; import javax.swing.border.*; public class Buttons extends JPanel { JButton jb = new JButton("JButton"); BasicArrowButton up = new BasicArrowButton( BasicArrowButton.NORTH), down = new BasicArrowButton( BasicArrowButton.SOUTH), right = new BasicArrowButton( BasicArrowButton.EAST), left = new BasicArrowButton( BasicArrowButton.WEST); public Buttons() { add(jb); add(new JToggleButton("JToggleButton")); add(new JCheckBox("JCheckBox")); add(new JRadioButton("JRadioButton")); JPanel jp = new JPanel(); jp.setBorder(new TitledBorder("Directions")); jp.add(up); jp.add(down); jp.add(left); jp.add(right); add(jp); } public static void main(String args[]) { Show.inFrame(new Buttons(), 300, 200); } } ///:~
//: ButtonGroups.java // Uses reflection to create groups of different // types of AbstractButton. package c13.swing; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; import java.lang.reflect.*; public class ButtonGroups extends JPanel { static String[] ids = { "June", "Ward", "Beaver", "Wally", "Eddie", "Lumpy", }; static JPanel makeBPanel(Class bClass, String[] ids) { ButtonGroup bg = new ButtonGroup(); JPanel jp = new JPanel(); String title = bClass.getName(); title = title.substring( title.lastIndexOf('.') + 1); jp.setBorder(new TitledBorder(title)); for(int i = 0; i < ids.length; i++) { AbstractButton ab = new JButton("failed"); try { // Get the dynamic constructor method // that takes a String argument: Constructor ctor = bClass.getConstructor( new Class[] { String.class }); // Create a new object: ab = (AbstractButton)ctor.newInstance( new Object[]{ids[i]}); } catch(Exception ex) { System.out.println("can't create " + bClass); } bg.add(ab); jp.add(ab); } return jp; } public ButtonGroups() { add(makeBPanel(JButton.class, ids)); add(makeBPanel(JToggleButton.class, ids)); add(makeBPanel(JCheckBox.class, ids)); add(makeBPanel(JRadioButton.class, ids)); } public static void main(String args[]) { Show.inFrame(new ButtonGroups(), 500, 300); } } ///:~
//: Faces.java // Icon behavior in JButtons package c13.swing; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Faces extends JPanel { static Icon[] faces = { new ImageIcon("face0.gif"), new ImageIcon("face1.gif"), new ImageIcon("face2.gif"), new ImageIcon("face3.gif"), new ImageIcon("face4.gif"), }; JButton jb = new JButton("JButton", faces[3]), jb2 = new JButton("Disable"); boolean mad = false; public Faces() { jb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ if(mad) { jb.setIcon(faces[3]); mad = false; } else { jb.setIcon(faces[0]); mad = true; } jb.setVerticalAlignment(JButton.TOP); jb.setHorizontalAlignment(JButton.LEFT); } }); jb.setRolloverEnabled(true); jb.setRolloverIcon(faces[1]); jb.setPressedIcon(faces[2]); jb.setDisabledIcon(faces[4]); jb.setToolTipText("Yow!"); add(jb); jb2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ if(jb.isEnabled()) { jb.setEnabled(false); jb2.setText("Enable"); } else { jb.setEnabled(true); jb2.setText("Disable"); } } }); add(jb2); } public static void main(String args[]) { Show.inFrame(new Faces(), 300, 200); } } ///:~
//: Menus.java // A menu-building system; also demonstrates // icons in labels and menu items. package c13.swing; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Menus extends JPanel { static final Boolean bT = new Boolean(true), bF = new Boolean(false); // Dummy class to create type identifiers: static class MType { MType(int i) {} }; static final MType mi = new MType(1), // Normal menu item cb = new MType(2), // Checkbox menu item rb = new MType(3); // Radio button menu item JTextField t = new JTextField(10); JLabel l = new JLabel("Icon Selected", Faces.faces[0], JLabel.CENTER); ActionListener a1 = new ActionListener() { public void actionPerformed(ActionEvent e) { t.setText( ((JMenuItem)e.getSource()).getText()); } }; ActionListener a2 = new ActionListener() { public void actionPerformed(ActionEvent e) { JMenuItem mi = (JMenuItem)e.getSource(); l.setText(mi.getText()); l.setIcon(mi.getIcon()); } }; // Store menu data as "resources": public Object[][] fileMenu = { // Menu name and accelerator: { "File", new Character('F') }, // Name type accel listener enabled { "New", mi, new Character('N'), a1, bT }, { "Open", mi, new Character('O'), a1, bT }, { "Save", mi, new Character('S'), a1, bF }, { "Save As", mi, new Character('A'), a1, bF}, { null }, // Separator { "Exit", mi, new Character('x'), a1, bT }, }; public Object[][] editMenu = { // Menu name: { "Edit", new Character('E') }, // Name type accel listener enabled { "Cut", mi, new Character('t'), a1, bT }, { "Copy", mi, new Character('C'), a1, bT }, { "Paste", mi, new Character('P'), a1, bT }, { null }, // Separator { "Select All", mi,new Character('l'),a1,bT}, }; public Object[][] helpMenu = { // Menu name: { "Help", new Character('H') }, // Name type accel listener enabled { "Index", mi, new Character('I'), a1, bT }, { "Using help", mi,new Character('U'),a1,bT}, { null }, // Separator { "About", mi, new Character('t'), a1, bT }, }; public Object[][] optionMenu = { // Menu name: { "Options", new Character('O') }, // Name type accel listener enabled { "Option 1", cb, new Character('1'), a1,bT}, { "Option 2", cb, new Character('2'), a1,bT}, }; public Object[][] faceMenu = { // Menu name: { "Faces", new Character('a') }, // Optinal last element is icon { "Face 0", rb, new Character('0'), a2, bT, Faces.faces[0] }, { "Face 1", rb, new Character('1'), a2, bT, Faces.faces[1] }, { "Face 2", rb, new Character('2'), a2, bT, Faces.faces[2] }, { "Face 3", rb, new Character('3'), a2, bT, Faces.faces[3] }, { "Face 4", rb, new Character('4'), a2, bT, Faces.faces[4] }, }; public Object[] menuBar = { fileMenu, editMenu, faceMenu, optionMenu, helpMenu, }; static public JMenuBar createMenuBar(Object[] menuBarData) { JMenuBar menuBar = new JMenuBar(); for(int i = 0; i < menuBarData.length; i++) menuBar.add( createMenu((Object[][])menuBarData[i])); return menuBar; } static ButtonGroup bgroup; static public JMenu createMenu(Object[][] menuData) { JMenu menu = new JMenu(); menu.setText((String)menuData[0][0]); menu.setMnemonic( ((Character)menuData[0][1]).charValue()); // Create redundantly, in case there are // any radio buttons: bgroup = new ButtonGroup(); for(int i = 1; i < menuData.length; i++) { if(menuData[i][0] == null) menu.add(new JSeparator()); else menu.add(createMenuItem(menuData[i])); } return menu; } static public JMenuItem createMenuItem(Object[] data) { JMenuItem m = null; MType type = (MType)data[1]; if(type == mi) m = new JMenuItem(); else if(type == cb) m = new JCheckBoxMenuItem(); else if(type == rb) { m = new JRadioButtonMenuItem(); bgroup.add(m); } m.setText((String)data[0]); m.setMnemonic( ((Character)data[2]).charValue()); m.addActionListener( (ActionListener)data[3]); m.setEnabled( ((Boolean)data[4]).booleanValue()); if(data.length == 6) m.setIcon((Icon)data[5]); return m; } Menus() { setLayout(new BorderLayout()); add(createMenuBar(menuBar), BorderLayout.NORTH); JPanel p = new JPanel(); p.setLayout(new BorderLayout()); p.add(t, BorderLayout.NORTH); p.add(l, BorderLayout.CENTER); add(p, BorderLayout.CENTER); } public static void main(String args[]) { Show.inFrame(new Menus(), 300, 200); } } ///:~
//: Popup.java // Creating popup menus with Swing package c13.swing; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Popup extends JPanel { JPopupMenu popup = new JPopupMenu(); JTextField t = new JTextField(10); public Popup() { add(t); ActionListener al = new ActionListener() { public void actionPerformed(ActionEvent e){ t.setText( ((JMenuItem)e.getSource()).getText()); } }; JMenuItem m = new JMenuItem("Hither"); m.addActionListener(al); popup.add(m); m = new JMenuItem("Yon"); m.addActionListener(al); popup.add(m); m = new JMenuItem("Afar"); m.addActionListener(al); popup.add(m); popup.addSeparator(); m = new JMenuItem("Stay Here"); m.addActionListener(al); popup.add(m); PopupListener pl = new PopupListener(); addMouseListener(pl); t.addMouseListener(pl); } class PopupListener extends MouseAdapter { public void mousePressed(MouseEvent e) { maybeShowPopup(e); } public void mouseReleased(MouseEvent e) { maybeShowPopup(e); } private void maybeShowPopup(MouseEvent e) { if(e.isPopupTrigger()) { popup.show( e.getComponent(), e.getX(), e.getY()); } } } public static void main(String args[]) { Show.inFrame(new Popup(),200,150); } } ///:~
//: ListCombo.java // List boxes & Combo boxes package c13.swing; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ListCombo extends JPanel { public ListCombo() { setLayout(new GridLayout(2,1)); JList list = new JList(ButtonGroups.ids); add(new JScrollPane(list)); JComboBox combo = new JComboBox(); for(int i = 0; i < 100; i++) combo.addItem(Integer.toString(i)); add(combo); } public static void main(String args[]) { Show.inFrame(new ListCombo(),200,200); } } ///:~
//: Progress.java // Using progress bars and sliders package c13.swing; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.border.*; public class Progress extends JPanel { JProgressBar pb = new JProgressBar(); JSlider sb = new JSlider(JSlider.HORIZONTAL, 0, 100, 60); public Progress() { setLayout(new GridLayout(2,1)); add(pb); sb.setValue(0); sb.setPaintTicks(true); sb.setMajorTickSpacing(20); sb.setMinorTickSpacing(5); sb.setBorder(new TitledBorder("Slide Me")); pb.setModel(sb.getModel()); // Share model add(sb); } public static void main(String args[]) { Show.inFrame(new Progress(),200,150); } } ///:~
//: Trees.java // Simple Swing tree example. Trees can be made // vastly more complex than this. package c13.swing; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.tree.*; // Takes an array of Strings and makes the first // element a node and the rest leaves: class Branch { DefaultMutableTreeNode r; public Branch(String[] data) { r = new DefaultMutableTreeNode(data[0]); for(int i = 1; i < data.length; i++) r.add(new DefaultMutableTreeNode(data[i])); } public DefaultMutableTreeNode node() { return r; } } public class Trees extends JPanel { String[][] data = { { "Colors", "Red", "Blue", "Green" }, { "Flavors", "Tart", "Sweet", "Bland" }, { "Length", "Short", "Medium", "Long" }, { "Volume", "High", "Medium", "Low" }, { "Temperature", "High", "Medium", "Low" }, { "Intensity", "High", "Medium", "Low" }, }; static int i = 0; DefaultMutableTreeNode root, child, chosen; JTree tree; DefaultTreeModel model; public Trees() { setLayout(new BorderLayout()); root = new DefaultMutableTreeNode("root"); tree = new JTree(root); // Add it and make it take care of scrolling: add(new JScrollPane(tree), BorderLayout.CENTER); // Capture the tree's model: model =(DefaultTreeModel)tree.getModel(); JButton test = new JButton("Press me"); test.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ if(i < data.length) { child = new Branch(data[i++]).node(); // What's the last one you clicked? chosen = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if(chosen == null) chosen = root; // The model will create the // appropriate event. In response, the // tree will update itself: model.insertNodeInto(child, chosen, 0); // This puts the new node on the // currently chosen node. } } }); // Change the button's colors: test.setBackground(Color.blue); test.setForeground(Color.white); JPanel p = new JPanel(); p.add(test); add(p, BorderLayout.SOUTH); } public static void main(String args[]) { Show.inFrame(new Trees(),200,500); } } ///:~
//: Table.java // Simple demonstration of JTable package c13.swing; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.table.*; import javax.swing.event.*; // The TableModel controls all the data: class DataModel extends AbstractTableModel { Object[][] data = { {"one", "two", "three", "four"}, {"five", "six", "seven", "eight"}, {"nine", "ten", "eleven", "twelve"}, }; // Prints data when table changes: class TML implements TableModelListener { public void tableChanged(TableModelEvent e) { for(int i = 0; i < data.length; i++) { for(int j = 0; j < data[0].length; j++) System.out.print(data[i][j] + " "); System.out.println(); } } } DataModel() { addTableModelListener(new TML()); } public int getColumnCount() { return data[0].length; } public int getRowCount() { return data.length; } public Object getValueAt(int row, int col) { return data[row][col]; } public void setValueAt(Object val, int row, int col) { data[row][col] = val; // Indicate the change has happened: fireTableDataChanged(); } public boolean isCellEditable(int row, int col) { return true; } }; public class Table extends JPanel { public Table() { setLayout(new BorderLayout()); JTable table = new JTable(new DataModel()); JScrollPane scrollpane = JTable.createScrollPaneForTable(table); add(scrollpane, BorderLayout.CENTER); } public static void main(String args[]) { Show.inFrame(new Table(),200,200); } } ///:~
//: Tabbed.java // Using tabbed panes package c13.swing; import java.awt.*; import javax.swing.*; import javax.swing.border.*; public class Tabbed extends JPanel { static Object[][] q = { { "Felix", Borders.class }, { "The Professor", Buttons.class }, { "Rock Bottom", ButtonGroups.class }, { "Theodore", Faces.class }, { "Simon", Menus.class }, { "Alvin", Popup.class }, { "Tom", ListCombo.class }, { "Jerry", Progress.class }, { "Bugs", Trees.class }, { "Daffy", Table.class }, }; static JPanel makePanel(Class c) { String title = c.getName(); title = title.substring( title.lastIndexOf('.') + 1); JPanel sp = null; try { sp = (JPanel)c.newInstance(); } catch(Exception e) { System.out.println(e); } sp.setBorder(new TitledBorder(title)); return sp; } public Tabbed() { setLayout(new BorderLayout()); JTabbedPane tabbed = new JTabbedPane(); for(int i = 0; i < q.length; i++) tabbed.addTab((String)q[i][0], makePanel((Class)q[i][1])); add(tabbed, BorderLayout.CENTER); tabbed.setSelectedIndex(q.length/2); } public static void main(String args[]) { Show.inFrame(new Tabbed(),460,350); } } ///:~