From 554fd8c5195424bdbcabf5de30fdc183aba391bd Mon Sep 17 00:00:00 2001 From: upstream source tree Date: Sun, 15 Mar 2015 20:14:05 -0400 Subject: obtained gcc-4.6.4.tar.bz2 from upstream website; verified gcc-4.6.4.tar.bz2.sig; imported gcc-4.6.4 source tree from verified upstream tarball. downloading a git-generated archive based on the 'upstream' tag should provide you with a source tree that is binary identical to the one extracted from the above tarball. if you have obtained the source via the command 'git clone', however, do note that line-endings of files in your working directory might differ from line-endings of the respective files in the upstream repository. --- .../examples/CORBA/NamingService/Demo.java | 200 +++ .../examples/CORBA/SimpleCommunication/Demo.java | 102 ++ .../CORBA/SimpleCommunication/DemoServer.java | 118 ++ .../communication/DemoServant.java | 230 +++ .../communication/DemoTester.java | 111 ++ .../communication/DirectTest.java | 344 +++++ .../communication/RequestTest.java | 284 ++++ .../communication/StructureToPass.java | 66 + .../communication/StructureToPassHelper.java | 103 ++ .../communication/StructureToPassHolder.java | 37 + .../communication/StructureToReturn.java | 71 + .../communication/StructureToReturnHelper.java | 116 ++ .../communication/StructureToReturnHolder.java | 60 + .../communication/TreeNode.java | 60 + .../communication/TreeNodeHelper.java | 162 ++ .../communication/TreeNodeHolder.java | 100 ++ .../communication/WeThrowThisException.java | 75 + .../communication/WeThrowThisExceptionHelper.java | 117 ++ .../communication/_DemoTesterImplBase.java | 209 +++ .../communication/_DemoTesterStub.java | 429 ++++++ .../gnu/classpath/examples/CORBA/swing/README.html | 493 ++++++ .../examples/CORBA/swing/x5/CanvasWorld.java | 307 ++++ .../examples/CORBA/swing/x5/ChatConstants.java | 80 + .../examples/CORBA/swing/x5/ClientFrame.java | 417 ++++++ .../classpath/examples/CORBA/swing/x5/Demo.java | 99 ++ .../examples/CORBA/swing/x5/GameManager.java | 68 + .../examples/CORBA/swing/x5/GameManagerImpl.java | 135 ++ .../examples/CORBA/swing/x5/IorReader.java | 124 ++ .../examples/CORBA/swing/x5/OrbStarter.java | 236 +++ .../classpath/examples/CORBA/swing/x5/Player.java | 96 ++ .../examples/CORBA/swing/x5/PlayerImpl.java | 275 ++++ .../examples/CORBA/swing/x5/PlayingDesk.java | 512 +++++++ .../classpath/examples/CORBA/swing/x5/State.java | 82 + .../examples/CORBA/swing/x5/X5Server.java | 175 +++ .../CORBA/swing/x5/_GameManagerImpl_Tie.java | 209 +++ .../examples/CORBA/swing/x5/_GameManager_Stub.java | 207 +++ .../examples/CORBA/swing/x5/_PlayerImpl_Tie.java | 209 +++ .../examples/CORBA/swing/x5/_Player_Stub.java | 397 +++++ .../examples/awt/AicasGraphicsBenchmark.java | 1018 +++++++++++++ .../classpath/examples/awt/AnimationApplet.java | 232 +++ .../examples/gnu/classpath/examples/awt/Demo.java | 1189 +++++++++++++++ .../gnu/classpath/examples/awt/HintingDemo.java | 420 ++++++ .../gnu/classpath/examples/datatransfer/Demo.java | 652 ++++++++ .../examples/gnu/classpath/examples/html/Demo.java | 131 ++ .../gnu/classpath/examples/icons/aicas.png | Bin 0 -> 2320 bytes .../examples/gnu/classpath/examples/icons/back.png | Bin 0 -> 828 bytes .../gnu/classpath/examples/icons/badge.png | Bin 0 -> 45862 bytes .../classpath/examples/icons/big-fullscreen.png | Bin 0 -> 3768 bytes .../gnu/classpath/examples/icons/big-home.png | Bin 0 -> 4135 bytes .../gnu/classpath/examples/icons/big-warning.png | Bin 0 -> 2250 bytes .../gnu/classpath/examples/icons/palme.gif | Bin 0 -> 502 bytes .../gnu/classpath/examples/icons/reload.png | Bin 0 -> 1324 bytes .../gnu/classpath/examples/icons/stock-copy.png | Bin 0 -> 285 bytes .../gnu/classpath/examples/icons/stock-cut.png | Bin 0 -> 328 bytes .../gnu/classpath/examples/icons/stock-go-back.png | Bin 0 -> 523 bytes .../gnu/classpath/examples/icons/stock-go-down.png | Bin 0 -> 536 bytes .../classpath/examples/icons/stock-go-forward.png | Bin 0 -> 522 bytes .../gnu/classpath/examples/icons/stock-mic.png | Bin 0 -> 590 bytes .../gnu/classpath/examples/icons/stock-new.png | Bin 0 -> 349 bytes .../gnu/classpath/examples/icons/stock-open.png | Bin 0 -> 448 bytes .../gnu/classpath/examples/icons/stock-paste.png | Bin 0 -> 563 bytes .../gnu/classpath/examples/icons/stock-quit.png | Bin 0 -> 507 bytes .../gnu/classpath/examples/icons/stock-save-as.png | Bin 0 -> 751 bytes .../gnu/classpath/examples/icons/stock-save.png | Bin 0 -> 539 bytes .../classpath/examples/icons/stock-spell-check.png | Bin 0 -> 374 bytes .../classpath/examples/java2d/J2dBenchmark.java | 1571 ++++++++++++++++++++ .../classpath/examples/java2d/J2dBenchmarkGUI.java | 891 +++++++++++ .../gnu/classpath/examples/java2d/JNIOverhead.java | 390 +++++ .../examples/gnu/classpath/examples/java2d/bench.c | 606 ++++++++ .../examples/gnu/classpath/examples/java2d/bench.h | 64 + .../gnu/classpath/examples/jawt/DemoJAWT.c | 150 ++ .../gnu/classpath/examples/jawt/DemoJAWT.java | 77 + .../classpath/examples/management/TestBeans.java | 40 + .../examples/management/TestClassLoading.java | 77 + .../examples/management/TestCompilation.java | 48 + .../examples/management/TestGarbageCollector.java | 50 + .../classpath/examples/management/TestMemory.java | 52 + .../examples/management/TestMemoryManager.java | 46 + .../examples/management/TestMemoryPool.java | 91 ++ .../gnu/classpath/examples/management/TestOS.java | 38 + .../classpath/examples/management/TestRuntime.java | 54 + .../classpath/examples/management/TestThread.java | 118 ++ .../examples/gnu/classpath/examples/midi/Demo.java | 137 ++ .../gnu/classpath/examples/print/Demo.java | 391 +++++ .../examples/sound/AudioPlayerSample.java | 222 +++ .../classpath/examples/swing/BrowserEditorKit.java | 56 + .../gnu/classpath/examples/swing/ButtonDemo.java | 319 ++++ .../gnu/classpath/examples/swing/ComboBoxDemo.java | 386 +++++ .../gnu/classpath/examples/swing/Demo.java | 629 ++++++++ .../gnu/classpath/examples/swing/DemoDesktop.java | 82 + .../gnu/classpath/examples/swing/DemoFactory.java | 57 + .../examples/swing/DocumentFilterDemo.java | 288 ++++ .../classpath/examples/swing/FileChooserDemo.java | 264 ++++ .../gnu/classpath/examples/swing/HtmlDemo.java | 379 +++++ .../gnu/classpath/examples/swing/ListDemo.java | 231 +++ .../classpath/examples/swing/MetalThemeEditor.java | 585 ++++++++ .../gnu/classpath/examples/swing/MiniDemo.java | 233 +++ .../examples/swing/NavigationFilterDemo.java | 205 +++ .../classpath/examples/swing/ProgressBarDemo.java | 239 +++ .../classpath/examples/swing/ScrollBarDemo.java | 174 +++ .../gnu/classpath/examples/swing/SliderDemo.java | 287 ++++ .../gnu/classpath/examples/swing/SpinnerDemo.java | 235 +++ .../classpath/examples/swing/TabbedPaneDemo.java | 256 ++++ .../gnu/classpath/examples/swing/TableDemo.java | 410 +++++ .../gnu/classpath/examples/swing/TextAreaDemo.java | 620 ++++++++ .../classpath/examples/swing/TextFieldDemo.java | 594 ++++++++ .../gnu/classpath/examples/swing/TreeDemo.java | 318 ++++ .../gnu/classpath/examples/swing/forms.html | 98 ++ .../gnu/classpath/examples/swing/frame1.html | 41 + .../gnu/classpath/examples/swing/frame2.html | 42 + .../gnu/classpath/examples/swing/frame3.html | 42 + .../gnu/classpath/examples/swing/frame4.html | 41 + .../gnu/classpath/examples/swing/frames.html | 44 + .../gnu/classpath/examples/swing/tables.html | 66 + .../gnu/classpath/examples/swing/textstyles.html | 78 + .../gnu/classpath/examples/swing/welcome.html | 63 + 116 files changed, 23232 insertions(+) create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/NamingService/Demo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/Demo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/DemoServer.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/DemoServant.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/DemoTester.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/DirectTest.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/RequestTest.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToPass.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToPassHelper.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToPassHolder.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToReturn.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToReturnHelper.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToReturnHolder.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/TreeNode.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/TreeNodeHelper.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/TreeNodeHolder.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/WeThrowThisException.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/WeThrowThisExceptionHelper.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/_DemoTesterImplBase.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/_DemoTesterStub.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/README.html create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/CanvasWorld.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/ChatConstants.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/ClientFrame.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/Demo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/GameManager.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/GameManagerImpl.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/IorReader.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/OrbStarter.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/Player.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/PlayerImpl.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/PlayingDesk.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/State.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/X5Server.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/_GameManagerImpl_Tie.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/_GameManager_Stub.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/_PlayerImpl_Tie.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/_Player_Stub.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/awt/AicasGraphicsBenchmark.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/awt/AnimationApplet.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/awt/Demo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/awt/HintingDemo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/datatransfer/Demo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/html/Demo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/icons/aicas.png create mode 100644 libjava/classpath/examples/gnu/classpath/examples/icons/back.png create mode 100644 libjava/classpath/examples/gnu/classpath/examples/icons/badge.png create mode 100644 libjava/classpath/examples/gnu/classpath/examples/icons/big-fullscreen.png create mode 100644 libjava/classpath/examples/gnu/classpath/examples/icons/big-home.png create mode 100644 libjava/classpath/examples/gnu/classpath/examples/icons/big-warning.png create mode 100644 libjava/classpath/examples/gnu/classpath/examples/icons/palme.gif create mode 100644 libjava/classpath/examples/gnu/classpath/examples/icons/reload.png create mode 100644 libjava/classpath/examples/gnu/classpath/examples/icons/stock-copy.png create mode 100644 libjava/classpath/examples/gnu/classpath/examples/icons/stock-cut.png create mode 100644 libjava/classpath/examples/gnu/classpath/examples/icons/stock-go-back.png create mode 100644 libjava/classpath/examples/gnu/classpath/examples/icons/stock-go-down.png create mode 100644 libjava/classpath/examples/gnu/classpath/examples/icons/stock-go-forward.png create mode 100644 libjava/classpath/examples/gnu/classpath/examples/icons/stock-mic.png create mode 100644 libjava/classpath/examples/gnu/classpath/examples/icons/stock-new.png create mode 100644 libjava/classpath/examples/gnu/classpath/examples/icons/stock-open.png create mode 100644 libjava/classpath/examples/gnu/classpath/examples/icons/stock-paste.png create mode 100644 libjava/classpath/examples/gnu/classpath/examples/icons/stock-quit.png create mode 100644 libjava/classpath/examples/gnu/classpath/examples/icons/stock-save-as.png create mode 100644 libjava/classpath/examples/gnu/classpath/examples/icons/stock-save.png create mode 100644 libjava/classpath/examples/gnu/classpath/examples/icons/stock-spell-check.png create mode 100644 libjava/classpath/examples/gnu/classpath/examples/java2d/J2dBenchmark.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/java2d/J2dBenchmarkGUI.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/java2d/JNIOverhead.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/java2d/bench.c create mode 100644 libjava/classpath/examples/gnu/classpath/examples/java2d/bench.h create mode 100644 libjava/classpath/examples/gnu/classpath/examples/jawt/DemoJAWT.c create mode 100644 libjava/classpath/examples/gnu/classpath/examples/jawt/DemoJAWT.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/management/TestBeans.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/management/TestClassLoading.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/management/TestCompilation.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/management/TestGarbageCollector.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/management/TestMemory.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/management/TestMemoryManager.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/management/TestMemoryPool.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/management/TestOS.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/management/TestRuntime.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/management/TestThread.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/midi/Demo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/print/Demo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/sound/AudioPlayerSample.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/BrowserEditorKit.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/ButtonDemo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/ComboBoxDemo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/Demo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/DemoDesktop.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/DemoFactory.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/DocumentFilterDemo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/FileChooserDemo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/HtmlDemo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/ListDemo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/MetalThemeEditor.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/MiniDemo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/NavigationFilterDemo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/ProgressBarDemo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/ScrollBarDemo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/SliderDemo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/SpinnerDemo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/TabbedPaneDemo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/TableDemo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/TextAreaDemo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/TextFieldDemo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/TreeDemo.java create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/forms.html create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/frame1.html create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/frame2.html create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/frame3.html create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/frame4.html create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/frames.html create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/tables.html create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/textstyles.html create mode 100644 libjava/classpath/examples/gnu/classpath/examples/swing/welcome.html (limited to 'libjava/classpath/examples/gnu') diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/NamingService/Demo.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/NamingService/Demo.java new file mode 100644 index 000000000..f71c24f2b --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/NamingService/Demo.java @@ -0,0 +1,200 @@ +/* Demo.java -- Shows how to use Classpath transient naming service. + Copyright (C) 2005 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.NamingService; + +import gnu.CORBA.IOR; + +import org.omg.CORBA.ORB; +import org.omg.CORBA.Object; +import org.omg.CosNaming.Binding; +import org.omg.CosNaming.BindingHolder; +import org.omg.CosNaming.BindingIterator; +import org.omg.CosNaming.BindingIteratorHolder; +import org.omg.CosNaming.BindingListHolder; +import org.omg.CosNaming.NameComponent; +import org.omg.CosNaming.NamingContext; +import org.omg.CosNaming.NamingContextExt; +import org.omg.CosNaming.NamingContextExtHelper; +import org.omg.CosNaming.NamingContextHelper; + +/** + * A simple test of the naming service. + * + * The main class of the GNU Classpath transient naming service is + * {@link gnu.CORBA.NamingService}. This class must be started + * before starting this example. + * + * This example should interoperate as with GNU Classpath naming + * service, as with Sun Microsystems transient and persistent + * naming services, included in releases 1.3 and 1.4 (tnameserv and + * orbd). To work with this example, the naming service must + * be started on the local host, at the port 900. + * + * The persistent naming service is currently under development. + * + * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org) + */ +public class Demo +{ + public static void main(String[] an_args) + { + // We create the following naming graph: + // + // | + // +--- + // | | + // | +--- obj + // | + // +--- xobj + // + // Where both obj and xobj are CORBA objects, representing the + // default naming service. + // + System.out.println("Starting the GNU Classpath " + + "built-in transient naming service" + ); + + final String[] args = an_args; + + new Thread() + { + public void run() + { + gnu.classpath.tools.tnameserv.Main.main(args); + } + }.start(); + + System.out.println("Waiting for three seconds for naming service to start:"); + try + { + Thread.sleep(3000); + } + catch (InterruptedException ex) + { + } + + try + { + ORB orb = ORB.init(args, null); + + Object no = orb.resolve_initial_references("NameService"); + + System.out.println("Naming service IOR:" + orb.object_to_string(no)); + + System.out.println(IOR.parse(orb.object_to_string(no))); + + NamingContextExt namer = NamingContextExtHelper.narrow(no); + + System.out.println("Naming service: " + namer.getClass().getName()); + + NamingContext second = namer.new_context(); + + namer.rebind_context(namer.to_name("c.d"), second); + namer.rebind(namer.to_name("xobj"), no); + + second.rebind(namer.to_name("obj"), no); + + NamingContext nsec = + NamingContextHelper.narrow(namer.resolve_str("c.d")); + + System.out.println(namer.resolve(namer.to_name("c.d/obj"))); + + // In all cases, this must be the same object (the naming + // service itself). + System.out.println(nsec.resolve(new NameComponent[] + { + new NameComponent("obj", "") + } + ) + ); + System.out.println(namer.resolve_str("xobj")); + + // In all cases, this must be the same object (the naming + // service itself). + System.out.println(namer.resolve(new NameComponent[] + { + new NameComponent("c", "d"), + new NameComponent("obj", "") + } + ) + ); + + System.out.println(namer.resolve_str("c.d/obj")); + + System.out.println("Test binding list iterator:"); + + BindingListHolder lh = new BindingListHolder(); + BindingIteratorHolder lih = new BindingIteratorHolder(); + + namer.list(0, lh, lih); + + BindingIterator iter = lih.value; + BindingHolder binding = new BindingHolder(); + + while (iter.next_one(binding)) + { + Binding b = binding.value; + System.out.println("NAME: " + namer.to_string(b.binding_name) + + " TYPE " + b.binding_type.value() + ); + } + + System.out.println("Testing binding list:"); + + iter.destroy(); + + namer.list(Integer.MAX_VALUE, lh, lih); + + for (int i = 0; i < lh.value.length; i++) + { + Binding b = lh.value [ i ]; + System.out.println("NAME: " + namer.to_string(b.binding_name) + + " TYPE " + b.binding_type.value() + ); + } + } + catch (Exception ex) + { + ex.printStackTrace(); + System.exit(1); + } + + System.exit(0); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/Demo.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/Demo.java new file mode 100644 index 000000000..944f66191 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/Demo.java @@ -0,0 +1,102 @@ +/* Demo.java -- Demonstrates simple CORBA client-server communications. + Copyright (C) 2005 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.SimpleCommunication; + +import java.io.File; + +import gnu.classpath.examples.CORBA.SimpleCommunication.communication.DirectTest; +import gnu.classpath.examples.CORBA.SimpleCommunication.communication.RequestTest; + + +/** + * This sample illustrates the CORBA communication between server + * and client. In this simple example both server and client are + * started on the same virtual machine. For the real interoperability + * tests, however, the server is started on the platform (library+jvm) of + * one vendor, and the client on the platform of another vendor. + * + * The interoperability is currently tested with Sun Microystems + * jre 1.4. + * + * This example required the current folder to be writable to pass + * the IOR references via shared file. + * + * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org) + */ +public class Demo +{ + public static void main(final String[] args) + { + File ior = new File("IOR.txt"); + if (ior.exists()) + ior.delete(); + + // Start the server. + new Thread() + { + public void run() + { + DemoServer.start_server(args); + } + }.start(); + + System.out.print("Waiting for the server to start "); + while (!ior.exists()) + { + // Pause some time for the server to start. + try + { + Thread.sleep(200); + } + catch (InterruptedException ex) + { + } + System.out.print("."); + } + System.out.println("ok."); + System.out.println(); + + // Test the stream oriented communication. + DirectTest.main(args); + // Test the request oriented communication. + RequestTest.main(args); + + System.exit(0); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/DemoServer.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/DemoServer.java new file mode 100644 index 000000000..d7b1a7771 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/DemoServer.java @@ -0,0 +1,118 @@ +/* DemoServer.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.SimpleCommunication; + +import gnu.classpath.examples.CORBA.SimpleCommunication.communication.DemoServant; + +import org.omg.CORBA.ORB; + +import java.io.FileOutputStream; +import java.io.PrintStream; + +/** + * This is the server class that handles the client requests, + * delegating the functionality to the {@link DemoServant}. + * + * When starting, the server writes the IOR.txt file into the current + * folder. With the information, stored in this file, the server + * should be reachable over Internet, unless blocked by security tools. + * + * This code is tested for interoperability with Sun Microsystems + * java implementation 1.4.2 (08.b03). Server, client of both can + * be started either on Sun's or on Classpath CORBA implementation, + * in any combinations. + * + * BE SURE TO START THIS SERVER BEFORE STARTING THE CLIENT. + * + * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org) + */ +public class DemoServer +{ + + public static void main(String[] args) + { + start_server(args); + } + + public static ORB start_server(String[] args) + { + try + { + // Create and initialize the ORB. + final ORB orb = org.omg.CORBA.ORB.init(args, null); + + // Create the servant and register it with the ORB. + DemoServant tester = new DemoServant(); + orb.connect(tester); + + // Storing the IOR reference. + String ior = orb.object_to_string(tester); + System.out.println("IOR: " + ior); + + gnu.CORBA.IOR ii = gnu.CORBA.IOR.parse(ior); + System.out.println(ii); + + // The file IOR.txt in the current folder will be used + // to find the object by clients. + FileOutputStream f = new FileOutputStream("IOR.txt"); + PrintStream p = new PrintStream(f); + p.print(ior); + p.close(); + + System.out.println("The test server ready and waiting ..."); + + new Thread() + { + public void run() + { + // Start the thread, serving the invocations from clients. + orb.run(); + } + }.start(); + + return orb; + } + catch (Exception e) + { + System.err.println("ERROR: " + e); + e.printStackTrace(System.out); + return null; + } + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/DemoServant.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/DemoServant.java new file mode 100644 index 000000000..9af20d227 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/DemoServant.java @@ -0,0 +1,230 @@ +/* DemoServant.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.SimpleCommunication.communication; + +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.ByteHolder; +import org.omg.CORBA.CompletionStatus; +import org.omg.CORBA.DoubleHolder; +import org.omg.CORBA.ShortHolder; +import org.omg.CORBA.StringHolder; + +/** + * This class handles the actual server functionality in this test + * application. When the client calls the remote method, this + * finally results calling the method of this class. + * + * The parameters, passed to the server only, are just parameters of the + * java methods. The parameters that shuld be returned to client + * are wrapped into holder classes. + * + * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org) + */ +public class DemoServant + extends _DemoTesterImplBase +{ + /** + * The field, that can be set and checked by remote client. + */ + private int m_theField = 17; + + /** + * Passes wide (UTF-16) string and narrow (ISO8859_1) string. + * @see gnu.CORBA.GIOP.CharSets_OSF for supported and default + * encodings. Returs they generalization as a wide string. + */ + public String passCharacters(String wide, String narrow) + { + System.out.println("SERVER: **** Wide and narrow string test."); + System.out.println("SERVER: Received '" + narrow + "' and '" + wide + + "'" + ); + + return "return '" + narrow + "' and '" + wide + "'"; + } + + /** + * Accept and return parameters, having various types. + */ + public int passSimple(ByteHolder an_octet, int a_long, ShortHolder a_short, + StringHolder a_string, DoubleHolder a_double + ) + { + System.out.println("SERVER: ***** Test passing multiple parameters"); + System.out.println("SERVER: Received:"); + System.out.println("SERVER: octet " + an_octet.value); + System.out.println("SERVER: short " + a_short.value); + System.out.println("SERVER: string " + a_string.value); + + // Returning incremented values. + an_octet.value++; + a_short.value++; + + // OUT parameter, return only. + a_double.value = 1; + a_string.value += " [return]"; + return 452572; + } + + /** + * Accept and return the string arrays. + */ + public String[] passStrings(String[] args) + { + System.out.println("SERVER: ***** Transferring string arrays"); + + String[] rt = new String[ args.length ]; + for (int i = 0; i < args.length; i++) + { + System.out.println("SERVER: " + args [ i ]); + + // Returning the changed content. + rt [ i ] = args [ i ] + ":" + args [ i ]; + } + return rt; + } + + /** + * Accept and return the structures. + */ + public StructureToReturn passStructure(StructureToPass in_structure) + { + System.out.println("SERVER: ***** Transferring structures"); + System.out.println("SERVER: Received " + in_structure.a + ":" + + in_structure.b + ); + + // Create and send back the returned structure. + StructureToReturn r = new StructureToReturn(); + r.c = in_structure.a + in_structure.b; + r.n = 555; + r.arra = new int[] { 11, 22, 33 }; + return r; + } + + /** + * Pass and return the tree structure + */ + public void passTree(TreeNodeHolder tree) + { + System.out.println("SERVER: ***** Transferring tree"); + + StringBuilder b = new StringBuilder(); + + // This both creates the tree string representation + // and changes the TreeNode names. + getImage(b, tree.value); + System.out.println("SERVER: The tree was: " + b + ", returning changed."); + } + + /** + * Just prints the hello message. + */ + public void sayHello() + { + System.out.println("SERVER: ***** Hello, world!"); + } + + /** + * Get the value of our field. + */ + public int theField() + { + System.out.println("SERVER: ***** Getting the field value, " + m_theField); + return m_theField; + } + + /** + * Set the value of our field. + */ + public void theField(int a_field) + { + System.out.println("SERVER: ***** Setting the field value to " + a_field); + m_theField = a_field; + } + + /** + * Throw an exception. + * + * @param parameter specifies which exception will be thrown. + * + * @throws WeThrowThisException for the non negative parameter. + * @throws BAD_OPERATION for the negative parameter. + */ + public void throwException(int parameter) + throws WeThrowThisException + { + System.out.println("SERVER: ***** Testing exceptions"); + if (parameter > 0) + { + System.out.println("SERVER: Throwing the user exception, " + + "specific field = "+parameter + ); + throw new WeThrowThisException(parameter); + } + else + { + System.out.println("SERVER: Throwing " + + "the BAD_OPERATION, minor 456, completed" + ); + throw new BAD_OPERATION(456, CompletionStatus.COMPLETED_YES); + } + } + + /** + * Visit all tree nodes, getting the string representation + * and adding '++' to the TreeNode names. + * + * @param b the buffer to collect the string representation. + * @param n the rott tree TreeNode. + */ + private void getImage(StringBuilder b, TreeNode n) + { + b.append(n.name); + n.name = n.name + "++"; + b.append(": ("); + + for (int i = 0; i < n.children.length; i++) + { + getImage(b, n.children [ i ]); + b.append(' '); + } + b.append(") "); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/DemoTester.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/DemoTester.java new file mode 100644 index 000000000..f3766f325 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/DemoTester.java @@ -0,0 +1,111 @@ +/* DemoTester.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.SimpleCommunication.communication; + +import org.omg.CORBA.ByteHolder; +import org.omg.CORBA.DoubleHolder; +import org.omg.CORBA.ShortHolder; +import org.omg.CORBA.StringHolder; + +/** + * The interface of our remote object. Some IDL compiles split it + * into "DemoTester" and "comTesterOperations", but we do not see + * much sense in doing this here. + * + * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org) + */ +public interface DemoTester +{ + /** + * Passes wide (UTF-16) string and narrow (ISO8859_1) string. + * Both types are mapped into java String. + * + * @see gnu.CORBA.GIOP.CharSets_OSF for supported and default + * encodings. + */ + String passCharacters(String wide, String narrow); + + /** + * Passes various parameters in both directions. + * The parameters that must return the value are wrapped in holders. + */ + int passSimple(ByteHolder an_octet, int a_long, ShortHolder a_short, + StringHolder a_string, DoubleHolder a_double + ); + + /** + * Passes and returns the string sequence (flexible length). + */ + String[] passStrings(String[] arg); + + /** + * Passes and returns the structures. + */ + StructureToReturn passStructure(StructureToPass in_structure); + + /** + * Pass and return the tree structure + * + * @param tree the root TreeNode of the tree. + */ + void passTree(TreeNodeHolder tree); + + /** + * Just prints the "Hello" message. + */ + void sayHello(); + + /** + * Gets the value of the field in our object. + */ + int theField(); + + /** + * Sets the value for the field in our object. + */ + void theField(int newTheField); + + /** + * Throws either 'WeThrowThisException' with the 'ourField' field + * initialised to the passed positive value + * or system exception (if the parameter is zero or negative). + */ + void throwException(int parameter) + throws WeThrowThisException; +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/DirectTest.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/DirectTest.java new file mode 100644 index 000000000..843530de5 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/DirectTest.java @@ -0,0 +1,344 @@ +/* DirectTest.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.SimpleCommunication.communication; + +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.ByteHolder; +import org.omg.CORBA.DoubleHolder; +import org.omg.CORBA.ORB; +import org.omg.CORBA.ShortHolder; +import org.omg.CORBA.StringHolder; +import org.omg.CORBA.UserException; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +/** + * This code uses CORBA to call various methods of the remote object, + * passing data structures in both directions. It finds the server by + * reading the IOR.txt file that must be present in the folder, + * where the program has been started. + * + * The IOR.txt file is written by the server + * {@link gnu.classpath.examples.CORBA.SimpleCommunication.DemoServer}. + * The server should be reachable over Internet, unless blocked by + * security tools. + * + * This code is tested for interoperability with Sun Microsystems + * java implementation 1.4.2 (08.b03). Server, client of both can + * be started either on Sun's or on Classpath CORBA implementation, + * in any combinations. + * + * BE SURE TO START THE SERVER BEFORE STARTING THE CLIENT. + * + * This version uses direct casting. This is the most convenient + * method, but it is normally used together with the IDL compiler. + * + * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org) + */ +public class DirectTest +{ + /* + * The IOR.txt file, used to find the server and the object on the server. is written when starting the accompanying + */ + public static final String IOR_FILE = "IOR.txt"; + + /** + * The invocation target. + */ + DemoTester object; + + /** + * Get the object reference. + */ + public static void main(String[] args) + { + try + { + ORB orb = org.omg.CORBA.ORB.init(args, null); + + File f = new File(IOR_FILE); + char[] c = new char[ (int) f.length() ]; + FileReader fr = new FileReader(f); + fr.read(c); + fr.close(); + + String ior = new String(c); + DirectTest we = new DirectTest(); + we.object = (DemoTester) orb.string_to_object(ior); + we.Demo(); + orb.shutdown(false); + } + catch (IOException ex) + { + System.out.println("Cannot find or read the IOR file " + + "in the current folder" + ); + ex.printStackTrace(); + } + } + + /** Run all demos. */ + public void Demo() + { + testHello(); + testField(); + testParameters(); + testStringArray(); + testStructure(); + testWideNarrowStrings(); + testTree(); + testSystemException(); + testUserException(); + } + + /** + * Test the field getter/setter. + */ + public void testField() + { + System.out.println("***** Test the remote field getter/setter."); + System.out.println("The field value is now " + object.theField()); + System.out.println("Setting it to 555"); + object.theField(555); + System.out.println("The field value is now " + object.theField()); + } + + /** The simple invocation of the parameterless remote method. */ + public void testHello() + { + System.out.println("***** Say hello (see the server console)."); + object.sayHello(); + } + + /** + * Test passing multiple parameters in both directions. + */ + public void testParameters() + { + System.out.println("***** Pass multiple parameters."); + + // Holder classes are required to simulate passing + // "by reference" (modification is returned back to the server). + ByteHolder a_byte = new ByteHolder((byte) 0); + ShortHolder a_short = new ShortHolder((short) 3); + StringHolder a_string = new StringHolder("[string 4]"); + + // This is an 'out' parameter; the value must not be passed to servant. + DoubleHolder a_double = new DoubleHolder(56.789); + + int returned = object.passSimple(a_byte, 2, a_short, a_string, a_double); + + System.out.println(" Returned value " + returned); + System.out.println(" Returned parameters: "); + System.out.println(" octet " + a_byte.value); + System.out.println(" short " + a_short.value); + System.out.println(" string '" + a_string.value+"'"); + System.out.println(" double " + a_double.value); + } + + /** + * Test passing the string array, flexible size. + */ + public void testStringArray() + { + System.out.println("***** Pass string array."); + + String[] x = new String[] { "one", "two" }; + + // The array is passed as CORBA sequence, variable size is supported. + String[] y = object.passStrings(x); + + for (int i = 0; i < y.length; i++) + { + System.out.println(" Passed " + x [ i ] + ", returned: " + y [ i ]); + } + } + + /** + * Test passing the structures. + */ + public void testStructure() + { + System.out.println("***** Pass structure"); + + StructureToPass arg = new StructureToPass(); + arg.a = "A"; + arg.b = "B"; + + StructureToReturn r = object.passStructure(arg); + + System.out.println(" Fields of the returned structure:"); + + System.out.println(" c: " + r.c); + System.out.println(" n: " + r.n); + + // The field r.arra is declared as the fixed size CORBA array. + System.out.println(" r[0]: " + r.arra [ 0 ]); + System.out.println(" r[1]: " + r.arra [ 1 ]); + System.out.println(" r[3]: " + r.arra [ 2 ]); + } + + /** + * Test catching the system exception, thrown on the remote side. + */ + public void testSystemException() + { + System.out.println("**** Test system exception:"); + try + { + // Negative parameter = system exception. + object.throwException(-55); + } + catch (BAD_OPERATION ex) + { + System.out.println(" The expected BAD_OPERATION, minor code " + + ex.minor + ", has been thrown on remote side." + ); + } + catch (UserException uex) + { + throw new InternalError(); + } + } + + /** + * Test passing the tree structure. Any shape of the tree is + * supported without rewriting the code. + */ + public void testTree() + { + // Manually create the tree of nodes: + // Root + // +-- a + // | + // +-- b + // +-- ba + // | | + // | +-- bac + // | + // +-- bb + System.out.println("***** Pass and return the tree."); + + TreeNode n = nod("Root"); + + n.children = new TreeNode[] { nod("a"), nod("b") }; + n.children [ 1 ].children = new TreeNode[] { nod("ba"), nod("bb") }; + n.children [ 1 ].children [ 0 ].children = new TreeNode[] { nod("bac") }; + + TreeNodeHolder nh = new TreeNodeHolder(n); + + // The server should add '++' to each TreeNode name. + object.passTree(nh); + + // Convert the returned tree to some strig representation. + StringBuilder img = new StringBuilder(); + getImage(img, nh.value); + + System.out.println("Returned tree: " + img.toString()); + } + + /** + * Test catching the user exception, thrown on the remote side. + */ + public void testUserException() + { + System.out.println("**** Test user exception:"); + try + { + // The user exception contains one user-defined field that will + // be initialised to the passed parameter. + object.throwException(123); + throw new InternalError(); + } + catch (WeThrowThisException uex) + { + System.out.println(" The user exception with field " + uex.ourField + + ", has been thrown on remote side." + ); + } + } + + /** + * Passes wide (UTF-16) string and narrow (ISO8859_1) string. + * @see gnu.CORBA.GIOP.CharSets_OSF for supported and default + * encodings. + */ + public void testWideNarrowStrings() + { + System.out.println("**** Test 8 bit and 16 bit char strings"); + + String r = object.passCharacters("wide string", "narrow string"); + System.out.println(" returned: '" + r + "'"); + } + + /** + * Get the string representation of the passed tree. + * @param b the string buffer to accumulate the representation. + * @param n the tree (root TreeNode). + */ + private void getImage(StringBuilder b, TreeNode n) + { + b.append(n.name); + b.append(": ("); + + for (int i = 0; i < n.children.length; i++) + { + getImage(b, n.children [ i ]); + b.append(' '); + } + b.append(") "); + } + + /** + * Create a TreeNode with the given header. + * + * @param hdr the TreeNode header. + * @return the created TreeNode. + */ + private TreeNode nod(String hdr) + { + TreeNode n = new TreeNode(); + n.children = new TreeNode[ 0 ]; + n.name = hdr; + + return n; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/RequestTest.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/RequestTest.java new file mode 100644 index 000000000..9c908e520 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/RequestTest.java @@ -0,0 +1,284 @@ +/* RequestTest.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + + This file is part of GNU Classpath. + + GNU Classpath is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + GNU Classpath is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. + + Linking this library statically or dynamically with other modules is + making a combined work based on this library. Thus, the terms and + conditions of the GNU General Public License cover the whole + combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent + modules, and to copy and distribute the resulting executable under + terms of your choice, provided that you also meet, for each linked + independent module, the terms and conditions of the license of that + module. An independent module is a module which is not derived from + or based on this library. If you modify this library, you may extend + this exception to your version of the library, but you are not + obligated to do so. If you do not wish to do so, delete this + exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.SimpleCommunication.communication; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.ExceptionList; +import org.omg.CORBA.NVList; +import org.omg.CORBA.ORB; +import org.omg.CORBA.Request; +import org.omg.CORBA.TCKind; +import org.omg.CORBA.UnknownUserException; + +/** + * This code uses CORBA to call various methods of the remote object, + * passing data structures in both directions. It finds the server by + * reading the IOR.txt file that must be present in the folder, + * where the program has been started. + * + * The IOR.txt file is written by the server + * {@link gnu.classpath.examples.CORBA.SimpleCommunication.DemoServer}. + * The server should be reachable over Internet, unless blocked by + * security tools. + * + * This code is tested for interoperability with Sun Microsystems + * java implementation 1.4.2 (08.b03). Server, client of both can + * be started either on Sun's or on Classpath CORBA implementation, + * in any combinations. + * + * BE SURE TO START THE SERVER BEFORE STARTING THE CLIENT. + * + * Test invocations using org.omg.CORBA.Request. The methods are + * called by "name", like in java.lang.reflect. + * No need to have the local pre-compiled stub classes. + * + * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org) + */ +public class RequestTest +{ + /* + * The IOR.txt file, used to find the server and the object on the server. is written when starting the accompanying + */ + public static final String IOR_FILE = "IOR.txt"; + + /** + * The Object Request Brocker, used for various CORBA operations. + */ + ORB orb; + + /** + * Our remote object - the invocation target. + */ + org.omg.CORBA.Object object; + + /** + * Prepare for work. Read the file IOR.txt in the current folder + * and find the server using its information. + */ + public static void main(String[] args) + { + RequestTest we = new RequestTest(); + + we.orb = org.omg.CORBA.ORB.init(new String[ 0 ], null); + + char[] c = null; + try + { + File f = new File(IOR_FILE); + c = new char[ (int) f.length() ]; + + FileReader fr = new FileReader(f); + fr.read(c); + fr.close(); + } + catch (IOException ex) + { + System.out.println("Unable to write the IOR.txt into the current folder"); + ex.printStackTrace(); + } + + String ior = new String(c); + + we.object = we.orb.string_to_object(ior); + we.Demo(); + we.orb.shutdown(false); + } + + /** Run all demos. */ + public void Demo() + { + testHello(); + try + { + testParameters(); + } + catch (Exception ex) + { + // Not expected. + throw new InternalError(); + } + testSystemException(); + testWideNarrowStrings(); + } + + /** + * Send the hello message, one way. + */ + public void testHello() + { + System.out.println("***** Test 'HELLO WORLD' (see the server console)."); + + Request hello = + object._create_request(null, "sayHello", orb.create_list(0), null); + + // No response expected. + hello.send_oneway(); + } + + /** + * Test passing various parameters in both directions. + */ + public void testParameters() + throws Exception + { + System.out.println("***** Test passing multiple parameters:"); + + Request r = + object._create_request(null, "passSimple", orb.create_list(0), null); + + r.add_inout_arg().insert_octet((byte) 0); + r.add_in_arg().insert_long(2); + r.add_inout_arg().insert_short((short) 3); + r.add_inout_arg().insert_string("[string 4]"); + r.add_out_arg().type(orb.get_primitive_tc(TCKind.tk_double)); + + NVList para = r.arguments(); + + System.out.println(" --- Parameters before invocation: "); + + System.out.println(" octet " + para.item(0).value().extract_octet()); + System.out.println(" long (in parameter) " + + para.item(1).value().extract_long() + ); + System.out.println(" short " + para.item(2).value().extract_short()); + System.out.println(" string " + para.item(3).value().extract_string()); + + // For the last parameter, the value is not set. + r.set_return_type(orb.get_primitive_tc(TCKind.tk_long)); + + r.invoke(); + + para = r.arguments(); + + System.out.println(" --- Parameters after invocation:"); + + System.out.println(" octet " + para.item(0).value().extract_octet()); + System.out.println(" long (in parameter, must not be changed) " + + para.item(1).value().extract_long() + ); + System.out.println(" short " + para.item(2).value().extract_short()); + System.out.println(" string " + para.item(3).value().extract_string()); + System.out.println(" double " + para.item(4).value().extract_double()); + + System.out.println(" Returned value " + r.result().value().extract_long()); + } + + /** + * Test catching the system exception, thrown on the remote side. + */ + public void testSystemException() + { + System.out.println("**** Test system exception:"); + try + { + ExceptionList exList = orb.create_exception_list(); + exList.add(WeThrowThisExceptionHelper.type()); + + Request rq = + object._create_request(null, "throwException", orb.create_list(1), + null, exList, null + ); + + rq.add_in_arg().insert_long(-55); + + rq.invoke(); + + throw new InternalError(); + } + catch (BAD_OPERATION ex) + { + System.out.println(" The expected BAD_OPERATION, minor code " + + ex.minor + ", has been thrown on remote side." + ); + } + } + + /** + * Test catching the user exception, thrown on the remote side. + */ + public void testUserException() + { + System.out.println("**** Test user exception:"); + + ExceptionList exList = orb.create_exception_list(); + exList.add(WeThrowThisExceptionHelper.type()); + + Request rq = + object._create_request(null, "throwException", orb.create_list(1), null, + exList, null + ); + + rq.add_in_arg().insert_long(123); + rq.invoke(); + + UnknownUserException uku = (UnknownUserException) rq.env().exception(); + WeThrowThisException our_exception = WeThrowThisExceptionHelper.extract(uku.except); + + System.out.println(" Our user exception, field " + our_exception.ourField + + ", has been thrown on remote side." + ); + } + + /** + * Passes wide (UTF-16) string and narrow (ISO8859_1) string. + * @see gnu.CORBA.GIOP.CharSets_OSF for supported and default + * encodings. + */ + public void testWideNarrowStrings() + throws BAD_OPERATION + { + System.out.println("**** Test 8 bit and 16 bit char strings"); + + Request rq = + object._create_request(null, "passCharacters", orb.create_list(0), null); + + rq.add_in_arg().insert_wstring("wide string"); + rq.add_in_arg().insert_string("narrow string"); + + rq.set_return_type(orb.get_primitive_tc(TCKind.tk_wstring)); + + rq.invoke(); + + System.out.println(" Returned ' " + rq.result().value().extract_wstring()); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToPass.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToPass.java new file mode 100644 index 000000000..eecf6f3a6 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToPass.java @@ -0,0 +1,66 @@ +/* StructureToPass.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.SimpleCommunication.communication; + + +/** + * The data structure, passed from to the server from client in our tests. + * + * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org) + */ +public class StructureToPass + implements org.omg.CORBA.portable.IDLEntity +{ + /** + * Use serialVersionUID for interoperability. + */ + private static final long serialVersionUID = 1; + + /** + * The first string, stored in this structure (defined as + * "narrow string"). + */ + public String a; + + /** + * The second string, stored in this structure (define as + * "wide" (usually Unicode) string. + */ + public String b; +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToPassHelper.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToPassHelper.java new file mode 100644 index 000000000..155ad170b --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToPassHelper.java @@ -0,0 +1,103 @@ +/* StructureToPassHelper.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.SimpleCommunication.communication; + +import gnu.CORBA.OrbRestricted; + +import org.omg.CORBA.StructMember; +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * The helper operations for the {@link StructureToPass}. + * + * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org) + */ +public abstract class StructureToPassHelper +{ + /** + * The repository ID of the {@link StructureToPass}. + */ + private static String id = + "IDL:gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToPass:1.0"; + + /** + * Get the repository id. + */ + public static String id() + { + return id; + } + + /** + * Read the structure from the CDR stram. + */ + public static StructureToPass read(InputStream istream) + { + StructureToPass value = new StructureToPass(); + value.a = istream.read_string(); + value.b = istream.read_wstring(); + return value; + } + + /** + * Get the type code of this structure. + */ + public static synchronized TypeCode type() + { + StructMember[] members = new StructMember[2]; + TypeCode member = null; + member = OrbRestricted.Singleton.create_string_tc(0); + members[0] = new StructMember("a", member, null); + member = OrbRestricted.Singleton.create_string_tc(0); + members[1] = new StructMember("b", member, null); + return OrbRestricted.Singleton.create_struct_tc(StructureToPassHelper.id(), + "StructureToPass", members); + } + + /** + * Write the structure into the CDR stream. + */ + public static void write(OutputStream ostream, StructureToPass value) + { + ostream.write_string(value.a); + ostream.write_wstring(value.b); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToPassHolder.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToPassHolder.java new file mode 100644 index 000000000..5bbe6908e --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToPassHolder.java @@ -0,0 +1,37 @@ + + +package gnu.classpath.examples.CORBA.SimpleCommunication.communication; + +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.Streamable; + +public final class StructureToPassHolder + implements Streamable +{ + public StructureToPass value; + + public StructureToPassHolder() + { + } + + public StructureToPassHolder(StructureToPass initialValue) + { + value = initialValue; + } + + public void _read(InputStream i) + { + value = StructureToPassHelper.read(i); + } + + public org.omg.CORBA.TypeCode _type() + { + return StructureToPassHelper.type(); + } + + public void _write(OutputStream o) + { + StructureToPassHelper.write(o, value); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToReturn.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToReturn.java new file mode 100644 index 000000000..2f497cba4 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToReturn.java @@ -0,0 +1,71 @@ +/* StructureToReturn.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.classpath.examples.CORBA.SimpleCommunication.communication; + +import org.omg.CORBA.portable.IDLEntity; + +/** + * This data structure is returned from the server to client in our tests. + * + * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org) + */ +public class StructureToReturn + implements IDLEntity +{ + /** + * Use serialVersionUID for interoperability. + */ + private static final long serialVersionUID = 1; + + /** + * The string field. + */ + public String c; + + /** + * The CORBA array field. This field is handled as the fixed + * size CORBA array, but structures can also have the variable + * size CORBA sequences. + */ + public int[] arra = new int[3]; + + /** + * The int (CORBA long) field. + */ + public int n; +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToReturnHelper.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToReturnHelper.java new file mode 100644 index 000000000..83f422c52 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToReturnHelper.java @@ -0,0 +1,116 @@ +/* StructureToReturnHelper.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.classpath.examples.CORBA.SimpleCommunication.communication; + +import gnu.CORBA.OrbRestricted; + +import org.omg.CORBA.StructMember; +import org.omg.CORBA.TCKind; +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * This class defines the helper operations for {@link StructureToReturn}. + * + * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org) + */ +public abstract class StructureToReturnHelper +{ + /** + * The repository id. + */ + private static String _id = + "IDL:gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToReturn:1.0"; + + /** + * Return the repository id. + */ + public static String id() + { + return _id; + } + + /** + * Read the structure from the CDR stream. + */ + public static StructureToReturn read(InputStream istream) + { + StructureToReturn value = new StructureToReturn(); + value.n = istream.read_long(); + value.c = istream.read_wstring(); + value.arra = new int[ 3 ]; + + // Read the fixed size array. + for (int i = 0; i < 3; i++) + value.arra [ i ] = istream.read_long(); + return value; + } + + /** + * Create the typecode. + */ + public static synchronized TypeCode type() + { + StructMember[] members = new StructMember[3]; + TypeCode member = OrbRestricted.Singleton.get_primitive_tc(TCKind.tk_long); + members[0] = new StructMember("n", member, null); + member = OrbRestricted.Singleton.create_string_tc(0); + members[1] = new StructMember("c", member, null); + member = OrbRestricted.Singleton.get_primitive_tc(TCKind.tk_long); + member = OrbRestricted.Singleton.create_array_tc(3, member); + members[2] = new StructMember("arra", member, null); + return OrbRestricted.Singleton.create_struct_tc( + StructureToReturnHelper.id(), + "StructureToReturn", + members); + } + + /** + * Write the structure to the CDR stream. + */ + public static void write(OutputStream ostream, StructureToReturn value) + { + ostream.write_long(value.n); + ostream.write_wstring(value.c); + + // Write the fixed size array. + for (int i = 0; i < 3; i++) + ostream.write_long(value.arra [ i ]); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToReturnHolder.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToReturnHolder.java new file mode 100644 index 000000000..c70f9cfcc --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToReturnHolder.java @@ -0,0 +1,60 @@ + + +package gnu.classpath.examples.CORBA.SimpleCommunication.communication; + +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.Streamable; + +/** + * The holder for the structure, returned from the server. + */ +public final class StructureToReturnHolder + implements Streamable +{ + /** + * The enclosed structure. + */ + public StructureToReturn value = null; + + /** + * Create the empty holder. + */ + public StructureToReturnHolder() + { + } + + /** + * Crate the holder with the defined initial value. + */ + public StructureToReturnHolder(StructureToReturn initialValue) + { + value = initialValue; + } + + /** + * Read the value from the CDR stream. + */ + public void _read(InputStream in) + { + value = StructureToReturnHelper.read(in); + } + + /** + * Get the typecode of this structure. + */ + public TypeCode _type() + { + return StructureToReturnHelper.type(); + } + + /** + * Write the value from the CDR stream. + * @param out + */ + public void _write(OutputStream out) + { + StructureToReturnHelper.write(out, value); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/TreeNode.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/TreeNode.java new file mode 100644 index 000000000..4fb28345a --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/TreeNode.java @@ -0,0 +1,60 @@ +/* TreeNode.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.SimpleCommunication.communication; + +/** + * The support for the tree structure, used in the test of + * ability to pass and return the tree structure. + * + * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) + */ +public class TreeNode + implements org.omg.CORBA.portable.IDLEntity +{ + /** + * Use serialVersionUID for interoperability. + */ + private static final long serialVersionUID = 1; + + /** The TreeNode name */ + public String name = null; + + /** The TreeNode children. */ + public TreeNode[] children = null; +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/TreeNodeHelper.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/TreeNodeHelper.java new file mode 100644 index 000000000..eac1c9a24 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/TreeNodeHelper.java @@ -0,0 +1,162 @@ +/* TreeNodeHelper.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.SimpleCommunication.communication; + + +import gnu.CORBA.OrbRestricted; + +import org.omg.CORBA.Any; +import org.omg.CORBA.StructMember; +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * This class is used for various helper operations around the + * tree {@link} structure. + * + * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org) + */ +public abstract class TreeNodeHelper +{ + /** + * The TreeNode repository id, used to identify the structure. + */ + private static String _id = + "IDL:gnu/classpath/examples/CORBA/SimpleCommunication/communication/TreeNode:1.0"; + + /** + * Caches the typecode, allowing to compute it only once. + */ + private static TypeCode typeCode; + + /** + * This is used to handle the recursive object references in + * CORBA - supported way. The tree TreeNode definition is recursive, + * as the TreeNode contains the sequence of the nodes as its field. + */ + private static boolean active; + + /** + * Extract the tree TreeNode from the unversal CORBA wrapper, Any. + */ + public static TreeNode extract(Any a) + { + return read(a.create_input_stream()); + } + + /** + * Get the TreeNode string identifer. + */ + public static String id() + { + return _id; + } + + /** + * Insert the TreeNode into the universal CORBA wrapper, Any. + */ + public static void insert(Any a, TreeNode that) + { + OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + /** + * Read the TreeNode from the common data reprentation (CDR) stream. + */ + public static TreeNode read(InputStream istream) + { + TreeNode value = new TreeNode(); + value.name = istream.read_string(); + + int _len0 = istream.read_long(); + value.children = new TreeNode[ _len0 ]; + for (int i = 0; i < value.children.length; ++i) + value.children [ i ] = TreeNodeHelper.read(istream); + return value; + } + + /** + * Get the TreeNode type code definition. + */ + public static synchronized TypeCode type() + { + // Compute the type code only once. + if (typeCode == null) + { + synchronized (TypeCode.class) + { + if (typeCode == null) + { + // To avoid the infinite recursion loop, the + // recursive reference is handled in specific way. + if (active) + return OrbRestricted.Singleton.create_recursive_tc(_id); + active = true; + + // List all memebers of the TreeNode structure. + StructMember[] members = new StructMember[ 2 ]; + TypeCode memberType; + memberType = OrbRestricted.Singleton.create_string_tc(0); + members [ 0 ] = new StructMember("name", memberType, null); + memberType = OrbRestricted.Singleton.create_recursive_tc(""); + members [ 1 ] = new StructMember("children", memberType, null); + typeCode = + OrbRestricted.Singleton.create_struct_tc(TreeNodeHelper.id(), "TreeNode", members); + active = false; + } + } + } + return typeCode; + } + + /** + * Write the TreeNode into the common data reprentation (CDR) stream. + */ + public static void write(OutputStream ostream, TreeNode value) + { + ostream.write_string(value.name); + ostream.write_long(value.children.length); + for (int i = 0; i < value.children.length; ++i) + TreeNodeHelper.write(ostream, value.children [ i ]); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/TreeNodeHolder.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/TreeNodeHolder.java new file mode 100644 index 000000000..ec180ce57 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/TreeNodeHolder.java @@ -0,0 +1,100 @@ +/* TreeNodeHolder.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.SimpleCommunication.communication; + +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.Streamable; + +/** + * The TreeNode holder is a wrapper about the TreeNode data structure. It + * can be used where the TreeNode must be passed both to and from + * the method being called. The same structure holds the tree, + * as it can be represented as a root TreeNode with children. + * + * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org) + */ +public class TreeNodeHolder + implements Streamable +{ + /** + * Stores the TreeNode value. + */ + public TreeNode value; + + /** + * Creates the TreeNode holder with the null initial value. + */ + public TreeNodeHolder() + { + } + + /** + * Creates the TreeNode holder with the given initial value. + */ + public TreeNodeHolder(TreeNode initialValue) + { + value = initialValue; + } + + /** + * Reads the TreeNode value from the common data representation (CDR) + * stream. + */ + public void _read(InputStream in) + { + value = TreeNodeHelper.read(in); + } + + /** + * Writes the TreeNode value into common data representation (CDR) + * stream. + * @return + */ + public TypeCode _type() + { + return TreeNodeHelper.type(); + } + + public void _write(OutputStream out) + { + TreeNodeHelper.write(out, value); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/WeThrowThisException.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/WeThrowThisException.java new file mode 100644 index 000000000..fcf632b32 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/WeThrowThisException.java @@ -0,0 +1,75 @@ +/* WeThrowThisException.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.SimpleCommunication.communication; + +import org.omg.CORBA.UserException; +import org.omg.CORBA.portable.IDLEntity; + +/** + * Our user exception, thrown in the tests of handling the exceptions, + * thrown on remote side. The exception contains the user - defined + * data field that is transferred from client to the server when the + * exception is thrown. + * + * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org) + */ +public class WeThrowThisException + extends UserException + implements IDLEntity +{ + /** + * Use serialVersionUID for interoperability. + */ + private static final long serialVersionUID = 1; + + /** + * Our specific field, transferred to client. + */ + public int ourField; + + /** + * Create the exception. + * + * @param _ourField the value of our specific field. + */ + public WeThrowThisException(int _ourField) + { + ourField = _ourField; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/WeThrowThisExceptionHelper.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/WeThrowThisExceptionHelper.java new file mode 100644 index 000000000..23ebc8256 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/WeThrowThisExceptionHelper.java @@ -0,0 +1,117 @@ +/* WeThrowThisExceptionHelper.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.SimpleCommunication.communication; + +import gnu.CORBA.OrbRestricted; + +import org.omg.CORBA.Any; +import org.omg.CORBA.StructMember; +import org.omg.CORBA.TCKind; +import org.omg.CORBA.TypeCode; + +/** + * The class, providing various helper operations with our user + * exception. + * + * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org) + */ +public abstract class WeThrowThisExceptionHelper +{ + /** + * The exception repository id. This name is also used to find the + * mapping local CORBA class. + */ + private static String _id = + "IDL:gnu/classpath/examples/CORBA/SimpleCommunication/communication/WeThrowThisException:1.0"; + + /** + * Get the exception repository id. + */ + public static String id() + { + return _id; + } + + /** + * Extract the exception from the given Any where it might be + * wrapped. + */ + public static WeThrowThisException extract(Any a) + { + return read(a.create_input_stream()); + } + + /** + * Read the exception from the CDR stream. + */ + public static WeThrowThisException read(org.omg.CORBA.portable.InputStream istream) + { + WeThrowThisException value = new WeThrowThisException(0); + + // The repository ID is not used + istream.read_string(); + value.ourField = istream.read_long(); + return value; + } + + /** + * Create the type code of this exception. + */ + public static synchronized TypeCode type() + { + StructMember[] members = new StructMember[ 1 ]; + TypeCode member = null; + member = OrbRestricted.Singleton.get_primitive_tc(TCKind.tk_long); + members [ 0 ] = new StructMember("ourField", member, null); + return OrbRestricted.Singleton.create_struct_tc(WeThrowThisExceptionHelper.id(), + "WeThrowThisException", members + ); + } + + /** + * Write the exception into the CDR stream. + */ + public static void write(org.omg.CORBA.portable.OutputStream ostream, + WeThrowThisException value + ) + { + ostream.write_string(id()); + ostream.write_long(value.ourField); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/_DemoTesterImplBase.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/_DemoTesterImplBase.java new file mode 100644 index 000000000..02e5e1a49 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/_DemoTesterImplBase.java @@ -0,0 +1,209 @@ +/* _DemoTesterImplBase.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.SimpleCommunication.communication; + +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.ByteHolder; +import org.omg.CORBA.CompletionStatus; +import org.omg.CORBA.DoubleHolder; +import org.omg.CORBA.ShortHolder; +import org.omg.CORBA.StringHolder; +import org.omg.CORBA.StringSeqHelper; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.InvokeHandler; +import org.omg.CORBA.portable.ObjectImpl; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.ResponseHandler; + +/** + * The base for the class that is actually implementing the functionality + * of the object on the server side ({@link DemoServant} of our case). + * + * Following CORBA standards, the name of this class must start from + * underscore and end by the "ImplBase". + * + * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org) + */ +public abstract class _DemoTesterImplBase + extends ObjectImpl + implements DemoTester, InvokeHandler +{ +/** + * When the server receives the request message from client, it + * calls this method. + * + * @param a_method the method name. + * @param in the CDR stream, from where the implementing code must + * read the method parameters. + * @param rh the response handler, used to get the stream where + * the returned values must be written. + * + * @return the stream, obtained from the response handler. + */ + public OutputStream _invoke(String a_method, InputStream in, + ResponseHandler rh + ) + { + OutputStream out; + + /* Get the field value. */ + if (a_method.equals("_get_theField")) + { + int result = (int) 0; + result = theField(); + out = rh.createReply(); + out.write_long(result); + } + else + /* Set the field value. */ + if (a_method.equals("_set_theField")) + { + int newTheField = in.read_long(); + theField(newTheField); + out = rh.createReply(); + } + else + /* Logs calls to the file. */ + if (a_method.equals("sayHello")) + { + sayHello(); + out = rh.createReply(); + } + else + /* Passes various parameters in both directions. */ + if (a_method.equals("passSimple")) + { + ByteHolder an_octet = new ByteHolder(); + an_octet.value = in.read_octet(); + + int a_long = in.read_long(); + ShortHolder a_short = new ShortHolder(); + a_short.value = in.read_short(); + + StringHolder a_string = new StringHolder(); + a_string.value = in.read_string(); + + DoubleHolder a_double = new DoubleHolder(); + int result = passSimple(an_octet, a_long, a_short, a_string, a_double); + out = rh.createReply(); + out.write_long(result); + out.write_octet(an_octet.value); + out.write_short(a_short.value); + out.write_string(a_string.value); + out.write_double(a_double.value); + } + else + /* Passes the 'wide' (usually Unicode) string and the ordinary string. */ + if (a_method.equals("passCharacters")) + { + String wide = in.read_wstring(); + String narrow = in.read_string(); + String result = null; + result = passCharacters(wide, narrow); + out = rh.createReply(); + out.write_wstring(result); + } + else + /* + Throws either 'WeThrowThisException' with the 'ourField' field + initialised to the passed positive value + or system exception (if the parameter is zero or negative). + */ + if (a_method.equals("throwException")) + { + try + { + int parameter = in.read_long(); + throwException(parameter); + out = rh.createReply(); + } + catch (WeThrowThisException exception) + { + out = rh.createExceptionReply(); + WeThrowThisExceptionHelper.write(out, exception); + } + } + else + /* Passes and returns the structures. */ + if (a_method.equals("passStructure")) + { + StructureToPass in_structure = StructureToPassHelper.read(in); + StructureToReturn result = null; + result = passStructure(in_structure); + out = rh.createReply(); + StructureToReturnHelper.write(out, result); + } + else + /* Passes and returns the string sequence. */ + if (a_method.equals("passStrings")) + { + String[] arg = StringSeqHelper.read(in); + String[] result = null; + result = passStrings(arg); + out = rh.createReply(); + StringSeqHelper.write(out, result); + } + else + /** Pass and return the tree structure */ + if (a_method.equals("passTree")) + { + TreeNodeHolder tree = new TreeNodeHolder(); + tree.value = TreeNodeHelper.read(in); + passTree(tree); + out = rh.createReply(); + TreeNodeHelper.write(out, tree.value); + } + + else + throw new BAD_OPERATION("No method: " + a_method, 0, + CompletionStatus.COMPLETED_MAYBE + ); + + return out; + } + + /** + * Return an array of this object repository ids. + */ + public String[] _ids() + { + // They are the same as for the stub. + return _DemoTesterStub._ids; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/_DemoTesterStub.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/_DemoTesterStub.java new file mode 100644 index 000000000..7481c4ead --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/_DemoTesterStub.java @@ -0,0 +1,429 @@ +/* _DemoTesterStub.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.SimpleCommunication.communication; + +import org.omg.CORBA.ByteHolder; +import org.omg.CORBA.DoubleHolder; +import org.omg.CORBA.MARSHAL; +import org.omg.CORBA.ShortHolder; +import org.omg.CORBA.StringHolder; +import org.omg.CORBA.StringSeqHelper; +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.ObjectImpl; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.RemarshalException; + +/** + * The stub (proxy) class, representing the remote object on the client + * side. It has all the same methods as the actual implementation + * on the server side. These methods contain the code for remote + * invocation. + * + * Following CORBA standards, the name of this class must start from + * underscore and end by the "Stub". + * + * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org) + */ +public class _DemoTesterStub + extends ObjectImpl + implements DemoTester +{ + /** + * A string array of DemoTester repository ids. + */ + public static String[] _ids = + { + "IDL:gnu/classpath/examples/CORBA/SimpleCommunication/communication/DemoTester:1.0" + }; + + /** + * Return an array of DemoTester repository ids. + */ + public String[] _ids() + { + return _ids; + } + + /** + * Passes wide (UTF-16) string and narrow (ISO8859_1) string. + * @see gnu.CORBA.GIOP.CharSets_OSF for supported and default + * encodings. + */ + public String passCharacters(String wide, String narrow) + { + InputStream in = null; + try + { + // Get the output stream. + OutputStream out = _request("passCharacters", true); + + // Write the parameters. + + // The first string is passed as "wide" + // (usually 16 bit UTF-16) string. + out.write_wstring(wide); + + // The second string is passed as "narrow" + // (usually 8 bit ISO8859_1) string. + out.write_string(narrow); + + // Do the invocation. + in = _invoke(out); + + // Read the method return value. + String result = in.read_wstring(); + return result; + } + catch (ApplicationException ex) + { + // The exception has been throws on remote side, but we + // do not expect any. Throw the MARSHAL exception. + in = ex.getInputStream(); + throw new MARSHAL(ex.getId()); + } + catch (RemarshalException _rm) + { + // This exception means that the parameters must be re-written. + return passCharacters(wide, narrow); + } + finally + { + // Release the resources, associated with the reply stream. + _releaseReply(in); + } + } + + /** + * Passes various parameters in both directions. The parameters that + * shoud also return the values are wrapped into holders. + */ + public int passSimple(ByteHolder an_octet, int a_long, ShortHolder a_short, + StringHolder a_string, DoubleHolder a_double + ) + { + InputStream in = null; + try + { + // Get the stream where the parameters must be written: + OutputStream out = _request("passSimple", true); + + // Write the parameters. + out.write_octet(an_octet.value); + out.write_long(a_long); + out.write_short(a_short.value); + out.write_string(a_string.value); + + // Invoke the method. + in = _invoke(out); + + // Read the returned values. + int result = in.read_long(); + + // Read the inout and out parameters. + an_octet.value = in.read_octet(); + a_short.value = in.read_short(); + a_string.value = in.read_string(); + a_double.value = in.read_double(); + return result; + } + catch (ApplicationException ex) + { + // Handle excepion on remote side. + in = ex.getInputStream(); + throw new MARSHAL(ex.getId()); + } + catch (RemarshalException _rm) + { + // Handle instruction to resend the parameters. + return passSimple(an_octet, a_long, a_short, a_string, a_double); + } + finally + { + _releaseReply(in); + } + } + + /** + Passes and returns the string sequence. + */ + public String[] passStrings(String[] arg) + { + InputStream in = null; + try + { + // Get the stream where the parameters must be written: + OutputStream out = _request("passStrings", true); + + // Wrap the string array using the string sequence helper. + StringSeqHelper.write(out, arg); + + // Invoke the method. + in = _invoke(out); + + // Read the returned result using the string sequence helper. + String[] result = StringSeqHelper.read(in); + return result; + } + catch (ApplicationException ex) + { + // Handle the exception, thrown on remote side. + in = ex.getInputStream(); + throw new MARSHAL(ex.getId()); + } + catch (RemarshalException _rm) + { + return passStrings(arg); + } + finally + { + _releaseReply(in); + } + } + + /** + Passes and returns the structures. + */ + public StructureToReturn passStructure(StructureToPass in_structure) + { + InputStream in = null; + try + { + // Get the stream where the parameters must be written. + OutputStream out = _request("passStructure", true); + + // Write the structure, using its helper. + StructureToPassHelper.write(out, in_structure); + + // Invoke the method. + in = _invoke(out); + + // Read the returned structer, using another helper. + StructureToReturn result = StructureToReturnHelper.read(in); + return result; + } + catch (ApplicationException ex) + { + in = ex.getInputStream(); + throw new MARSHAL(ex.getId()); + } + catch (RemarshalException _rm) + { + return passStructure(in_structure); + } + finally + { + _releaseReply(in); + } + } + + /** + * Pass and return the tree structure + */ + public void passTree(TreeNodeHolder tree) + { + InputStream in = null; + try + { + // Get the stream where the parameters must be written. + OutputStream out = _request("passTree", true); + + // Write the tree (TreeNode with its chilred, grandchildren and so on), + // using the appropriate helper. + TreeNodeHelper.write(out, tree.value); + + // Call the method. + in = _invoke(out); + + // Read the returned tree. + tree.value = TreeNodeHelper.read(in); + } + catch (ApplicationException ex) + { + // Handle eception on remote side. + in = ex.getInputStream(); + throw new MARSHAL(ex.getId()); + } + catch (RemarshalException _rm) + { + passTree(tree); + } + finally + { + _releaseReply(in); + } + } + + /** + * One way call of the remote method. + */ + public void sayHello() + { + InputStream in = null; + try + { + // As we do not expect any response, the second + // parameter is 'false'. + OutputStream out = _request("sayHello", false); + in = _invoke(out); + } + catch (ApplicationException ex) + { + in = ex.getInputStream(); + throw new MARSHAL(ex.getId()); + } + catch (RemarshalException _rm) + { + sayHello(); + } + finally + { + _releaseReply(in); + } + } + + /** + * Get the field value. + */ + public int theField() + { + InputStream in = null; + try + { + // The special name of operation instructs just to get + // the field value rather than calling the method. + OutputStream out = _request("_get_theField", true); + in = _invoke(out); + + int result = in.read_long(); + return result; + } + catch (ApplicationException ex) + { + in = ex.getInputStream(); + throw new MARSHAL(ex.getId()); + } + catch (RemarshalException _rm) + { + return theField(); + } + finally + { + _releaseReply(in); + } + } + + /** + * Set the field value. + */ + public void theField(int newTheField) + { + InputStream in = null; + try + { + // The special name of operation instructs just to set + // the field value rather than calling the method. + OutputStream out = _request("_set_theField", true); + out.write_long(newTheField); + in = _invoke(out); + } + catch (ApplicationException ex) + { + in = ex.getInputStream(); + throw new MARSHAL(ex.getId()); + } + catch (RemarshalException _rm) + { + theField(newTheField); + } + finally + { + _releaseReply(in); + } + } + + /** + * The server side exception tests. + * + * @param parameter the server throws the user exception in the case + * of the positive value of this argument, and system + * exception otherwise. + * + * @throws WeThrowThisException + */ + public void throwException(int parameter) + throws WeThrowThisException + { + InputStream in = null; + try + { + // Get stream. + OutputStream out = _request("throwException", true); + + // Write parameter. + out.write_long(parameter); + + // Call method. + in = _invoke(out); + } + catch (ApplicationException ex) + { + in = ex.getInputStream(); + + // Get the exception id. + String id = ex.getId(); + + // If this is the user exception we expect to catch, read and throw + // it here. The system exception, if thrown, is handled by _invoke. + if (id.equals("IDL:gnu/classpath/examples/CORBA/SimpleCommunication/communication/WeThrowThisException:1.0") + ) + throw WeThrowThisExceptionHelper.read(in); + else + throw new MARSHAL(id); + } + catch (RemarshalException _rm) + { + throwException(parameter); + } + finally + { + _releaseReply(in); + } + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/README.html b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/README.html new file mode 100644 index 000000000..a3a9e6282 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/README.html @@ -0,0 +1,493 @@ + + + Five-in-a-row v 0.0 + + +

+ Five-in-a-row + 0.0 supplementary documentation +

+

Introduction and rules +

+

+ Five-in-a-row + is a two player strategy game. The players + are connected via network using CORBA-based RMI/IIOP protocol and + make they moves with the help of the Swing-based + interface. While playing, the users can also chat. +

+

The system consists of the single server and any number of + interconnected players. The person, willing to play, starts the + client and connects the server. The server redirects call to the + partner that has previously connected the same server, also willing + to play. +

+

The game desk is a field where it is possible to set O's + and X'es, one per move. The goal is to get five O's in a row while + preventing your partner from getting five X's in a row. Vertical, + horizontal and diagonal rows are allowed. The system detects the + loss-victory situation on the desk, but currently does not serve as a + playing partner, requiring at least two human players for this game. +

+

Both players can at any time reset the game (restarting it with + the same player) or leave the game (disconnecting). The disconnected + player can contact the game manager again, requesting to find another + partner. +

+

Simple as it is, the application has some features of the typical + role playing game that frequently just has more states, actions, + possible moves and also provides far richer graphics environment. The + game manger serves as a World-Wide-Pub where you can always find a + partner to play. + + The players can made both unsynchronized (chatting, game reset and + leaving) and synchronized (moves) actions. The game state changes + while playing, and the set of the available actions depends on the + current state. Finally, the mouse and canvas are involved. However + using RMI/IIOP machinery allowed to implement all this functionality + with just 13 classes (plus 4 generated), all of them being rather + simple. + + This example refers to the standard classes only and must be buildable + from your IDE as long as it has any java 1.4 compiler. +

+

+ The used IIOP protocol must ensure interoperability, allowing players + to use different java virtual machines and operating systems. + The processors may have the opposite byte order. +

+

Configuration and run +

+

The game manager server executable class is + gnu.classpath.examples.CORBA.swing.x5.X5Server + . After start, + it will print to console the Internet address that must be entered to + the client to reach the manager. +

+

The client executable class it + gnu.classpath.examples.CORBA.swing.x5.Demo + . +

+

The game should run with GNU Classpath + 0.19 and Sun Microsystems java 1.5.0_04. Due later fixed bugs it will + not run with the older versions of these two implementations. +

+

The game manager HTTP server uses port + 1500. Hence all firewalls between the server and the player must be + configured to allow HTTP on 1500. The ports, used by the RMI/IIOP are + not persistent. GNU Classpath is configured to take ports 1501, 1502 + and 1503 (the firewalls must allow to use them for RMI/IIOP). The + CORBA implementation other than Classpath may use different port + values. Unfortunately, there is no standard method to configure the + used port range in a vendor-independent way. +

+

The game server +

+

The game manager is first reachable via http:// protocol (for + instance http://123.456.7.89:1500). The simple server at this port + always serves much longer string, representing the CORBA stringified + object reference (IOR). The + Five-in-a-row  + client uses + this reference to find and access the remote game server object. +

+

If the server player queue is empty, it simply queues this player. + If the queue is not empty, the server introduces the arrived player + and queued player to each other as leaves the them alone. When + playing, the two clients communicate with each other directly, so the + server is just a “meeting point” where the players can + find each other. The game server is a console-only application. +

+

The initial server http:// address must be transferred to players + by some other means of communication (web chat, E-mail, link in a web + site and so on). The server writes this address to the specified + file, and the client can also take the default value from the same + file. This is convenient when all applications run on a single + machine, but also may be used to transfer the address via shared + filesystem. +

+

The game client +

+

The clients are Swing-based GUI applications, capable for remote + communication with each other and with the game manager. They have a + set of predefined states and switch between these states in + accordance to the preprogrammed logic. The client states are defined + in the + State + interface. They are displayed in the bottom left + corner of the window and are summarized in the following table: +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Our state + + Partner state + + Possible actions + + Comment +
+ Disconnected + + Partner not accessible + + Connect + + Initial state. +
+ Queued + + Partner not accessible + + Leave + + Queued by the game manager. +
+ I think. + + I wait for your move + + Make move, reset game, leave, chat. + + The person who waited for another player to come starts + the game first. +
+ I wait for your move + + I think + + Chat, reset game, leave. + + After the partner makes the move, the state changes to + I think + , unless the end of game situation is detected by + the desk analyzer. +
+ I have lost + + I have won + + Chat, reset game, leave. + + Can be entered with the help of the desk analyzer only. +
+ I have won + + I have lost + + Chat, reset game, leave + + Can be entered with the help of the desk analyzer only. +
+ Error + + Any + + Chat, leave + + This should never happen under normal work, but the demo + program may be modified by the user. +
+
+
+ As it is seen, being in one of the states, the client expects to + be the partner client in a certain defined state, and both clients + change they states in a synchronized manner. Each state has its own + set of the available actions and each action either preserves the + current state (chat, reset) or changes it following the rules. For + this simple example, the state change rules are obvious. +

The used RMI-IIOP architecture +

+ Both player and game manager servants are derived from the + org.omg.PortableServer.Servant + and, being servants, are simply + connected to the + POA + with + POA.servant_to_reference + . The + first remote object (game manager) is found using the stringified + object reference. No naming service is involved. +

+Where required, the CORBA objects are narrowed into required +player and game manager interfaces using method +PortableRemoteObject.narrow(org.omg.CORBA.Object object, Class + interface_class) +, passing the actual interface of the object as +the second parameter. After narrowing, the remote side obtains +possibility to invoke remote methods, defined in the interface of +this object. After the first remote object is found, other objects +can be simply passed as the method parameters. For instance, the game +manager introduces another player by passing its reference as a +parameter to the method +Player.start_game. + +

Class and interface summary +

+ + + + + + + + + + + + + + +
+ Executables classes +
+ Demo + + The main executable class of the game client. +
+ X5Server + + The main executable class of the game manager server. +
+

+ + + + + + + + + + + + + + + + +
+ Interface Summary +
+ GameManager + + The game manager interface. +
+ Player + + Defines remote methods that are invoked by another player or by + the challenge server. +
+ State + + Defines the states in that the player can be. +
+  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Class Summary +
+ _GameManager_Stub + + Normally generated with rmic compiler, this class represents + the GameManager Stub on the client side. +
+ _GameManagerImpl_Tie + + Normally generated with rmic compiler, this class represents + the GameManager Tie on the client side. +
+ _Player_Stub + + Generate with rmic, command line rmic -iiop -poa -keep + gnu.classpath.examples.CORBA.swing.x5.PlayerImpl (the compiled + package must be present in the current folder). +
+ _PlayerImpl_Tie + + Generate with rmic, command line rmic -iiop -poa -keep + gnu.classpath.examples.CORBA.swing.x5.PlayerImpl (the compiled + package must be present in the current folder). +
+ ChatConstants + + The chat color code constants, used to indicate who is talking. +
+ ClientFrame + + The JFrame of the GUI client. +
+ GameManagerImpl + + The manager connects two players into the game. +
+ IorReader + + Reads the remote URL. +
+ OrbStarter + + Starts the ORBs, involved into this application. +
+ PlayerImpl + + The implementation of the PlayerCommunicator, providing the + local functionality. +
+ PlayingDesk + + Manages actions, related to the game rules and also does all + painting. +
+

See also +

+

+ http://www.javascripter.net/games/xo/xo.htm + +

+

+ http://www.leepoint.net/notes-java/45examples/55games/five/five.html + +

+

Copyright +

+

+ Copyright (C) 2005 Free Software Foundation, + Inc. This file is part of GNU Classpath. GNU Classpath is free + software; you can redistribute it and/or modify it under the terms of + the GNU General Public License as published by the Free Software + Foundation; either version 2, or (at your option) any later version. + GNU Classpath is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. You should have received a + copy of the GNU General Public License along with GNU Classpath; see + the file COPYING. If not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + Linking this library statically or dynamically with other modules is + making a combined work based on this library. Thus, the terms and + conditions of the GNU General Public License cover the whole + combination. As a special exception, the copyright holders of this + library give you permission to link this library with independent + modules to produce an executable, regardless of the license terms of + these independent modules, and to copy and distribute the resulting + executable under terms of your choice, provided that you also meet, + for each linked independent module, the terms and conditions of the + license of that module. An independent module is a module which is + not derived from or based on this library. If you modify this + library, you may extend this exception to your version of the + library, but you are not obligated to do so. If you do not wish to do + so, delete this exception statement from your version. + +

+

+
+
+

+

+First version written by +Audrius Meškauskas +

+ + diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/CanvasWorld.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/CanvasWorld.java new file mode 100644 index 000000000..5ec902dbd --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/CanvasWorld.java @@ -0,0 +1,307 @@ +/* CanvasWorld.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + + This file is part of GNU Classpath. + + GNU Classpath is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + GNU Classpath is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. + + Linking this library statically or dynamically with other modules is + making a combined work based on this library. Thus, the terms and + conditions of the GNU General Public License cover the whole + combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent + modules, and to copy and distribute the resulting executable under + terms of your choice, provided that you also meet, for each linked + independent module, the terms and conditions of the license of that + module. An independent module is a module which is not derived from + or based on this library. If you modify this library, you may extend + this exception to your version of the library, but you are not + obligated to do so. If you do not wish to do so, delete this + exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.swing.x5; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.Point; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; + +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JScrollPane; + +/** + * The purpose of this simple example is to check if the mouse events are + * correctly received in a scrollable canvas and also if the canvas are + * correctly repainted. The similar canvas are used in various games and + * interactive demonstrations. + * + * The user can set one of the three possible figures with the different + * mouse buttons. The figure must be set where the user have clicked the + * mouse. + * + * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) + */ +public class CanvasWorld + extends JComponent + implements MouseListener, State +{ + /** + * Use serialVersionUID for interoperability. + */ + private static final long serialVersionUID = 1; + + /** + * Red oval, set by the left mouse button. + */ + public static final int RED = 0; + + /** + * Black cross, set by the right mouse button. + */ + public static final int BLACK = 1; + + /** + * Blue and smaller oval, set by the middle mouse button. + */ + public static final int HINT = 2; + + /** + * The message string is displayed at the top of the window. + */ + String message = "Click left, right or middle button in to set the figure"; + + /** + * The additinal message, related to the mouse events. + */ + String mouse = "No mouse event so far"; + + /** + * The grid spacing. + */ + static int W = 16; + + /** + * The radius of the dots being painted. + */ + static int R = W / 3; + + /** + * The collection of the red dots. + */ + ArrayList reds = new ArrayList(); + + /** + * The collection of the black crosses. + */ + ArrayList blacks = new ArrayList(); + + /** + * The collection of the smaller blue crosses. + */ + ArrayList hints = new ArrayList(); + + public CanvasWorld() + { + try + { + addMouseListener(this); + } + catch (Exception e) + { + throw new AssertionError(e); + } + } + + /** + * Paint this component. + */ + public void paintComponent(Graphics g) + { + int w = getWidth(); + int h = getHeight(); + + g.setColor(Color.white); + g.fillRect(0, 0, w, h); + + drawGrid(w, h, g); + + g.setColor(Color.black); + + g.drawString(message, W, W); + g.drawString(mouse, W, 2*W); + + drawFigures(g); + } + + /** + * Check for the presence of the given point in the collection. + */ + public final boolean pointPresent(int x, int y, Collection in) + { + Iterator iter = in.iterator(); + Point p; + while (iter.hasNext()) + { + p = (Point) iter.next(); + if (p.x == x && p.y == y) + return true; + } + return false; + } + + public void drawGrid(int w, int h, Graphics g) + { + g.setColor(Color.lightGray); + + int xs = 2*W+W/2; + + // Draw vertical lines: + for (int x = 0; x < w; x += W) + { + g.drawLine(x, xs, x, h); + } + + // Draw horizontal lines: + for (int y = 3*W; y < h; y += W) + { + g.drawLine(0, y, w, y); + } + + g.setColor(Color.gray); + } + + public void drawFigures(Graphics g) + { + g.setColor(Color.red); + drawDots(reds, g, RED); + + g.setColor(Color.black); + drawDots(blacks, g, BLACK); + + g.setColor(Color.blue); + drawDots(hints, g, HINT); + } + + public Point makePoint(int x, int y) + { + return new Point(x / W, y / W); + } + + /** + * Draw a collection of dots (the collor must be set before calling the + * method). + */ + public void drawDots(Collection dots, Graphics g, int mode) + { + Iterator iter = dots.iterator(); + int x; + int y; + + int hW = W / 2; + int RR = R * 2; + int hR = R / 2; + Point p; + while (iter.hasNext()) + { + p = (Point) iter.next(); + x = p.x * W + hW; + y = p.y * W + hW; + + if (mode == RED) + g.drawOval(x - R, y - R, RR, RR); + else if (mode == BLACK) + { + g.drawLine(x - R, y - R, x + R, y + R); + g.drawLine(x - R, y + R, x + R, y - R); + } + else + { + // Hint. + g.drawOval(x - hR, y - hR, R, R); + } + } + } + + public void mouseClicked(MouseEvent e) + { + int x = e.getX(); + int y = e.getY(); + + Point p = makePoint(x, y); + + // Ignore clicks on the occupied cells. + if (pointPresent(p.x, p.y, reds) || (pointPresent(p.x, p.y, blacks))) + { + message = "Clicked on the occupied cell."; + return; + } + else + message = "Figure set at ["+p.x+","+p.y+"]"; + + if (e.getButton() == MouseEvent.BUTTON1) + reds.add(p); + else if (e.getButton() == MouseEvent.BUTTON3) + blacks.add(p); + else if (e.getButton() == MouseEvent.BUTTON2) + hints.add(p); + repaint(); + } + + public void mouseEntered(MouseEvent m) + { + mouse = "Mouse entered."; + repaint(); + } + + public void mousePressed(MouseEvent m) + { + mouse = "Mouse pressed at "+m.getX()+","+m.getY(); + repaint(); + } + + public void mouseReleased(MouseEvent m) + { + mouse = "Mouse released at "+m.getX()+","+m.getY(); + repaint(); + } + + public void mouseExited(MouseEvent m) + { + mouse = "Mouse exited"; + repaint(); + } + + public static void main(String[] args) + { + JFrame frame = new JFrame(); + CanvasWorld world = new CanvasWorld(); + world.setPreferredSize(new Dimension(1000,1000)); + frame.add(new JScrollPane(world)); + frame.setSize(400, 200); + frame.setVisible(true); + } + +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/ChatConstants.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/ChatConstants.java new file mode 100644 index 000000000..5b3d7557b --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/ChatConstants.java @@ -0,0 +1,80 @@ +/* ChatConstants.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + + This file is part of GNU Classpath. + + GNU Classpath is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + GNU Classpath is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. + + Linking this library statically or dynamically with other modules is + making a combined work based on this library. Thus, the terms and + conditions of the GNU General Public License cover the whole + combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent + modules, and to copy and distribute the resulting executable under + terms of your choice, provided that you also meet, for each linked + independent module, the terms and conditions of the license of that + module. An independent module is a module which is not derived from + or based on this library. If you modify this library, you may extend + this exception to your version of the library, but you are not + obligated to do so. If you do not wish to do so, delete this + exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.swing.x5; + +import java.awt.Color; + +/** + * The chat color code constants, used to indicate who is talking. + * Additionally, the red color is reseved for the most important messages, + * related to the start and end of the game. + * + * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) + */ +public class ChatConstants +{ + /** + * Messages from the local system. + */ + public static byte SYSTEM = 0; + + /** + * Mirrored messsages from the local player. + */ + public static byte SELF = 1; + + /** + * Messages from the remote player. + */ + public static byte REMOTE_PLAYER = 2; + + /** + * Messages from the game server/ + */ + public static byte GAME_SERVER = 3; + + /** + * The array of the used colors. + */ + public static Color[] colors = + new Color[] + { + Color.black, new Color(0, 80, 0), new Color(0, 0, 128), Color.blue + }; +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/ClientFrame.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/ClientFrame.java new file mode 100644 index 000000000..04b8dd976 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/ClientFrame.java @@ -0,0 +1,417 @@ +/* ClientFrame.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + + This file is part of GNU Classpath. + + GNU Classpath is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + GNU Classpath is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. + + Linking this library statically or dynamically with other modules is + making a combined work based on this library. Thus, the terms and + conditions of the GNU General Public License cover the whole + combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent + modules, and to copy and distribute the resulting executable under + terms of your choice, provided that you also meet, for each linked + independent module, the terms and conditions of the license of that + module. An independent module is a module which is not derived from + or based on this library. If you modify this library, you may extend + this exception to your version of the library, but you are not + obligated to do so. If you do not wish to do so, delete this + exception statement from your version. */ + +package gnu.classpath.examples.CORBA.swing.x5; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.GridLayout; +import java.awt.event.*; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; + +import java.rmi.RemoteException; + +import javax.rmi.PortableRemoteObject; + +import javax.swing.*; +import java.awt.Dimension; + +/** + * The JFrame of the GUI client. + * + * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) + */ +public class ClientFrame + extends JFrame +{ + /** + * The size of the playing field. + */ + public final Dimension DESK_SIZE = + new Dimension(624, 352-PlayingDesk.W); + + /** + * Use serialVersionUID for interoperability. + */ + private static final long serialVersionUID = 1; + + // Define the application components: + + /** + * Central panel where the main action takes place. + */ + PlayingDesk desk = new PlayingDesk(); + + /** + * The scroll pane for canvas. + */ + JScrollPane scroll = new JScrollPane(); + + /** + * Will remember the manager IOR. + */ + String mior = ""; + + // The bottom panel contains the area that is used both to enter URL and + // for chatting. + JPanel pnBottom = new JPanel(); + + BorderLayout layBottom = new BorderLayout(); + + JTextField taUrl = new JTextField(); + + // The top primitive chatting panel, composed from labels. + JPanel pnChat = new JPanel(); + + GridLayout layChat = new GridLayout(); + + JLabel lbC3 = new JLabel(); + + JLabel lbC2 = new JLabel(); + + JLabel lbC1 = new JLabel(); + + // The button panel. + JPanel pnButtons = new JPanel(); + + GridLayout layButtons = new GridLayout(); + + JButton bLeave = new JButton(); + + JButton bConnect = new JButton(); + + JButton bExit = new JButton(); + + JButton bReset = new JButton(); + + JLabel lbState = new JLabel(); + + JButton bChat = new JButton(); + + JButton bPaste = new JButton(); + + public ClientFrame() + { + try + { + jbInit(); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + private void jbInit() + throws Exception + { + desk.frame = this; + + pnBottom.setLayout(layBottom); + + pnChat.setLayout(layChat); + layChat.setColumns(1); + layChat.setRows(3); + + lbC1.setText("This program needs the game server (see README on how to start it)."); + lbC2.setText("Enter the game server address (host:port)"); + lbC3.setText("Pressing \'Connect\' with the empty address will start the server on " + + "the local machine."); + bLeave.setEnabled(true); + bLeave.setToolTipText("Leave if either you have lost or do not want longer to play with " + + "this partner."); + bLeave.setText("Leave game"); + bLeave.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + bLeave_actionPerformed(e); + } + }); + bConnect.setToolTipText("Connect your playing partner"); + bConnect.setText("Connect"); + bConnect.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + bConnect_actionPerformed(e); + } + }); + pnButtons.setLayout(layButtons); + bExit.setToolTipText("Exit this program"); + bExit.setText("Exit"); + bExit.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + bExit_actionPerformed(e); + } + }); + layButtons.setHgap(2); + bReset.setToolTipText("Restart the game. The partner may choose to exit!"); + bReset.setText("Reset game"); + bReset.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + bReset_actionPerformed(e); + } + }); + lbState.setText("Disconnected"); + bChat.setToolTipText("Send message to player. Reuse the address "+ + "field to enter the message."); + bChat.setText("Chat"); + bChat.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + bChat_actionPerformed(e); + } + }); + + bPaste.setText("Paste"); + bPaste.setToolTipText("Paste, same as Ctrl-V"); + bPaste.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + bPaste_actionPerformed(e); + } + }); + + desk.setMaximumSize(DESK_SIZE); + desk.setPreferredSize(DESK_SIZE); + + scroll.getViewport().add(desk, null); + getContentPane().add(scroll, BorderLayout.CENTER); + getContentPane().add(pnBottom, BorderLayout.SOUTH); + + pnBottom.add(taUrl, BorderLayout.CENTER); + pnBottom.add(pnChat, BorderLayout.NORTH); + + pnChat.add(lbC1, null); + pnChat.add(lbC2, null); + pnChat.add(lbC3, null); + pnBottom.add(pnButtons, BorderLayout.SOUTH); + pnButtons.add(lbState, null); + pnButtons.add(bConnect, null); + pnButtons.add(bChat, null); + pnButtons.add(bLeave, null); + pnButtons.add(bReset, null); + pnButtons.add(bExit, null); + pnButtons.add(bPaste, null); + + desk.player.set_current_state(State.DISCONNECTED); + } + + /** + * Handles exit procedure. + */ + protected void processWindowEvent(WindowEvent e) + { + super.processWindowEvent(e); + if (e.getID() == WindowEvent.WINDOW_CLOSING) + { + bExit_actionPerformed(null); + } + } + + /** + * Handles the connection procedure. + */ + void bConnect_actionPerformed(ActionEvent e) + { + try + { + int state = desk.player.get_current_state(); + + if (state == State.DISCONNECTED || state == State.ERROR) + { + talk(ChatConstants.colors[0], "Connecting..."); + + if (desk.manager == null) + { + mior = taUrl.getText().trim(); + + // Obtain the manager object: + org.omg.CORBA.Object object = null; + + try + { + object = desk.orb.string_to_object(mior); + } + catch (Exception exc) + { + // Maybe CORBA 3.0.3 is not completely implemented? + if (mior.startsWith("http://") || mior.startsWith("ftp://") + || mior.startsWith("file://")) + object = desk.orb.string_to_object(IorReader.readUrl(mior)); + else + throw exc; + } + + desk.manager = (GameManager) PortableRemoteObject.narrow( + object, GameManager.class); + + // Export the desk.player as a remote object. + PortableRemoteObject.exportObject(desk.player); + } + + desk.player.set_current_state(State.QUEUED); + desk.manager.requestTheGame(desk.player); + } + + // Save the specified IOR for the future use: + File gmf = new File(OrbStarter.WRITE_URL_TO_FILE); + FileWriter f = new FileWriter(gmf); + BufferedWriter b = new BufferedWriter(f); + + b.write(mior); + b.close(); + } + catch (Exception ex) + { + talk(Color.red, "The manager is not reachable by this address."); + talk(Color.red, ex.getMessage()); + desk.player.set_current_state(State.DISCONNECTED); + } + } + + /** + * Display the new message with the given color. Shift the other messages over + * the labels. + */ + public void talk(Color color, String text) + { + lbC1.setText(lbC2.getText()); + lbC1.setForeground(lbC2.getForeground()); + + lbC2.setText(lbC3.getText()); + lbC2.setForeground(lbC3.getForeground()); + + lbC3.setText(text); + lbC3.setForeground(color); + } + + /** + * Exit this program. + */ + void bExit_actionPerformed(ActionEvent e) + { + try + { + if (desk.player.get_current_state() != State.DISCONNECTED + && desk.player.partner != null) + { + desk.player.partner.receive_chat(ChatConstants.REMOTE_PLAYER, + "I close the program!"); + desk.player.partner.disconnect(); + } + } + catch (RemoteException ex) + { + // We will print the exception because this is a demo application that + // may be modified for learning purposes. + ex.printStackTrace(); + } + System.exit(0); + } + + void bReset_actionPerformed(ActionEvent e) + { + if (desk.player.partner != null) + { + try + { + desk.player.partner.receive_chat(ChatConstants.REMOTE_PLAYER, + "Your partner restarted the game."); + + desk.player.start_game(desk.player.partner, false); + desk.player.partner.start_game(desk.player, true); + } + catch (RemoteException ex) + { + // We will print the exception because this is a demo application + // that + // may be modified for learning purposes. + ex.printStackTrace(); + } + } + else + talk(Color.black, "You have not started the game yet."); + } + + void bLeave_actionPerformed(ActionEvent e) + { + desk.player.leave(); + } + + void bChat_actionPerformed(ActionEvent e) + { + try + { + if (desk.player.partner != null) + { + String message = taUrl.getText(); + desk.player.partner.receive_chat(ChatConstants.REMOTE_PLAYER, message); + talk(ChatConstants.colors[ChatConstants.SELF], message); + taUrl.setText(""); + } + else + { + talk(Color.black, "Sorry, not connected to anybody"); + } + } + catch (RemoteException ex) + { + // We will print the exception because this is a demo application that + // may be modified for learning purposes. + ex.printStackTrace(); + } + } + + /** + * Work around our keyboard shortcut handling that is still not working + * properly. + */ + void bPaste_actionPerformed(ActionEvent e) + { + taUrl.paste(); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/Demo.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/Demo.java new file mode 100644 index 000000000..3461f0284 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/Demo.java @@ -0,0 +1,99 @@ +/* Demo.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + + This file is part of GNU Classpath. + + GNU Classpath is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + GNU Classpath is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. + + Linking this library statically or dynamically with other modules is + making a combined work based on this library. Thus, the terms and + conditions of the GNU General Public License cover the whole + combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent + modules, and to copy and distribute the resulting executable under + terms of your choice, provided that you also meet, for each linked + independent module, the terms and conditions of the license of that + module. An independent module is a module which is not derived from + or based on this library. If you modify this library, you may extend + this exception to your version of the library, but you are not + obligated to do so. If you do not wish to do so, delete this + exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.swing.x5; + +import java.awt.Dimension; +import java.awt.Toolkit; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; + +/** + * The main executable class of the game client. + * + * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) + */ +public class Demo +{ + + public static void main(String[] args) + { + ClientFrame frame = new ClientFrame(); + frame.setSize(new Dimension(640, 480)); + frame.setTitle("Make vertical, horizontal or diagonal line of 5 dots. " + + "Click mouse to set the dot."); + frame.validate(); + + // Center the window + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + Dimension frameSize = frame.getSize(); + if (frameSize.height > screenSize.height) + { + frameSize.height = screenSize.height; + } + if (frameSize.width > screenSize.width) + { + frameSize.width = screenSize.width; + } + frame.setLocation((screenSize.width - frameSize.width) / 2, + (screenSize.height - frameSize.height) / 2); + frame.setVisible(true); + + // Set the ior. + try + { + if (OrbStarter.WRITE_URL_TO_FILE != null) + { + File saved_ior = new File(OrbStarter.WRITE_URL_TO_FILE); + if (saved_ior.exists()) + { + FileReader f = new FileReader(saved_ior); + String s = new BufferedReader(f).readLine(); + frame.taUrl.setText(s); + } + } + } + catch (Exception e) + { + // We will print the exception, because this is a demo program - + // expected to be modified by user. + e.printStackTrace(); + } + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/GameManager.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/GameManager.java new file mode 100644 index 000000000..c08f49a7c --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/GameManager.java @@ -0,0 +1,68 @@ +/* GameManager.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + + This file is part of GNU Classpath. + + GNU Classpath is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + GNU Classpath is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. + + Linking this library statically or dynamically with other modules is + making a combined work based on this library. Thus, the terms and + conditions of the GNU General Public License cover the whole + combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent + modules, and to copy and distribute the resulting executable under + terms of your choice, provided that you also meet, for each linked + independent module, the terms and conditions of the license of that + module. An independent module is a module which is not derived from + or based on this library. If you modify this library, you may extend + this exception to your version of the library, but you are not + obligated to do so. If you do not wish to do so, delete this + exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.swing.x5; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +/** + * The game manager interface. + * + * Defines the operations of the game server that connects two players into + * the game. The game server does not participate in the game itself. + * + * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) + */ +public interface GameManager extends Remote +{ + /** + * Register the newPlayer as the person who is willing to play. When another + * player calls this method, the Manager connects them by calling + * {@link PlayerCommunicator#start_game}. The manager provides the partner + * and sets (randomly) the starting side. + */ + void requestTheGame(Player newPlayer) throws RemoteException; + + /** + * Unregister the player that left and is no longer waiting for a playing + * partner to come. + * @throws RemoteException + */ + void unregister(Player player) throws RemoteException; +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/GameManagerImpl.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/GameManagerImpl.java new file mode 100644 index 000000000..cf305318a --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/GameManagerImpl.java @@ -0,0 +1,135 @@ +/* GameManagerImpl.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + + This file is part of GNU Classpath. + + GNU Classpath is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + GNU Classpath is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. + + Linking this library statically or dynamically with other modules is + making a combined work based on this library. Thus, the terms and + conditions of the GNU General Public License cover the whole + combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent + modules, and to copy and distribute the resulting executable under + terms of your choice, provided that you also meet, for each linked + independent module, the terms and conditions of the license of that + module. An independent module is a module which is not derived from + or based on this library. If you modify this library, you may extend + this exception to your version of the library, but you are not + obligated to do so. If you do not wish to do so, delete this + exception statement from your version. */ + +package gnu.classpath.examples.CORBA.swing.x5; + +import java.rmi.RemoteException; + +import org.omg.CORBA.ORB; +import org.omg.CORBA.Object; + +/** + * The manager connects two players into the game. + * + * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) + */ +public class GameManagerImpl + implements GameManager +{ + /** + * The game manager IOR. + */ + static String ior; + + /** + * The game manager ORB. + */ + static ORB orb; + + /** + * True if the manager started ok. + */ + static boolean ok; + + /** + * Another player that is already waiting for the game. + */ + Player queuedPlayer = null; + + public synchronized void requestTheGame(Player newPlayer) + throws RemoteException + { + System.out.println("Game requested"); + + if (queuedPlayer == null) + { + // No other player so far. + newPlayer.receive_chat(ChatConstants.GAME_SERVER, + "Request registered, waiting for the other player to come..."); + System.out.println("Player queued."); + queuedPlayer = newPlayer; + } + else if (queuedPlayer.equals(newPlayer)) + { + // The same player applies again. + newPlayer.receive_chat(ChatConstants.GAME_SERVER, + "No other player so far... Please wait."); + } + else + { + // As the queued player waited for the game, we allow him/her + // to start the game. This is a reward for waiting. + newPlayer.receive_chat(ChatConstants.GAME_SERVER, + "The other player is waiting. The game started, your " + + "partner begins..."); + queuedPlayer.receive_chat(ChatConstants.GAME_SERVER, + "The other player arrived. Lets play, you begin the game now..."); + + newPlayer.start_game(queuedPlayer, false); + queuedPlayer.start_game(newPlayer, true); + + queuedPlayer = null; + System.out.println("Players connected."); + } + } + + /** + * Unregister the player who left and is no longer waiting for another side. + */ + public void unregister(Player player) + throws RemoteException + { + if (queuedPlayer != null) + { + // We need to verify the identity of the player being unregistered. + // The stubs, being derived from the org.omg.CORBA.Object, have the + // method for this. This method compares the player host address, + // used port and the object key. + if (player instanceof Object && queuedPlayer instanceof Object) + { + Object a = (Object) player; + Object b = (Object) queuedPlayer; + + if (a._is_equivalent(b)) + queuedPlayer = null; + } + else + queuedPlayer = null; + } + System.out.println("Unregistering player"); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/IorReader.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/IorReader.java new file mode 100644 index 000000000..4afd47549 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/IorReader.java @@ -0,0 +1,124 @@ +/* IorReader.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + + This file is part of GNU Classpath. + + GNU Classpath is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + GNU Classpath is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. + + Linking this library statically or dynamically with other modules is + making a combined work based on this library. Thus, the terms and + conditions of the GNU General Public License cover the whole + combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent + modules, and to copy and distribute the resulting executable under + terms of your choice, provided that you also meet, for each linked + independent module, the terms and conditions of the license of that + module. An independent module is a module which is not derived from + or based on this library. If you modify this library, you may extend + this exception to your version of the library, but you are not + obligated to do so. If you do not wish to do so, delete this + exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.swing.x5; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.MalformedURLException; +import java.net.URL; + +import org.omg.CORBA.BAD_PARAM; +import org.omg.CORBA.DATA_CONVERSION; + +/** + * Reads the remote URL. Following formal/04-03-12, CORBA should be able to do + * this without the help of this class. However some popular class libraries + * are written using the older CORBA specifications and may not handle + * functionality, require by this game. This class substitutes the functionality, + * ensuring that these implementations will also start and we will be able + * to test the interoperability. + * + * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) + */ +public class IorReader +{ + /** + * Read IOR from the remote URL. + */ + public static String readUrl(String url) + { + URL u; + try + { + u = new URL(url); + } + catch (MalformedURLException mex) + { + throw new BAD_PARAM("Malformed URL: '" + url + "'"); + } + + try + { + InputStreamReader r = new InputStreamReader(u.openStream()); + + StringBuilder b = new StringBuilder(); + int c; + + while ((c = r.read()) > 0) + b.append((char) c); + + return b.toString().trim(); + } + catch (Exception exc) + { + DATA_CONVERSION d = new DATA_CONVERSION("Reading " + url + " failed."); + throw d; + } + } + + /** + * Read IOR from the file in the local file system. + */ + public static String readFile(String file) + { + File f = new File(file); + if (!f.exists()) + { + DATA_CONVERSION err = new DATA_CONVERSION(f.getAbsolutePath() + + " does not exist."); + throw err; + } + try + { + char[] c = new char[(int) f.length()]; + FileReader fr = new FileReader(f); + fr.read(c); + fr.close(); + return new String(c).trim(); + } + catch (IOException ex) + { + DATA_CONVERSION d = new DATA_CONVERSION(); + d.initCause(ex); + throw (d); + } + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/OrbStarter.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/OrbStarter.java new file mode 100644 index 000000000..54632658d --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/OrbStarter.java @@ -0,0 +1,236 @@ +/* OrbStarter.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + + This file is part of GNU Classpath. + + GNU Classpath is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + GNU Classpath is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. + + Linking this library statically or dynamically with other modules is + making a combined work based on this library. Thus, the terms and + conditions of the GNU General Public License cover the whole + combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent + modules, and to copy and distribute the resulting executable under + terms of your choice, provided that you also meet, for each linked + independent module, the terms and conditions of the license of that + module. An independent module is a module which is not derived from + or based on this library. If you modify this library, you may extend + this exception to your version of the library, but you are not + obligated to do so. If you do not wish to do so, delete this + exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.swing.x5; + +import java.rmi.RemoteException; +import java.util.Properties; + +import javax.rmi.PortableRemoteObject; +import javax.rmi.CORBA.Tie; + +import org.omg.CORBA.ORB; +import org.omg.PortableServer.POA; +import org.omg.PortableServer.POAHelper; +import org.omg.PortableServer.Servant; + +/** + * Starts the ORBs, involved into this application. + * + * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) + */ +public class OrbStarter +{ + /** + * The game manager name server port. This server allows to access the game + * manager by host (IP) and port rather than by the rather long IOR string. + */ + static int MANAGER_NAMER_PORT = 1500; + + /** + * The used port range (understood and used by GNU Classpath only). + */ + static String USED_PORT_RANGE = "1501-1503"; + + /** + * Specify the file where under start the game manager writes its IOR. + * You may specify the path if the game manager and player clients have + * access to some share file system or if you prefer to write IOR to + * floppy and then read from the floppy on the client side. Both clients + * and server will use this constant. Set to null not to write the IOR. + */ + static String WRITE_URL_TO_FILE = "game_manager_ior.txt"; + + /** + * Start the manager ORB. + * @return the manager URL if it starts. + */ + public static String startManager(final String[] args) + { + GameManagerImpl.ior = null; + GameManagerImpl.ok = false; + + final Properties p = new Properties(); + p.put("gnu.CORBA.ListenerPort", USED_PORT_RANGE); + + try + { + new Thread() + { + public void run() + { + try + { + GameManagerImpl.orb = ORB.init(args, p); + + // Obtain the root poa: + POA rootPOA = POAHelper.narrow(GameManagerImpl.orb.resolve_initial_references("RootPOA")); + + GameManagerImpl impl = new GameManagerImpl(); + + PortableRemoteObject.exportObject(impl); + + // Construct the tie that is also the servant. + Tie tie = new _GameManagerImpl_Tie(); + + // Set the invocation target for this tie. + tie.setTarget(impl); + + // Obtain the reference to the corresponding CORBA object: + org.omg.CORBA.Object object = rootPOA.servant_to_reference((Servant) tie); + + GameManagerImpl.ok = true; + + // Activate the root POA. + rootPOA.the_POAManager().activate(); + + // Get the IOR URL that must be passed to clients. + GameManagerImpl.ior = GameManagerImpl.orb.object_to_string(object); + + GameManagerImpl.orb.run(); + } + catch (Exception exc) + { + exc.printStackTrace(); + GameManagerImpl.ior = "Unable to start the ORB: " + exc; + } + } + }.start(); + + // Wait the thread to enter orb.run. + long t = System.currentTimeMillis(); + while (GameManagerImpl.ior == null + && System.currentTimeMillis() - t < 20000) + { + Thread.sleep(100); + } + + return GameManagerImpl.ior; + } + catch (Exception e) + { + e.printStackTrace(); + return "Exception: " + e; + } + } + + /** + * Start the client ORB. + */ + public static String startPlayer(final Player player, final PlayingDesk desk) + { + desk.ior = null; + desk.ok = false; + + final Properties p = new Properties(); + p.put("gnu.CORBA.ListenerPort", USED_PORT_RANGE); + + try + { + new Thread() + { + public void run() + { + try + { + desk.orb = ORB.init(new String[0], p); + + POA rootPOA = POAHelper.narrow(desk.orb.resolve_initial_references("RootPOA")); + rootPOA.the_POAManager().activate(); + + // Construct the tie. + Tie tie = new _PlayerImpl_Tie(); + + // Set the implementing class (invocation target). + tie.setTarget(new PlayerImpl()); + + // Connect the tie as POA servant. + org.omg.CORBA.Object object = rootPOA.servant_to_reference((Servant) tie); + + // Get the stringified reference. + desk.ior = desk.orb.object_to_string(object); + + // Mark that the object was created OK. + desk.ok = true; + desk.orb.run(); + } + catch (Exception exc) + { + exc.printStackTrace(); + desk.ior = "Unable to start the ORB: " + exc; + } + } + }.start(); + + long t = System.currentTimeMillis(); + while (desk.ior == null && System.currentTimeMillis() - t < 20000) + { + Thread.sleep(100); + } + } + catch (Exception e) + { + e.printStackTrace(); + return "Exception: " + e; + } + + // Add shutdown hook to unregister from the manager. + Runtime.getRuntime().addShutdownHook(new Thread() + { + public void run() + { + if (desk.manager != null && player != null) + { + try + { + desk.manager.unregister(player); + } + catch (RemoteException ex) + { + // We will print the exception because this is a demo + // application that + // may be modified for learning purposes. + ex.printStackTrace(); + } + desk.manager = null; + } + } + }); + return desk.ior; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/Player.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/Player.java new file mode 100644 index 000000000..ced7d5d82 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/Player.java @@ -0,0 +1,96 @@ +/* Player.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + + This file is part of GNU Classpath. + + GNU Classpath is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + GNU Classpath is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. + + Linking this library statically or dynamically with other modules is + making a combined work based on this library. Thus, the terms and + conditions of the GNU General Public License cover the whole + combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent + modules, and to copy and distribute the resulting executable under + terms of your choice, provided that you also meet, for each linked + independent module, the terms and conditions of the license of that + module. An independent module is a module which is not derived from + or based on this library. If you modify this library, you may extend + this exception to your version of the library, but you are not + obligated to do so. If you do not wish to do so, delete this + exception statement from your version. */ + +package gnu.classpath.examples.CORBA.swing.x5; + +import java.awt.Point; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +/** + * Defines remote methods that are invoked by another player or by the + * challenge server. + * + * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) + */ +public interface Player extends Remote +{ + /** + * Receive the invitation to play from the patner or the game manager. + * + * @param address the address (host and port) of the remote partner. + * @param youStart if true, the game manager instructs to start + * the game first (another side is instructed to start the game second). + * + * @return true on success. + */ + boolean start_game(Player otherPlayer, boolean youStart) + throws RemoteException; + + /** + * Get the state of the local player (one of the constants, defined + * in this interface). + */ + int get_current_state() throws RemoteException; + + /** + * Receive the chat message from the friend or challenge server (remote). + * Possible at any state, always remote. + * + * @param color the color code, used to highlight the message. + * @param text the message text. + */ + void receive_chat(byte color, String test) throws RemoteException; + + /** + * Indicated that the remote side leaves the game (capitulating). + */ + void disconnect() throws RemoteException; + + /** + * Receive friends move (possible at I_WAIT_FOR_YOUR_MOVE). + * + * @param x grid position. + * @param y grid position. + * + * @param sessionId the session id, must match (otherwise the call is ignored). + * @param victory if not a null, the friend thinks that it has won, the parameter + * containing the ends of the builded line. + */ + void receive_move(int x, int y, Point[] victory) throws RemoteException; +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/PlayerImpl.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/PlayerImpl.java new file mode 100644 index 000000000..30b32c4b6 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/PlayerImpl.java @@ -0,0 +1,275 @@ +/* PlayerImpl.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + + This file is part of GNU Classpath. + + GNU Classpath is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + GNU Classpath is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. + + Linking this library statically or dynamically with other modules is + making a combined work based on this library. Thus, the terms and + conditions of the GNU General Public License cover the whole + combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent + modules, and to copy and distribute the resulting executable under + terms of your choice, provided that you also meet, for each linked + independent module, the terms and conditions of the license of that + module. An independent module is a module which is not derived from + or based on this library. If you modify this library, you may extend + this exception to your version of the library, but you are not + obligated to do so. If you do not wish to do so, delete this + exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.swing.x5; + +import java.awt.Color; +import java.awt.Point; + +import java.rmi.RemoteException; + +/** + * The implementation of the PlayerCommunicator, providing the local + * functionality. Apart remote methods, the class also defines some local + * methods, needed for the co-ordinated work with the game user interface. + * + * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) + */ +public class PlayerImpl + implements Player, State +{ + /** + * The playing table. + */ + PlayingDesk desk; + + /** + * The state of this player (one of the constants, defined in the player + * interface. + */ + private int state = DISCONNECTED; + + /** + * The other player. + */ + Player partner; + + /** + * Called when the local player refuses to continue the game. + */ + public void leave() + { + try + { + if (state == I_THINK || state == I_WAIT_FOR_YOUR_MOVE) + { + partner.receive_chat(ChatConstants.REMOTE_PLAYER, + "Your partner has left the game."); + partner.disconnect(); + } + else if (state == State.QUEUED) + { + if (desk.manager != null) + desk.manager.unregister(desk.player); + receive_chat(ChatConstants.SYSTEM, + "Do not be so pessimistic, try to play first!"); + } + set_current_state(State.DISCONNECTED); + + desk.frame.bChat.setEnabled(false); + desk.frame.bLeave.setEnabled(false); + desk.frame.bConnect.setEnabled(true); + desk.frame.taUrl.setText(desk.frame.mior); + } + catch (RemoteException ex) + { + // We will print the exception because this is a demo application that + // may be modified for learning purposes. + ex.printStackTrace(); + } + } + + /** + * Called when we make the move. The PlayingTable is responsible for checking + * the correctness of the move and detecting the victory. + * + * @param x x position of the new dot. + * @param y y position of the new dot. + * + * @param victory array of two memebers, representing the endpoints of the + * drawn line (victory detected) or null if no such yet exists. + */ + public void we_move(int x, int y, Point[] victory) + { + try + { + set_current_state(I_WAIT_FOR_YOUR_MOVE); + partner.receive_move(x, y, victory); + } + catch (RemoteException ex) + { + // We will print the exception because this is a demo application that + // may be modified for learning purposes. + ex.printStackTrace(); + + state = ERROR; + } + } + + /** + * Set the current state. + */ + public void set_current_state(int new_state) + { + state = new_state; + + if (state == DISCONNECTED) + { + setStatus("Disconnected"); + } + else if (state == I_THINK) + { + setStatus("Our move"); + } + else if (state == I_WAIT_FOR_YOUR_MOVE) + { + setStatus("Partner's move"); + } + else if (state == ERROR) + { + setStatus("Error."); + } + else if (state == I_HAVE_LOST) + { + setStatus("We lost"); + } + else if (state == I_HAVE_WON) + { + setStatus("Victory"); + } + else if (state == QUEUED) + { + setStatus("Queued"); + } + else + { + setStatus("State " + state); + } + + boolean connected = state != State.DISCONNECTED; + + desk.frame.bConnect.setEnabled(!connected && state != State.QUEUED); + desk.frame.bReset.setEnabled(connected); + desk.frame.bLeave.setEnabled(connected); + desk.frame.bChat.setEnabled(connected); + } + + /** + * Show the state in the status line. + */ + public void setStatus(String status) + { + desk.frame.lbState.setText(status); + } + + /** + * Receive the invitation to play from the patner or the game manager. + * + * @param address the address (host and port) of the remote partner. + * @param youStart if true, the game manager instructs to start the game first + * (another side is instructed to start the game second). + * + * Game server may also chat a little bit with both players, saying that the + * game has started. + * + * @return true on success. + */ + public boolean start_game(Player otherPlayer, boolean youStart) + throws RemoteException + { + partner = otherPlayer; + desk.reset(); + + if (youStart) + { + set_current_state(I_THINK); + } + else + { + set_current_state(I_WAIT_FOR_YOUR_MOVE); + } + + desk.frame.taUrl.setText(""); + + return true; + } + + /** + * Get the state of the local player (one of the constants, defined in this + * interface). + */ + public int get_current_state() + throws RemoteException + { + return state; + } + + /** + * Receive the chat message from the friend or challenge server (remote). + * Possible at any state, always remote. + * + * @param color the color code, used to highlight the message. + * @param text the message text. + */ + public void receive_chat(byte color, String text) + throws RemoteException + { + if (color >= ChatConstants.colors.length) + color = ChatConstants.REMOTE_PLAYER; + + desk.frame.talk(ChatConstants.colors[color], text); + } + + /** + * Indicated that the remote side leaves the game (capitulating). + */ + public void disconnect() + throws RemoteException + { + desk.frame.talk(Color.red, "The partner leaves the game."); + partner = null; + set_current_state(DISCONNECTED); + + desk.frame.taUrl.setText(desk.frame.mior); + } + + /** + * Receive friends move (possible at I_WAIT_FOR_YOUR_MOVE). + * + * @param x grid position. + * @param y grid position. + * @param victory if not a null, the friend thinks that it has won, the + * parameter containing the ends of the builded line. + */ + public void receive_move(int x, int y, Point[] victory) + throws RemoteException + { + // The state changes are handled by the PlayingTable + desk.friendsMove(x, y, victory); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/PlayingDesk.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/PlayingDesk.java new file mode 100644 index 000000000..681d42e6b --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/PlayingDesk.java @@ -0,0 +1,512 @@ +/* PlayingDesk.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + + This file is part of GNU Classpath. + + GNU Classpath is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + GNU Classpath is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. + + Linking this library statically or dynamically with other modules is + making a combined work based on this library. Thus, the terms and + conditions of the GNU General Public License cover the whole + combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent + modules, and to copy and distribute the resulting executable under + terms of your choice, provided that you also meet, for each linked + independent module, the terms and conditions of the license of that + module. An independent module is a module which is not derived from + or based on this library. If you modify this library, you may extend + this exception to your version of the library, but you are not + obligated to do so. If you do not wish to do so, delete this + exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.swing.x5; + +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Point; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.rmi.RemoteException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; + +import javax.swing.JComponent; + +import org.omg.CORBA.ORB; + +/** + * Manages actions, related to the game rules and also does all painting. + * + * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org) + */ +public class PlayingDesk + extends JComponent + implements MouseListener, State +{ + /** + * Use serialVersionUID for interoperability. + */ + private static final long serialVersionUID = 1; + + /** + * Indicates that the field point state is the red oval. + */ + public static final int RED = 0; + + /** + * Indicates that the field point state is the black cross. + */ + public static final int BLACK = 1; + + /** + * Indicates that the field point state is the hint, suggested by the fan. + */ + public static final int HINT = 2; + + /** + * The access to the main frame methods. + */ + ClientFrame frame; + + /** + * The access to the player communicator. + */ + PlayerImpl player; + + /** + * The game manager. + */ + GameManager manager; + + /** + * The player ORB. + */ + ORB orb; + + /** + * The player IOR. + */ + String ior; + + /** + * True if the player ORB started ok. + */ + boolean ok; + + /** + * The grid spacing. + */ + static int W = 16; + + /** + * The radius of the dots being painted. + */ + static int R = W / 3; + + /** + * The collection of the red dots. + */ + ArrayList reds = new ArrayList(); + + /** + * The collection of the black dots. + */ + ArrayList blacks = new ArrayList(); + + /** + * The array of hints. + */ + ArrayList hints = new ArrayList(); + + /** + * When the game is completed, obtains the value of the two end points of the + * created line. + */ + Point[] endOfGame; + + public PlayingDesk() + { + try + { + player = new PlayerImpl(); + player.desk = this; + + OrbStarter.startPlayer(player, this); + + jbInit(); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + /** + * Paint this component. + */ + public void paintComponent(Graphics g) + { + int w = getWidth(); + int h = getHeight(); + + g.setColor(Color.white); + g.fillRect(0, 0, w, h); + + drawGrid(w, h, g); + drawFigures(g); + } + + /** + * Check maybe a game is finished after setting the point N + */ + public Point[] checkFinished(Collection x, Point N) + { + Iterator iter = x.iterator(); + Point p; + + // The victory, if happens, must occur inside these boundaries: + int ax = N.x - 5; + int bx = N.x + 5; + + int ay = N.y - 5; + int by = N.y + 5; + + while (iter.hasNext()) + { + p = (Point) iter.next(); + + if (p.x > ax && p.x < bx && p.y > ay && p.y < by) + { + // Check the vertical line down + if (pointPresent(p.x, p.y + 1, x)) + if (pointPresent(p.x, p.y + 2, x)) + if (pointPresent(p.x, p.y + 3, x)) + if (pointPresent(p.x, p.y + 4, x)) + return new Point[] { p, new Point(p.x, p.y + 4) }; + + // Check the horizontal line left + if (pointPresent(p.x + 1, p.y, x)) + if (pointPresent(p.x + 2, p.y, x)) + if (pointPresent(p.x + 3, p.y, x)) + if (pointPresent(p.x + 4, p.y, x)) + return new Point[] { p, new Point(p.x + 4, p.y) }; + + // Check the diagonal line right down. + if (pointPresent(p.x + 1, p.y + 1, x)) + if (pointPresent(p.x + 2, p.y + 2, x)) + if (pointPresent(p.x + 3, p.y + 3, x)) + if (pointPresent(p.x + 4, p.y + 4, x)) + return new Point[] { p, new Point(p.x + 4, p.y + 4) }; + + // Check the diagonal line left down. + if (pointPresent(p.x - 1, p.y + 1, x)) + if (pointPresent(p.x - 2, p.y + 2, x)) + if (pointPresent(p.x - 3, p.y + 3, x)) + if (pointPresent(p.x - 4, p.y + 4, x)) + return new Point[] { p, new Point(p.x - 4, p.y + 4) }; + } + } + return null; + } + + /** + * Called when the "end of the game" situation is detected. + */ + public void drawFinishLine(int xa, int ya, int xb, int yb, Graphics g) + { + g.setColor(Color.blue); + + int hW = W / 2; + g.drawLine(xa * W + hW, ya * W + hW, xb * W + hW, yb * W + hW); + } + + /** + * Check for the presence of the given point in the collection. + */ + public final boolean pointPresent(int x, int y, Collection in) + { + Iterator iter = in.iterator(); + Point p; + while (iter.hasNext()) + { + p = (Point) iter.next(); + if (p.x == x && p.y == y) + return true; + } + return false; + } + + public void drawGrid(int w, int h, Graphics g) + { + g.setColor(Color.lightGray); + + // Draw vertical lines: + for (int x = 0; x < w; x += W) + { + g.drawLine(x, 0, x, h); + } + + // Draw horizontal lines: + for (int y = 0; y < h; y += W) + { + g.drawLine(0, y, w, y); + } + + g.setColor(Color.gray); + g.drawRect(0,0, frame.DESK_SIZE.width, frame.DESK_SIZE.height); + g.drawRect(0,0, frame.DESK_SIZE.width+3, frame.DESK_SIZE.height+3); + } + + public void drawFigures(Graphics g) + { + g.setColor(Color.red); + drawDots(reds, g, RED); + + g.setColor(Color.black); + drawDots(blacks, g, BLACK); + + g.setColor(Color.lightGray); + drawDots(hints, g, HINT); + + if (endOfGame != null) + drawFinishLine(endOfGame[0].x, endOfGame[0].y, endOfGame[1].x, + endOfGame[1].y, g); + } + + public Point makePoint(int x, int y) + { + return new Point(x / W, y / W); + } + + /** + * Draw a collection of dots (the collor must be set before calling the + * method). + */ + public void drawDots(Collection dots, Graphics g, int mode) + { + Iterator iter = dots.iterator(); + int x; + int y; + + int hW = W / 2; + int RR = R * 2; + int hR = R / 2; + Point p; + while (iter.hasNext()) + { + p = (Point) iter.next(); + x = p.x * W + hW; + y = p.y * W + hW; + + if (mode == RED) + g.drawOval(x - R, y - R, RR, RR); + else if (mode == BLACK) + { + g.drawLine(x - R, y - R, x + R, y + R); + g.drawLine(x - R, y + R, x + R, y - R); + } + else + { + // Hint. + g.drawOval(x - hR, y - hR, R, R); + } + } + } + + private void jbInit() + throws Exception + { + addMouseListener(this); + } + + public void mouseClicked(MouseEvent e) + { + try + { + int state = player.get_current_state(); + + // Check if the state is correct. + if (state == I_WAIT_FOR_YOUR_MOVE) + { + frame.talk(Color.black, + "It is now time for our partner's move, not ours. Please wait."); + } + else if (state == DISCONNECTED) + { + frame.talk(Color.black, + "We are not connected to the playing partner yet."); + } + else if (state == I_HAVE_LOST) + { + frame.talk(Color.black, + "We have already lost this battle, but why not to try again?"); + } + else if (state == I_HAVE_WON) + { + frame.talk(Color.black, + "The victory is ours, nothing more to do here."); + } + else if (player.partner == null) + frame.talk(Color.black, "No other player so far."); + else + { + int x = e.getX(); + int y = e.getY(); + + if (x>frame.DESK_SIZE.width || + y>frame.DESK_SIZE.height) + { + frame.talk(Color.black,"Outside the game area."); + return; + } + + Point p = makePoint(x, y); + + // Ignore clicks on the occupied cells. + if (pointPresent(p.x, p.y, reds) + || (pointPresent(p.x, p.y, blacks))) + { + frame.talk(Color.black, + "This is against the rules, select the unoccupied cell."); + return; + } + + reds.add(p); + + endOfGame = checkFinished(reds, p); + repaint(); + + if (endOfGame != null) + { + frame.talk(Color.red, "Our move " + p.x + "-" + p.y + + " and we win!"); + player.set_current_state(I_HAVE_WON); + } + else + { + frame.talk(Color.black, "Our move " + p.x + "-" + p.y + + ". Waiting for the other side move..."); + player.set_current_state(I_WAIT_FOR_YOUR_MOVE); + } + + player.partner.receive_move(p.x, p.y, endOfGame); + } + } + catch (RemoteException ex) + { + // We will print the exception because this is a demo application + // that may be modified for learning purposes. + ex.printStackTrace(); + } + } + + /** + * Handle the move of the other playing side. + */ + public void friendsMove(int x, int y, Point[] victory) + { + try + { + int state = player.get_current_state(); + if (state != I_WAIT_FOR_YOUR_MOVE || pointPresent(x, y, blacks)) + { + stateFailed("Move " + x + "-" + y); + } + else + { + blacks.add(new Point(x, y)); + + if (victory != null) + { + frame.talk(Color.red, + " We have lost this time, unfortunately.."); + player.set_current_state(I_HAVE_LOST); + endOfGame = victory; + } + else + { + frame.talk(Color.black, "Partner goes " + x + "-" + y + + ". Your move?"); + player.set_current_state(I_THINK); + } + repaint(); + } + } + catch (RemoteException rex) + { + rex.printStackTrace(); + } + } + + /** + * Prepare for the new game. + */ + public void reset() + { + blacks.clear(); + reds.clear(); + hints.clear(); + endOfGame = null; + repaint(); + } + + public void mouseEntered(MouseEvent m) + { + // Nothing to do. + } + + public void mousePressed(MouseEvent m) + { + // Nothing to do. + } + + public void mouseReleased(MouseEvent m) + { + // Nothing to do. + } + + public void mouseExited(MouseEvent m) + { + // Nothing to do. + } + + /** + * The systems detected the error conditions. The game cannot continue (the + * chat is still possible). + */ + public void stateFailed(String reason) + { + try + { + player.receive_chat(ChatConstants.REMOTE_PLAYER, + "Wrong move, game cannot continue (our state was " + + player.get_current_state() + ")"); + frame.talk(Color.red, "The remote side violates communicating rules."); + player.set_current_state(State.ERROR); + } + catch (RemoteException ex) + { + // We will print the exception because this is a demo application + // that may be modified for learning purposes. + ex.printStackTrace(); + } + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/State.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/State.java new file mode 100644 index 000000000..a759225bb --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/State.java @@ -0,0 +1,82 @@ +/* State.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + + This file is part of GNU Classpath. + + GNU Classpath is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + GNU Classpath is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. + + Linking this library statically or dynamically with other modules is + making a combined work based on this library. Thus, the terms and + conditions of the GNU General Public License cover the whole + combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent + modules, and to copy and distribute the resulting executable under + terms of your choice, provided that you also meet, for each linked + independent module, the terms and conditions of the license of that + module. An independent module is a module which is not derived from + or based on this library. If you modify this library, you may extend + this exception to your version of the library, but you are not + obligated to do so. If you do not wish to do so, delete this + exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.swing.x5; + +/** + * Defines the states in that the player can be. + * + * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) + */ +public interface State { + /** + * The initial ("disconnected") state. + */ + int DISCONNECTED = 0; + + /** + * The state, indicating that the player has been queued for the game and + * waiting for the partner to come. + */ + int QUEUED = 1; + + /** + * The "my move" state. + */ + int I_THINK = 2; + + /** + * The "friend's move" state. + */ + int I_WAIT_FOR_YOUR_MOVE = 3; + + /** + * States that we have won. + */ + int I_HAVE_WON = 4; + + /** + * States that we have lost. + */ + int I_HAVE_LOST = 5; + + /** + * The "inconsistent" state when it is not possible to continue the game. + */ + int ERROR = -1; +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/X5Server.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/X5Server.java new file mode 100644 index 000000000..516c701e1 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/X5Server.java @@ -0,0 +1,175 @@ +/* GameManagerAddressServer.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + + This file is part of GNU Classpath. + + GNU Classpath is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + GNU Classpath is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. + + Linking this library statically or dynamically with other modules is + making a combined work based on this library. Thus, the terms and + conditions of the GNU General Public License cover the whole + combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent + modules, and to copy and distribute the resulting executable under + terms of your choice, provided that you also meet, for each linked + independent module, the terms and conditions of the license of that + module. An independent module is a module which is not derived from + or based on this library. If you modify this library, you may extend + this exception to your version of the library, but you are not + obligated to do so. If you do not wish to do so, delete this + exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.swing.x5; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; + +/** + * The main executable class of the game manager server. + * + * The manager address server returns the IOR address string of the game + * manager. Hence the user does not need to enter the rather long IOR address + * string and only needs to specify the host and port of the machine where the + * game manager is running. + * + * The manager address server starts the main game manager as well. + * + * This server acts as a HTTP server that always returns the same response. This + * primitive functionality is sufficient for its task. + * + * The more complex CORBA applications should use the name service instead. We + * do not use the name service as this would require to start additional + * external application, specific for the different java platforms. + * + * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) + */ +public class X5Server +{ + /** + * Start the game manager. + */ + public static void main(String[] args) + { + // Start the game manager, write the IOR to the agreed location. + OrbStarter.startManager(args); + + if (!GameManagerImpl.ok) + { + System.out.println("Unable to start the game manager:"); + System.exit(1); + } + + // Print the IOR. + System.out.println(GameManagerImpl.ior); + + String manager_address = null; + + // Start the game manager server. + ServerSocket nameServer = null; + try + { + nameServer = new ServerSocket(OrbStarter.MANAGER_NAMER_PORT); + + System.out.println("The game manager is listening at:"); + manager_address = "http://" + + InetAddress.getLocalHost().getHostAddress() + ":" + + nameServer.getLocalPort(); + + System.out.println(manager_address); + + System.out.println("Enter this address to the " + + "input field of the game client."); + + System.out.println("Use ^C to stop the manager."); + } + catch (Exception ex) + { + System.out.println("The port " + OrbStarter.MANAGER_NAMER_PORT + + " is not available. The game manager namer will not start."); + System.exit(1); + } + + // Write the IOR to the local file system. + if (OrbStarter.WRITE_URL_TO_FILE != null) + { + try + { + File gmf = new File(OrbStarter.WRITE_URL_TO_FILE); + FileWriter f = new FileWriter(gmf); + BufferedWriter b = new BufferedWriter(f); + + b.write(manager_address); + b.close(); + } + catch (IOException e) + { + System.out.println("Local filesystem not accessible." + + "Read IOR from console."); + } + } + + // Do forever. + while (true) + { + try + { + Socket socket = nameServer.accept(); + + System.out.println("Connected."); + + // Set the two minutes timeout. + socket.setSoTimeout(1000 * 120); + + OutputStream out = socket.getOutputStream(); + + int length = GameManagerImpl.ior.length(); + + StringBuilder b = new StringBuilder(); + b.append("HTTP/1.0 200 OK\r\n"); + b.append("Content-Length: " + length + "\r\n"); + b.append("Connection: close\r\n"); + b.append("Content-Type: text/plain; charset=UTF-8\r\n"); + b.append("\r\n"); + + b.append(GameManagerImpl.ior); + + out.write(b.toString().getBytes("UTF-8")); + + socket.shutdownOutput(); + + if (!socket.isClosed()) + socket.close(); + + System.out.println("Completed."); + } + catch (Exception exc) + { + exc.printStackTrace(); + System.out.println("Network problem."); + } + } + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/_GameManagerImpl_Tie.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/_GameManagerImpl_Tie.java new file mode 100644 index 000000000..54ef1e93b --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/_GameManagerImpl_Tie.java @@ -0,0 +1,209 @@ +/* _GameManagerImpl_Tie.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + + This file is part of GNU Classpath. + + GNU Classpath is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + GNU Classpath is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. + + Linking this library statically or dynamically with other modules is + making a combined work based on this library. Thus, the terms and + conditions of the GNU General Public License cover the whole + combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent + modules, and to copy and distribute the resulting executable under + terms of your choice, provided that you also meet, for each linked + independent module, the terms and conditions of the license of that + module. An independent module is a module which is not derived from + or based on this library. If you modify this library, you may extend + this exception to your version of the library, but you are not + obligated to do so. If you do not wish to do so, delete this + exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.swing.x5; + +import java.rmi.Remote; + +import javax.rmi.PortableRemoteObject; +import javax.rmi.CORBA.Tie; + +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.UnknownException; +import org.omg.PortableServer.Servant; + +/** + * Normally generated with rmic compiler, this class represents the GameManager + * Tie on the client side. The Game Manager methods contain the code for remote + * invocation. + * + * This class is normally generated with rmic or grmic from the + * {@link GameManagerImpl}. See tools/gnu/classpath/tools/giop/README. + * + * In this example the class was manually edited and commented for better + * understanding of functionality. + * + * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) + */ +public class _GameManagerImpl_Tie + extends Servant + implements Tie +{ + /** + * The target, where remote invocations are forwarded. + */ + private GameManagerImpl target = null; + + /** + * The GameManager repository Id. + */ + private static final String[] _type_ids = + { "RMI:gnu.classpath.examples.CORBA.swing.x5.GameManager:0000000000000000" }; + + /** + * Set the target where the remote invocations are forwarded. + */ + public void setTarget(Remote a_target) + { + this.target = (GameManagerImpl) a_target; + } + + /** + * Get the target where the remote invocations are forwarded. + */ + public Remote getTarget() + { + return target; + } + + /** + * Get the CORBA object for that this Tie is currently serving the request. + * The same tie may serve multiple requests for the different objects in + * parallel threads. + */ + public org.omg.CORBA.Object thisObject() + { + return _this_object(); + } + + /** + * Deactivate this object. + */ + public void deactivate() + { + try + { + _poa().deactivate_object(_poa().servant_to_id(this)); + } + catch (org.omg.PortableServer.POAPackage.WrongPolicy exception) + { + } + catch (org.omg.PortableServer.POAPackage.ObjectNotActive exception) + { + } + catch (org.omg.PortableServer.POAPackage.ServantNotActive exception) + { + } + } + + /** + * Get the ORB for this tie. + */ + public ORB orb() + { + return _orb(); + } + + /** + * Set the ORB for this tie. + */ + public void orb(ORB orb) + { + try + { + ((org.omg.CORBA_2_3.ORB) orb).set_delegate(this); + } + catch (ClassCastException e) + { + throw new org.omg.CORBA.BAD_PARAM( + "POA Servant requires an instance of org.omg.CORBA_2_3.ORB"); + } + } + + /** + * Return all interfaces, supported by this method. + */ + public String[] _all_interfaces(org.omg.PortableServer.POA poa, + byte[] objectId) + { + return _type_ids; + } + + /** + * This method is invoked by CORBA system to handle the remote invocation. + * + * @param method the name of the method being invoked. + * @param _in the stream to read the method parameters. + * @param reply the responsed handler that can create the output stream to + * write the parameters being returned. + */ + public OutputStream _invoke(String method, InputStream _in, + ResponseHandler reply) + throws SystemException + { + try + { + org.omg.CORBA_2_3.portable.InputStream in = + (org.omg.CORBA_2_3.portable.InputStream) _in; + if (method.equals("requestTheGame")) + { + Player p = (Player) PortableRemoteObject.narrow( + in.read_Object(), Player.class); + target.requestTheGame(p); + + OutputStream out = reply.createReply(); + return out; + } + else if (method.equals("unregister")) + { + Player p = (Player) PortableRemoteObject.narrow( + in.read_Object(), Player.class); + target.unregister(p); + + OutputStream out = reply.createReply(); + return out; + } + else + throw new BAD_OPERATION(); + } + catch (SystemException ex) + { + throw ex; + } + catch (Throwable ex) + { + ex.printStackTrace(); + throw new UnknownException(ex); + } + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/_GameManager_Stub.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/_GameManager_Stub.java new file mode 100644 index 000000000..52fd103d6 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/_GameManager_Stub.java @@ -0,0 +1,207 @@ +/* _GameManager_Stub.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + + This file is part of GNU Classpath. + + GNU Classpath is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + GNU Classpath is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. + + Linking this library statically or dynamically with other modules is + making a combined work based on this library. Thus, the terms and + conditions of the GNU General Public License cover the whole + combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent + modules, and to copy and distribute the resulting executable under + terms of your choice, provided that you also meet, for each linked + independent module, the terms and conditions of the license of that + module. An independent module is a module which is not derived from + or based on this library. If you modify this library, you may extend + this exception to your version of the library, but you are not + obligated to do so. If you do not wish to do so, delete this + exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.swing.x5; + +import java.rmi.RemoteException; +import java.rmi.UnexpectedException; + +import javax.rmi.CORBA.Stub; +import javax.rmi.CORBA.Util; + +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.RemarshalException; +import org.omg.CORBA.portable.ServantObject; + +/** + * Normally generated with rmic compiler, this class represents the GameManager + * Stub on the client side. The Game Manager methods contain the code for + * remote invocation. + * + * This class is normally generated with rmic from the {@link GameManagerImpl}: + *
+ * rmic -iiop -poa -keep gnu.classpath.examples.CORBA.swing.x5.GameManagerImpl
+ * 
+ * (the compiled package must be present in the current folder). + * + * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) + */ +public class _GameManager_Stub extends Stub implements GameManager +{ + /** + * Use serialVersionUID for interoperability. + */ + private static final long serialVersionUID = 1; + + private static final String[] _type_ids = + { "RMI:gnu.classpath.examples.CORBA.swing.x5.GameManager:0000000000000000" }; + + public String[] _ids() + { + return _type_ids; + } + + /** + * Notify the manager that the player is no longer willing to play and + * should be removed from the queue. + */ + public void unregister(Player p) + throws RemoteException + { + if (!Util.isLocal(this)) + { + try + { + org.omg.CORBA.portable.InputStream in = null; + try + { + OutputStream out = _request("unregister", true); + Util.writeRemoteObject(out, p); + _invoke(out); + } + catch (ApplicationException ex) + { + in = ex.getInputStream(); + + String id = in.read_string(); + throw new UnexpectedException(id); + } + catch (RemarshalException ex) + { + unregister(p); + } + finally + { + _releaseReply(in); + } + } + catch (SystemException ex) + { + throw Util.mapSystemException(ex); + } + } + else + { + ServantObject so = + _servant_preinvoke("requestTheGame", GameManager.class); + if (so == null) + { + unregister(p); + return; + } + try + { + ((GameManager) so.servant).unregister(p); + } + catch (Throwable ex) + { + Throwable exCopy = (Throwable) Util.copyObject(ex, _orb()); + throw Util.wrapException(exCopy); + } + finally + { + _servant_postinvoke(so); + } + } + } + + /** + * The method that the user should invoke. + */ + public void requestTheGame(Player arg0) throws RemoteException + { + if (!Util.isLocal(this)) + { + try + { + org.omg.CORBA.portable.InputStream in = null; + try + { + OutputStream out = _request("requestTheGame", true); + Util.writeRemoteObject(out, arg0); + _invoke(out); + } + catch (ApplicationException ex) + { + in = ex.getInputStream(); + + String id = in.read_string(); + throw new UnexpectedException(id); + } + catch (RemarshalException ex) + { + requestTheGame(arg0); + } + finally + { + _releaseReply(in); + } + } + catch (SystemException ex) + { + throw Util.mapSystemException(ex); + } + } + else + { + ServantObject so = + _servant_preinvoke("requestTheGame", GameManager.class); + if (so == null) + { + requestTheGame(arg0); + return; + } + try + { + Player arg0Copy = (Player) Util.copyObject(arg0, _orb()); + ((GameManager) so.servant).requestTheGame(arg0Copy); + } + catch (Throwable ex) + { + Throwable exCopy = (Throwable) Util.copyObject(ex, _orb()); + throw Util.wrapException(exCopy); + } + finally + { + _servant_postinvoke(so); + } + } + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/_PlayerImpl_Tie.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/_PlayerImpl_Tie.java new file mode 100644 index 000000000..bc2333c07 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/_PlayerImpl_Tie.java @@ -0,0 +1,209 @@ +/* _PlayerImpl_Tie.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + + This file is part of GNU Classpath. + + GNU Classpath is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + GNU Classpath is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. + + Linking this library statically or dynamically with other modules is + making a combined work based on this library. Thus, the terms and + conditions of the GNU General Public License cover the whole + combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent + modules, and to copy and distribute the resulting executable under + terms of your choice, provided that you also meet, for each linked + independent module, the terms and conditions of the license of that + module. An independent module is a module which is not derived from + or based on this library. If you modify this library, you may extend + this exception to your version of the library, but you are not + obligated to do so. If you do not wish to do so, delete this + exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.swing.x5; + +import java.awt.Point; +import java.rmi.Remote; + +import javax.rmi.PortableRemoteObject; +import javax.rmi.CORBA.Tie; + +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.UnknownException; +import org.omg.PortableServer.Servant; + +/** + * Generate with rmic, command line + * rmic -iiop -poa -keep gnu.classpath.examples.CORBA.swing.x5.PlayerImpl + * (the compiled package must be present in the current folder). + * + * This class is normally generated with rmic or grmic from the + * {@link PlayerImpl}. See tools/gnu/classpath/tools/giop/README. + * + * In this example the class was manually edited and commented for better + * understanding of functionality. + * + * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) + */ +public class _PlayerImpl_Tie extends Servant implements Tie +{ + private PlayerImpl target = null; + private static final String[] _type_ids = + { "RMI:gnu.classpath.examples.CORBA.swing.x5.Player:0000000000000000" }; + + public void setTarget(Remote a_target) + { + this.target = (PlayerImpl) a_target; + } + + public Remote getTarget() + { + return target; + } + + public org.omg.CORBA.Object thisObject() + { + return _this_object(); + } + + public void deactivate() + { + try + { + _poa().deactivate_object(_poa().servant_to_id(this)); + } + catch (org.omg.PortableServer.POAPackage.WrongPolicy exception) + { + } + catch (org.omg.PortableServer.POAPackage.ObjectNotActive exception) + { + } + catch (org.omg.PortableServer.POAPackage.ServantNotActive exception) + { + } + } + + public ORB orb() + { + return _orb(); + } + + public void orb(ORB orb) + { + try + { + ((org.omg.CORBA_2_3.ORB) orb).set_delegate(this); + } + catch (ClassCastException e) + { + throw new org.omg.CORBA.BAD_PARAM( + "POA Servant requires an instance of org.omg.CORBA_2_3.ORB" + ); + } + } + + public String[] _all_interfaces(org.omg.PortableServer.POA poa, + byte[] objectId + ) + { + return _type_ids; + } + + public OutputStream _invoke(String method, InputStream _in, + ResponseHandler reply + ) throws SystemException + { + try + { + org.omg.CORBA_2_3.portable.InputStream in = + (org.omg.CORBA_2_3.portable.InputStream) _in; + switch (method.charAt(9)) + { + case 101 : + if (method.equals("start_game")) + { + Player arg0 = + (Player) PortableRemoteObject.narrow(in.read_Object(), + Player.class + ); + boolean arg1 = in.read_boolean(); + boolean result = target.start_game(arg0, arg1); + OutputStream out = reply.createReply(); + out.write_boolean(result); + return out; + } + + case 104 : + if (method.equals("receive_chat")) + { + byte arg0 = in.read_octet(); + String arg1 = (String) in.read_value(String.class); + target.receive_chat(arg0, arg1); + + OutputStream out = reply.createReply(); + return out; + } + + case 111 : + if (method.equals("receive_move")) + { + int arg0 = in.read_long(); + int arg1 = in.read_long(); + Point[] arg2 = (Point[]) in.read_value(Point[].class); + target.receive_move(arg0, arg1, arg2); + + OutputStream out = reply.createReply(); + return out; + } + + case 114 : + if (method.equals("_get_J_current_state")) + { + int result = target.get_current_state(); + OutputStream out = reply.createReply(); + out.write_long(result); + return out; + } + + case 116 : + if (method.equals("disconnect")) + { + target.disconnect(); + + OutputStream out = reply.createReply(); + return out; + } + } + throw new BAD_OPERATION("No such method: '"+method+"'"); + } + catch (SystemException ex) + { + throw ex; + } + catch (Throwable ex) + { + throw new UnknownException(ex); + } + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/_Player_Stub.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/_Player_Stub.java new file mode 100644 index 000000000..c5a2089ee --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/_Player_Stub.java @@ -0,0 +1,397 @@ +/* _Player_Stub.java -- + Copyright (C) 2005 Free Software Foundation, Inc. + + This file is part of GNU Classpath. + + GNU Classpath is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + GNU Classpath is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. + + Linking this library statically or dynamically with other modules is + making a combined work based on this library. Thus, the terms and + conditions of the GNU General Public License cover the whole + combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent + modules, and to copy and distribute the resulting executable under + terms of your choice, provided that you also meet, for each linked + independent module, the terms and conditions of the license of that + module. An independent module is a module which is not derived from + or based on this library. If you modify this library, you may extend + this exception to your version of the library, but you are not + obligated to do so. If you do not wish to do so, delete this + exception statement from your version. */ + + +package gnu.classpath.examples.CORBA.swing.x5; + +import java.awt.Point; +import java.io.Serializable; +import java.rmi.RemoteException; +import java.rmi.UnexpectedException; + +import javax.rmi.CORBA.Stub; +import javax.rmi.CORBA.Util; + +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.RemarshalException; +import org.omg.CORBA.portable.ServantObject; + +/** + * Generate with rmic, command line + * rmic -iiop -poa -keep gnu.classpath.examples.CORBA.swing.x5.PlayerImpl + * (the compiled package must be present in the current folder). + * + * This class is normally generated with rmic from the {@link GameManagerImpl}: + *
+ * rmic -iiop -poa -keep gnu.classpath.examples.CORBA.swing.x5.GameManagerImpl
+ * 
+ * (the compiled package must be present in the current folder). + * + * In this example the class was manually edited and commented for better + * understanding of functionality. + * + * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) + */ +public class _Player_Stub extends Stub implements Player +{ + /** + * Use serialVersionUID for interoperability. + */ + private static final long serialVersionUID = 1; + + private static final String[] _type_ids = + { "RMI:gnu.classpath.examples.CORBA.swing.x5.Player:0000000000000000" }; + + public String[] _ids() + { + return _type_ids; + } + + public boolean start_game(Player arg0, boolean arg1) + throws RemoteException + { + if (!Util.isLocal(this)) + { + try + { + org.omg.CORBA.portable.InputStream in = null; + try + { + OutputStream out = _request("start_game", true); + Util.writeRemoteObject(out, arg0); + out.write_boolean(arg1); + in = _invoke(out); + return in.read_boolean(); + } + catch (ApplicationException ex) + { + in = ex.getInputStream(); + + String id = in.read_string(); + throw new UnexpectedException(id); + } + catch (RemarshalException ex) + { + return start_game(arg0, arg1); + } + finally + { + _releaseReply(in); + } + } + catch (SystemException ex) + { + throw Util.mapSystemException(ex); + } + } + else + { + ServantObject so = _servant_preinvoke("start_game", Player.class); + if (so == null) + { + return start_game(arg0, arg1); + } + try + { + Player arg0Copy = (Player) Util.copyObject(arg0, _orb()); + return ((Player) so.servant).start_game(arg0Copy, arg1); + } + catch (Throwable ex) + { + Throwable exCopy = (Throwable) Util.copyObject(ex, _orb()); + throw Util.wrapException(exCopy); + } + finally + { + _servant_postinvoke(so); + } + } + } + + public int get_current_state() throws RemoteException + { + if (!Util.isLocal(this)) + { + try + { + org.omg.CORBA.portable.InputStream in = null; + try + { + OutputStream out = _request("_get_J_current_state", true); + in = _invoke(out); + return in.read_long(); + } + catch (ApplicationException ex) + { + in = ex.getInputStream(); + + String id = in.read_string(); + throw new UnexpectedException(id); + } + catch (RemarshalException ex) + { + return get_current_state(); + } + finally + { + _releaseReply(in); + } + } + catch (SystemException ex) + { + throw Util.mapSystemException(ex); + } + } + else + { + ServantObject so = + _servant_preinvoke("_get_J_current_state", Player.class); + if (so == null) + { + return get_current_state(); + } + try + { + return ((Player) so.servant).get_current_state(); + } + catch (Throwable ex) + { + Throwable exCopy = (Throwable) Util.copyObject(ex, _orb()); + throw Util.wrapException(exCopy); + } + finally + { + _servant_postinvoke(so); + } + } + } + + public void receive_chat(byte arg0, String arg1) throws RemoteException + { + if (!Util.isLocal(this)) + { + try + { + org.omg.CORBA_2_3.portable.InputStream in = null; + try + { + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) _request("receive_chat", + true + ); + out.write_octet(arg0); + out.write_value(arg1, String.class); + _invoke(out); + } + catch (ApplicationException ex) + { + in = + (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + + String id = in.read_string(); + throw new UnexpectedException(id); + } + catch (RemarshalException ex) + { + receive_chat(arg0, arg1); + } + finally + { + _releaseReply(in); + } + } + catch (SystemException ex) + { + throw Util.mapSystemException(ex); + } + } + else + { + ServantObject so = _servant_preinvoke("receive_chat", Player.class); + if (so == null) + { + receive_chat(arg0, arg1); + return; + } + try + { + ((Player) so.servant).receive_chat(arg0, arg1); + } + catch (Throwable ex) + { + Throwable exCopy = (Throwable) Util.copyObject(ex, _orb()); + throw Util.wrapException(exCopy); + } + finally + { + _servant_postinvoke(so); + } + } + } + + public void disconnect() throws RemoteException + { + if (!Util.isLocal(this)) + { + try + { + org.omg.CORBA.portable.InputStream in = null; + try + { + OutputStream out = _request("disconnect", true); + _invoke(out); + } + catch (ApplicationException ex) + { + in = ex.getInputStream(); + + String id = in.read_string(); + throw new UnexpectedException(id); + } + catch (RemarshalException ex) + { + disconnect(); + } + finally + { + _releaseReply(in); + } + } + catch (SystemException ex) + { + throw Util.mapSystemException(ex); + } + } + else + { + ServantObject so = _servant_preinvoke("disconnect", Player.class); + if (so == null) + { + disconnect(); + return; + } + try + { + ((Player) so.servant).disconnect(); + } + catch (Throwable ex) + { + Throwable exCopy = (Throwable) Util.copyObject(ex, _orb()); + throw Util.wrapException(exCopy); + } + finally + { + _servant_postinvoke(so); + } + } + } + + public void receive_move(int arg0, int arg1, Point[] arg2) + throws RemoteException + { + if (!Util.isLocal(this)) + { + try + { + org.omg.CORBA_2_3.portable.InputStream in = null; + try + { + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) _request("receive_move", + true + ); + out.write_long(arg0); + out.write_long(arg1); + out.write_value(cast_array(arg2), Point[].class); + _invoke(out); + } + catch (ApplicationException ex) + { + in = + (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + + String id = in.read_string(); + throw new UnexpectedException(id); + } + catch (RemarshalException ex) + { + receive_move(arg0, arg1, arg2); + } + finally + { + _releaseReply(in); + } + } + catch (SystemException ex) + { + throw Util.mapSystemException(ex); + } + } + else + { + ServantObject so = _servant_preinvoke("receive_move", Player.class); + if (so == null) + { + receive_move(arg0, arg1, arg2); + return; + } + try + { + Point[] arg2Copy = (Point[]) Util.copyObject(arg2, _orb()); + ((Player) so.servant).receive_move(arg0, arg1, arg2Copy); + } + catch (Throwable ex) + { + Throwable exCopy = (Throwable) Util.copyObject(ex, _orb()); + throw Util.wrapException(exCopy); + } + finally + { + _servant_postinvoke(so); + } + } + } + + // This method is required as a work-around for + // a bug in the JDK 1.1.6 verifier. + private Serializable cast_array(Object obj) + { + return (Serializable) obj; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/awt/AicasGraphicsBenchmark.java b/libjava/classpath/examples/gnu/classpath/examples/awt/AicasGraphicsBenchmark.java new file mode 100644 index 000000000..20cd5926e --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/awt/AicasGraphicsBenchmark.java @@ -0,0 +1,1018 @@ +/* AnimationApplet.java -- An example of an old-style AWT applet + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.awt; + +import java.awt.BorderLayout; +import java.awt.Canvas; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Image; +import java.awt.Insets; +import java.awt.Label; +import java.awt.Panel; +import java.awt.Toolkit; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.net.URL; +import java.util.Iterator; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.TreeMap; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class AicasGraphicsBenchmark extends Panel +{ + /** + * Default number of test-iterations. + */ + private static final int DEFAULT_TEST_SIZE = 1000; + + /** + * Default screen size. + */ + private static final int DEFAULT_SCREEN_WIDTH = 320; + private static final int DEFAULT_SCREEN_HEIGHT = 240; + + /** + * AWT tests. + */ + private static final int AWTTEST_LINES = 1 << 0; + private static final int AWTTEST_RECT = 1 << 1; + private static final int AWTTEST_POLYLINE = 1 << 2; + private static final int AWTTEST_POLYGON = 1 << 3; + private static final int AWTTEST_ARC = 1 << 4; + private static final int AWTTEST_OVAL = 1 << 5; + private static final int AWTTEST_ROUNDRECT = 1 << 6; + private static final int AWTTEST_STRING = 1 << 7; + private static final int AWTTEST_TRANSPARENTIMAGE = 1 << 8; + private static final int AWTTEST_IMAGE = 1 << 9; + + private static final int AWTTEST_NONE = 0; + private static final int AWTTEST_ALL = AWTTEST_LINES + | AWTTEST_RECT + | AWTTEST_POLYLINE + | AWTTEST_POLYGON + | AWTTEST_ARC + | AWTTEST_OVAL + | AWTTEST_ROUNDRECT + | AWTTEST_STRING + | AWTTEST_TRANSPARENTIMAGE + | AWTTEST_IMAGE + ; + + int iterations = 1; + private int screenWidth = DEFAULT_SCREEN_WIDTH; + private int screenHeight = DEFAULT_SCREEN_HEIGHT; + boolean doubleBufferFlag = true; + private int awtTests = AWTTEST_ALL; + + private Label testLabel; + + private String testContext = ""; + + Logger logger = Logger.getLogger("AicasGraphicsBenchmark"); + + private Image pngTestImage; + private Image gifTestImage; + + private TestSet testSetMap = new TestSet(); + + public AicasGraphicsBenchmark() + { + pngTestImage = loadImage("../icons/aicas.png"); + gifTestImage = loadImage("../icons/palme.gif"); + + setLayout(new BorderLayout()); + testLabel = new Label(); + add(testLabel,BorderLayout.NORTH); + add(new GraphicsTest(),BorderLayout.CENTER); + } + + void setTestContext(String testName) + { + logger.logp(Level.INFO, "AicasGraphicsBenchmark", "recordTest", + "--- Starting new test context: " + testName); + testContext = testName; + testLabel.setText(testName); + } + + private void recordTest(String testName, long time) + { + logger.logp(Level.INFO, "AicasGraphicsBenchmark", "recordTest", + testContext + ": " + testName + " duration (ms): " + time); + TestRecorder recorder = testSetMap.getTest(testName); + if (recorder == null) + { + recorder = new TestRecorder(testName); + testSetMap.putTest(testName,recorder); + } + recorder.addRun(time); + } + + void printReport() + { + for (Iterator i = testSetMap.testIterator(); i.hasNext(); ) + { + TestRecorder recorder = testSetMap.getTest((String)i.next()); + System.out.println("TEST " + recorder.getTestName() + ": average " + + recorder.getAverage() + "ms [" + + recorder.getMinTime() + "-" + recorder.getMaxTime() + + "]"); + } + } + + public static void main(String[] args) + { + int awtTests; + int i; + boolean endOfOptionsFlag; + AicasGraphicsBenchmark speed= new AicasGraphicsBenchmark(); + + // Parse arguments. + i = 0; + endOfOptionsFlag = false; + awtTests = AWTTEST_NONE; + while (i < args.length) + { + if (!endOfOptionsFlag) + { + if (args[i].equals("--help") || args[i].equals("-help") + || args[i].equals("-h")) + { + System.out.println("Usage: AicasGraphicsBenchmark [] [ ...]"); + System.out.println(""); + System.out.println("Options: -i|--iterations= - number of iterations (-1 is infinite)"); + System.out.println(" -w|--width= - screen width; default "+DEFAULT_SCREEN_WIDTH); + System.out.println(" -h|--height= - screen height; default "+DEFAULT_SCREEN_HEIGHT); + System.out.println(" -n|--noDoubleBuffer - disable double-buffering test"); + System.out.println(""); + System.out.println("Tests: line"); + System.out.println(" rect"); + System.out.println(" polyline"); + System.out.println(" polygon"); + System.out.println(" arc"); + System.out.println(" oval"); + System.out.println(" roundrect"); + System.out.println(" string"); + System.out.println(" transparentimage"); + System.out.println(" image"); + System.exit(1); + } + else if ((args[i].startsWith("-i=") + || args[i].startsWith("--iterations="))) + { + speed.iterations = + Integer.parseInt(args[i].substring(args[i].indexOf('=') + 1)); + i += 1; + continue; + } + else if ((args[i].equals("-i") || args[i].equals("--iterations"))) + { + if ((i + 1) >= args.length) + { + System.err.println("ERROR: No argument given for option '" + + args[i] + "'!"); + System.exit(2); + } + speed.iterations = Integer.parseInt(args[i + 1]); + i += 2; + continue; + } + else if ((args[i].startsWith("-w=") + || args[i].startsWith("--width="))) + { + speed.screenWidth = + Integer.parseInt(args[i].substring(args[i].indexOf('=') + 1)); + i += 1; + continue; + } + else if ((args[i].equals("-w") || args[i].equals("--width"))) + { + if ((i + 1) >= args.length) + { + System.err.println("ERROR: No argument given for option '" + + args[i] + "'!"); + System.exit(2); + } + speed.screenWidth = Integer.parseInt(args[i + 1]); + i += 2; + continue; + } + else if ((args[i].startsWith("-h=") + || args[i].startsWith("--height="))) + { + speed.screenHeight = + Integer.parseInt(args[i].substring(args[i].indexOf('=') + 1)); + i+=1; + continue; + } + else if ((args[i].equals("-h") || args[i].equals("--height"))) + { + if ((i+1) >= args.length) + { + System.err.println("ERROR: No argument given for option '" + + args[i] + "'!"); + System.exit(2); + } + speed.screenHeight = Integer.parseInt(args[i + 1]); + i += 2; + continue; + } + else if ((args[i].equals("-n") + || args[i].equals("--noDoubleBuffer"))) + { + speed.doubleBufferFlag = false; + i += 1; + continue; + } + else if (args[i].equals("--")) + { + endOfOptionsFlag = true; + i += 1; + continue; + } + else if (args[i].startsWith("-")) + { + System.err.println("ERROR: Unknown option '" + args[i] + "'!"); + System.exit(2); + } + } + StringTokenizer tokenizer = new StringTokenizer(args[i], " +,"); + while (tokenizer.hasMoreTokens()) + { + String s = tokenizer.nextToken().toLowerCase(); + if (s.equals("line")) + awtTests |= AWTTEST_LINES; + else if (s.equals("rect")) + awtTests |= AWTTEST_RECT; + else if (s.equals("polyline")) + awtTests |= AWTTEST_POLYLINE; + else if (s.equals("polygon")) + awtTests |= AWTTEST_POLYGON; + else if (s.equals("arc")) + awtTests |= AWTTEST_ARC; + else if (s.equals("oval")) + awtTests |= AWTTEST_OVAL; + else if (s.equals("roundrect")) + awtTests |= AWTTEST_ROUNDRECT; + else if (s.equals("string")) + awtTests |= AWTTEST_STRING; + else if (s.equals("transparentimage")) + awtTests |= AWTTEST_TRANSPARENTIMAGE; + else if (s.equals("image")) + awtTests |= AWTTEST_IMAGE; + else + { + System.err.println("Unknown AWT test '" + s + "'!"); + System.exit(2); + } + } + i += 1; + } + if (awtTests != AWTTEST_NONE) + speed.awtTests = awtTests; + + // Create graphics. + final Frame frame = new Frame("AicasGraphicsBenchmark"); + + frame.addWindowListener(new WindowAdapter() + { + public void windowClosing(WindowEvent e) + { + frame.setVisible(false); + System.exit(0); + } + }); + + frame.add(speed,BorderLayout.CENTER); + frame.setSize(speed.screenWidth,speed.screenHeight); + frame.setVisible(true); + + // Insets are correctly set only after the native peer was created. + Insets insets = frame.getInsets(); + // The internal size of the frame should be 320x240. + frame.setSize(320 + insets.right + insets.left, + 240 + insets.top + insets.bottom); + } + + private Image loadImage(String imageName) + { + Image result = null; + logger.logp(Level.INFO, "AicasGraphicsBenchmark", "loadImage", + "Loading image: " + imageName); + URL url = getClass().getResource(imageName); + if (url != null) + { + result = Toolkit.getDefaultToolkit().getImage(url); + prepareImage(result, this); + } + else + { + logger.logp(Level.WARNING, "AicasGraphicsBenchmark", "loadImage", + "Could not locate image resource in class path: " + + imageName); + } + return result; + } + + /** + * Executes the test methods. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + void runTestSet(Graphics g, Dimension size) + { + if ((awtTests & AWTTEST_LINES) != 0) + test_drawLine(g, size); + if ((awtTests & AWTTEST_RECT) != 0) + test_drawRect(g, size); + if ((awtTests & AWTTEST_RECT) != 0) + test_fillRect(g, size); + if ((awtTests & AWTTEST_POLYLINE) != 0) + test_drawPolyline(g, size); + if ((awtTests & AWTTEST_POLYGON) != 0) + test_drawPolygon(g, size); + if ((awtTests & AWTTEST_POLYGON) != 0) + test_fillPolygon(g,size); + if ((awtTests & AWTTEST_ARC) != 0) + test_drawArc(g,size); + if ((awtTests & AWTTEST_ARC) != 0) + test_fillArc(g,size); + if ((awtTests & AWTTEST_OVAL) != 0) + test_drawOval(g, size); + if ((awtTests & AWTTEST_OVAL) != 0) + test_fillOval(g, size); + if ((awtTests & AWTTEST_ROUNDRECT) != 0) + test_fillRoundRect(g, size); + if ((awtTests & AWTTEST_STRING) != 0) + test_drawString(g, size); + if ((awtTests & AWTTEST_TRANSPARENTIMAGE) != 0) + test_drawTransparentImage(g,size); + if ((awtTests & AWTTEST_IMAGE) != 0) + test_drawImage(g,size); + } + + /** + * Gets a new random Color. + * + * @returna new random Color + */ + private Color getNextColor() + { + return new Color((int) (Math.random() * 254) + 1, + (int) (Math.random() * 254) + 1, + (int) (Math.random() * 254) + 1); + } + + /** + * Draws random lines within the given dimensions. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawLine(Graphics g, Dimension size) + { + int maxTests = DEFAULT_TEST_SIZE; + int minSize = 10; + long startTime = System.currentTimeMillis(); + for (int i=0; i < maxTests; i += 1) + { + g.setColor(getNextColor()); + int x1 = (int) (Math.random() * (size.width-minSize)); + int y1 = (int) (Math.random() * (size.height-minSize)); + int x2 = (int) (Math.random() * (size.width-minSize)); + int y2 = (int) (Math.random() * (size.height-minSize)); + g.drawLine(x1, y1, x2, y2); + } + long endTime = System.currentTimeMillis(); + recordTest("drawLine " + maxTests + " times", (endTime-startTime)); + } + + /** + * Draws random rectangles within the given dimensions. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawRect(Graphics g, Dimension size) + { + int maxTests = DEFAULT_TEST_SIZE; + int minSize = 10; + long startTime = System.currentTimeMillis(); + for (int i=0; i < maxTests; i += 1) + { + g.setColor(getNextColor()); + int x1 = (int) (Math.random() * (size.width-minSize)); + int y1 = (int) (Math.random() * (size.height-minSize)); + int x2 = (int) (Math.random() * (size.width-minSize)); + int y2 = (int) (Math.random() * (size.height-minSize)); + g.drawRect(x1, y1, x2, y2); + } + long endTime = System.currentTimeMillis(); + recordTest("drawRect " + maxTests + " times", (endTime-startTime)); + } + + /** + * Draws random rectangles within the given dimensions. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_fillRect(Graphics g, Dimension size) + { + int maxTests = DEFAULT_TEST_SIZE; + int minSize = 10; + long startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + g.setColor(getNextColor()); + int x1 = (int) (Math.random() * (size.width-minSize)); + int y1 = (int) (Math.random() * (size.height-minSize)); + int x2 = (int) (Math.random() * (size.width-minSize)); + int y2 = (int) (Math.random() * (size.height-minSize)); + g.fillRect(x1, y1, x2, y2); + } + long endTime = System.currentTimeMillis(); + recordTest("fillRect " + maxTests + " times", (endTime-startTime)); + } + + /** + * Draws random polylines within the given dimensions. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawPolyline(Graphics g, Dimension size) + { + int maxTests = DEFAULT_TEST_SIZE; + long startTime = System.currentTimeMillis(); + for (int i=0; i < maxTests; i += 1) + { + g.setColor(getNextColor()); + int points = (int)(Math.random() * 6) + 3; + int[] x_coords = new int[points]; + int[] y_coords = new int[points]; + for (int j = 0; j < points; j+=1) + { + x_coords[j] = (int)(Math.random() * (size.width)); + y_coords[j] = (int)(Math.random() * (size.height)); + } + g.drawPolyline(x_coords,y_coords, points); + } + long endTime = System.currentTimeMillis(); + recordTest("drawPolyline " + maxTests + " times", (endTime-startTime)); + } + + /** + * Draws random polygons within the given dimensions. + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawPolygon(Graphics g, Dimension size) + { + int maxTests = DEFAULT_TEST_SIZE; + long startTime = System.currentTimeMillis(); + for (int i=0; i < maxTests; i += 1) + { + g.setColor(getNextColor()); + int points = (int) (Math.random() * 6) + 3; + int[] xcoords = new int[points]; + int[] ycoords = new int[points]; + for(int j = 0; j < points; j+=1) + { + xcoords[j] = (int) (Math.random() * (size.width)); + ycoords[j] = (int) (Math.random() * (size.height)); + } + g.drawPolygon(xcoords, ycoords, points); + } + long endTime = System.currentTimeMillis(); + recordTest("drawPolygon " + maxTests + " times", (endTime-startTime)); + } + + /** + * Draws random filled polygons within the given dimensions. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_fillPolygon(Graphics g, Dimension size) + { + int maxTests = DEFAULT_TEST_SIZE; + long startTime = System.currentTimeMillis(); + for (int i=0; i < maxTests; i += 1) + { + g.setColor(getNextColor()); + int points = (int) (Math.random() * 6) + 3; + int[] xcoords = new int[points]; + int[] ycoords = new int[points]; + for (int j = 0; j < points; j+=1) + { + xcoords[j] = (int) (Math.random() * (size.width)); + ycoords[j] = (int) (Math.random() * (size.height)); + } + g.fillPolygon(xcoords, ycoords, points); + } + long endTime = System.currentTimeMillis(); + recordTest("fillPolygon " + maxTests + " times", (endTime-startTime)); + } + + /** + * Draws random arcs within the given dimensions. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawArc(Graphics g, Dimension size) + { + int maxTests = DEFAULT_TEST_SIZE; + int minSize; + long startTime; + long endTime; + minSize = 10; + startTime = System.currentTimeMillis(); + for (int i=0; i < maxTests; i += 1) + { + g.setColor(getNextColor()); + int x = (int) (Math.random() * (size.width - minSize + 1)); + int y = (int) (Math.random() * (size.height - minSize + 1)); + int width = (int) (Math.random() * (size.width - x - minSize) + minSize); + int height = (int) (Math.random() * (size.height - y - minSize) + minSize); + int startAngle = (int) (Math.random() * 360); + int arcAngle = (int) (Math.random() * 360 - startAngle); + g.drawArc(x, y, width, height, startAngle, arcAngle); + } + endTime = System.currentTimeMillis(); + recordTest("drawArc " + maxTests + " times", (endTime-startTime)); + } + + /** + * Draws random filled arcs within the given dimensions. + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_fillArc(Graphics g, Dimension size) + { + int maxTests = DEFAULT_TEST_SIZE; + int minSize; + long startTime; + long endTime; + minSize = 10; + startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + g.setColor(getNextColor()); + int x = (int) (Math.random() * (size.width - minSize + 1)); + int y = (int) (Math.random() * (size.height - minSize + 1)); + int width = (int)(Math.random() * (size.width - x - minSize) + minSize); + int height = (int)(Math.random() * (size.height - y - minSize) + minSize); + int startAngle = (int)(Math.random() * 360); + int arcAngle = (int)(Math.random() * 360); + g.fillArc(x, y, width, height, startAngle, arcAngle); + + } + endTime = System.currentTimeMillis(); + recordTest("fillArc " + maxTests + " times", (endTime - startTime)); + } + + /** + * Draws random ovals within the given dimensions. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawOval(Graphics g, Dimension size) + { + int maxTests = DEFAULT_TEST_SIZE; + int minSize; + long startTime; + long endTime; + minSize = 10; + startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + g.setColor(getNextColor()); + int x = (int)(Math.random() * (size.width - minSize + 1)); + int y = (int)(Math.random() * (size.height - minSize + 1)); + int width = (int)(Math.random() * (size.width - x - minSize) + minSize); + int height = (int)(Math.random() * (size.height - y - minSize) + minSize); + g.drawOval(x, y, Math.min(width, height), Math.min(width, height)); + } + endTime = System.currentTimeMillis(); + recordTest("drawOval " + maxTests + " times", (endTime-startTime)); + } + + /** + * Draws random filled ovals within the given dimensions. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_fillOval(Graphics g, Dimension size) + { + int maxTests = DEFAULT_TEST_SIZE; + int minSize; + long startTime; + long endTime; + minSize = 10; + startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + g.setColor(getNextColor()); + int x = (int) (Math.random() * (size.width - minSize + 1)); + int y = (int) (Math.random() * (size.height - minSize + 1)); + int width = (int) (Math.random() * (size.width - x - minSize) + minSize); + int height = (int) (Math.random() * (size.height - y - minSize) + minSize); + g.fillOval(x, y, width,height); + } + endTime = System.currentTimeMillis(); + recordTest("fillOval " + maxTests + " times", (endTime-startTime)); + } + + /** + * Draws random filled rounded rectangles within the given dimensions. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_fillRoundRect(Graphics g, Dimension size) + { + int maxTests = DEFAULT_TEST_SIZE; + int minSize; + long startTime; + long endTime; + minSize = 10; + startTime = System.currentTimeMillis(); + for (int i=0; i < maxTests; i+=1) + { + g.setColor(getNextColor()); + int x = (int) (Math.random() * (size.width - minSize + 1)); + int y = (int) (Math.random() * (size.height - minSize + 1)); + int width = (int) (Math.random() * (size.width - x - minSize) + minSize); + int height = (int) (Math.random() * (size.height - y - minSize) + minSize); + int arcWidth = (int) (Math.random() * (width - 1) + 1); + int arcHeight = (int) (Math.random() * (height - 1) + 5); + g.fillRoundRect(x, y, width, height, arcWidth, arcHeight); + } + endTime = System.currentTimeMillis(); + recordTest("fillRoundRect " + maxTests + " times", (endTime-startTime)); + } + + /** + * Draws random images within the given dimensions. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawImage(Graphics g, Dimension size) + { + if (gifTestImage == null) + { + logger.logp(Level.WARNING, "AicasGraphicsBenchmark", "runTestSet", + "Skipping 'test_drawImage' due to missing resource."); + return; + } + + int maxTests = DEFAULT_TEST_SIZE / 2; + if(maxTests == 0) + maxTests = 1; + int imageWidth = gifTestImage.getWidth(this); + int imageHeight = gifTestImage.getHeight(this); + long startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + g.setColor(getNextColor()); + int x = (int) (Math.random() * (size.width - imageWidth + 1)); + int y = (int) (Math.random() * (size.height - imageHeight + 1)); + g.drawImage(gifTestImage, x, y, this); + } + long endTime = System.currentTimeMillis(); + recordTest("drawImage " + maxTests + " times", (endTime-startTime)); + } + + /** + * Draws random transparent images within the given dimensions. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawTransparentImage(Graphics g, Dimension size) + { + if (pngTestImage == null) + { + logger.logp(Level.WARNING, "AicasGraphicsBenchmark", "runTestSet", + "Skipping 'test_drawTransparentImage' due to missing resource."); + return; + } + + + int maxTests = DEFAULT_TEST_SIZE / 5; + if(maxTests == 0) + maxTests = 1; + int imageWidth = pngTestImage.getWidth(this); + int imageHeight = pngTestImage.getHeight(this); + long startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + g.setColor(getNextColor()); + int x = (int) (Math.random() * (size.width - imageWidth + 1)); + int y = (int) (Math.random() * (size.height - imageHeight + 1)); + g.drawImage(pngTestImage, x, y, this); + } + long endTime = System.currentTimeMillis(); + recordTest("draw transparent image " + maxTests + " times", + (endTime-startTime)); + } + + /** + * Draws random strings within the given dimensions. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawString(Graphics g, Dimension size) + { + int maxTests = DEFAULT_TEST_SIZE; + String testString = "HelloWorld"; + int stringWidth = g.getFontMetrics().stringWidth(testString); + int stringHeight = g.getFontMetrics().getHeight(); + + long startTime = System.currentTimeMillis(); + for(int i = 0; i < maxTests; i += 1) + { + g.setColor(getNextColor()); + g.drawString(testString, (int) (Math.random() * (size.width - stringWidth + 1)),(int)(Math.random() * (size.height - stringHeight + 1)) + stringHeight); + } + long endTime = System.currentTimeMillis(); + recordTest("drawString " + maxTests + " times", (endTime-startTime)); + } + + private class GraphicsTest extends Canvas implements Runnable + { + Thread paintThread; + boolean done = false; + boolean doPaint = false; + boolean withClipping = false; + + public GraphicsTest() + { + paintThread = new Thread(this); + paintThread.start(); + } + + public void run() + { + int runCount = 0; + while (!done) + { + runCount++; + + try + { + synchronized (this) + { + while (!doPaint) + { + try + { + wait(200); + } + catch (InterruptedException exception) + { + return; + } + } + } + + if (iterations != 0) + System.out.println("--- run...(" + runCount + "/" + iterations + + ") ------------------------------------------------------"); + + Graphics g = getGraphics(); + Dimension size = getSize(); + logger.logp(Level.INFO, "AicasGraphicsBenchmark.GraphicsTest", "run", + "Start testing non-double-buffered drawing"); + runSet_noClipping(g,size); + runSet_zeroClipping(g, size); + runSet_withClipping(g, size); + g.dispose(); + + if (doubleBufferFlag) + { + logger.logp(Level.INFO, "AicasGraphicsBenchmark.GraphicsTest", + "run", "Start testing double-buffered drawing"); + Graphics canvas = getGraphics(); + Image doublebuffer = createImage(size.width,size.height); + g = doublebuffer.getGraphics(); + runSet_noClipping(g,size); + g.dispose(); + canvas.drawImage(doublebuffer, 0, 0, this); + + g = doublebuffer.getGraphics(); + runSet_withClipping(g, size); + g.dispose(); + canvas.drawImage(doublebuffer, 0, 0, this); + + g = doublebuffer.getGraphics(); + runSet_zeroClipping(g, size); + g.dispose(); + canvas.drawImage(doublebuffer, 0, 0, this); + canvas.dispose(); + } + + printReport(); + + if (iterations != 0) + { + if (iterations != -1) + iterations--; + } + else + { + System.out.println("--- done --------------------------------------------------------"); + synchronized (this) + { + doPaint = false; + } + done = true; + } + } + catch (Error error) + { + System.err.println("Error: " + error); + System.exit(129); + } + } + System.exit(0); + } + + private void runSet_zeroClipping(Graphics g, Dimension size) + { + int clipped_width; + int clipped_height; + int clipped_x; + int clipped_y; + + clipped_width = 0; + clipped_height = 0; + clipped_x = (size.width) / 2; + clipped_y = (size.height) / 2; + g.setClip(0, 0, size.width, size.height); + g.setColor(Color.BLACK); + g.fillRect(0, 0, size.width, size.height); + g.setColor(Color.WHITE); + g.drawRect(0, 0, size.width - 1, size.height - 1); + g.fillRect(clipped_x - 1, clipped_y - 1, clipped_width + 2, clipped_height + 2); + + g.clipRect(clipped_x, clipped_y, clipped_width, clipped_height); + g.setColor(Color.BLACK); + g.fillRect(0, 0, size.width, size.height); + + setTestContext("clipping to zero"); + + runTestSet(g, size); + } + + private void runSet_withClipping(Graphics g, Dimension size) + { + int clipped_width = 2 * size.width / 3; + int clipped_height = 2 * size.height / 3; + int clipped_x = (size.width - clipped_width) / 2; + int clipped_y = (size.height - clipped_height) / 2; + + g.setClip(0,0,size.width,size.height); + + g.setColor(Color.BLACK); + g.fillRect(0, 0, size.width, size.height); + g.setColor(Color.GREEN); + g.drawRect(0, 0, size.width - 1, size.height - 1); + g.setColor(Color.WHITE); + g.fillRect(clipped_x - 1, clipped_y - 1, clipped_width + 2, clipped_height + 2); + + g.clipRect(clipped_x, clipped_y, clipped_width, clipped_height); + g.setColor(Color.BLACK); + g.fillRect(0, 0, size.width, size.height); + + setTestContext("with clipping"); + + runTestSet(g, size); + } + + public void runSet_noClipping(Graphics g, Dimension size) + { + g.setColor(Color.BLACK); + g.fillRect(0, 0, size.width, size.height); + + setTestContext("without clipping"); + + runTestSet(g, size); + } + + public void paint(Graphics g) + { + synchronized(this) + { + doPaint=true; + notify(); + } + } + } +} + +class TestContext +{ +} + +class TestSet +{ + private Map testsMap = new TreeMap(); + + public void putTest(String testName, TestRecorder recoder) + { + testsMap.put(testName,recoder); + } + + public TestRecorder getTest(String testName) + { + return (TestRecorder)testsMap.get(testName); + } + + public Iterator testIterator() + { + return testsMap.keySet().iterator(); + } +} + +class TestRecorder +{ + String test; + long totalTime = 0; + long minTime = Long.MAX_VALUE; + long maxTime = Long.MIN_VALUE; + int runCount = 0; + + /** + * @return Returns the maxTime. + */ + public final long getMaxTime() + { + return maxTime; + } + + /** + * @return Returns the minTime. + */ + public final long getMinTime() + { + return minTime; + } + + /** + * @return Returns the test name. + */ + public final String getTestName() + { + return test; + } + + public final double getAverage() + { + return ((double)totalTime) / ((double)runCount); + } + + public TestRecorder(String testName) + { + test = testName; + } + + public void addRun(long time) + { + totalTime += time; + if(minTime > time) + minTime = time; + if(maxTime < time) + maxTime = time; + runCount += 1; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/awt/AnimationApplet.java b/libjava/classpath/examples/gnu/classpath/examples/awt/AnimationApplet.java new file mode 100644 index 000000000..aea8cd4f6 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/awt/AnimationApplet.java @@ -0,0 +1,232 @@ +/* AnimationApplet.java -- An example of an old-style AWT applet + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.awt; + +import java.awt.*; +import java.applet.*; + + +/** + * AnimationApplet demonstrates the need for Xflush calls in + * GdkGraphics.c. To see how this demo can fail in their absence, + * remove the contents of schedule_flush in GdkGraphics.c. The + * animation will be so choppy that it is effectively stopped. + */ +public class AnimationApplet + extends Applet + implements Runnable +{ + boolean going = false; + Thread animThread = null; + int SPEED = 5; + int circleX = 0; + int circleY = 0; + int circleXold = 0; + int circleYold = 0; + int circleXdelta = 0; + int circleYdelta = 0; + int circleDiameter = 0; + int autoCircleX = 0; + int autoCircleY = 0; + int autoCircleXold = 0; + int autoCircleYold = 0; + int autoCircleXdelta = (int) (0.66 * SPEED); + int autoCircleYdelta = (int) (1.33 * SPEED); + int boardWidth = 0; + int boardHeight = 0; + int CIRCLE_SIZE = 5; + + private Graphics appletGraphics; + + // Update the circles' location values. + private void moveCircles() + { + circleX += circleXdelta; + if (circleX < 0) + circleX = 0; + if (circleX > boardWidth - circleDiameter) + circleX = boardWidth - circleDiameter; + + circleY += circleYdelta; + if (circleY < 0) + circleY = 0; + if (circleY > boardHeight - circleDiameter) + circleY = boardHeight - circleDiameter; + + autoCircleX += autoCircleXdelta; + if (autoCircleX < 0) + { + autoCircleX = 0; + autoCircleXdelta = -autoCircleXdelta; + } + if (autoCircleX > boardWidth - circleDiameter) + { + autoCircleX = boardWidth - circleDiameter; + autoCircleXdelta = -autoCircleXdelta; + } + + autoCircleY += autoCircleYdelta; + if (autoCircleY < 0) + { + autoCircleY = 0; + autoCircleYdelta = -autoCircleYdelta; + } + if (autoCircleY > boardHeight - circleDiameter) + { + autoCircleY = boardHeight - circleDiameter; + autoCircleYdelta = -autoCircleYdelta; + } + } + + // Clear the circle in the old location and paint a new circle + // in the new location. + private void paintCircles() + { + appletGraphics.setColor(Color.BLUE); + appletGraphics.fillOval(circleXold, circleYold, circleDiameter, + circleDiameter); + appletGraphics.setColor(Color.YELLOW); + appletGraphics.fillOval(circleX, circleY, circleDiameter, + circleDiameter); + + appletGraphics.setColor(Color.BLUE); + appletGraphics.fillOval(autoCircleXold, autoCircleYold, circleDiameter, + circleDiameter); + appletGraphics.setColor(Color.WHITE); + appletGraphics.fillOval(autoCircleX, autoCircleY, circleDiameter, + circleDiameter); + } + + // Override Applet.run. + public void run() + { + while (animThread != null) + { + circleXold = circleX; + circleYold = circleY; + autoCircleXold = autoCircleX; + autoCircleYold = autoCircleY; + + moveCircles(); + paintCircles(); + + if (animThread != null) + { + try + { + Thread.sleep(20); + } + catch (InterruptedException e) + { + } + } + } + } + + // Override Applet.paint. + public void paint(Graphics g) + { + boardWidth = this.getSize().width; + boardHeight = this.getSize().height; + g.setColor(Color.BLUE); + g.fillRect(0, 0, boardWidth, boardHeight); + if (!going) + { + FontMetrics fm = appletGraphics.getFontMetrics(); + appletGraphics.setColor(Color.WHITE); + String msg = "Click to Start"; + appletGraphics.drawString(msg, + (boardWidth >> 1) - (fm.stringWidth(msg) >> 1), + (boardHeight >> 1) - (fm.getHeight() >> 1)); + } + } + + // Override Applet.destroy. + public void destroy() + { + // animThread.stop(); + animThread = null; + } + + // Override Applet.init. + public void init() + { + boardWidth = this.getSize().width; + boardHeight = this.getSize().height; + going = false; + appletGraphics = getGraphics(); + appletGraphics.setFont(new Font(appletGraphics.getFont().getName(), + Font.BOLD, 15)); + } + + // Override Component.preferredSize for when we're run standalone. + public Dimension preferredSize () + { + return new Dimension (400, 400); + } + + // Override Applet.handleEvent, the old-style AWT-event handler. + public boolean handleEvent(Event event) + { + switch (event.id) + { + case Event.MOUSE_DOWN: + if (!going) + { + going = true; + circleDiameter = boardWidth / CIRCLE_SIZE; + circleX = (boardWidth - circleDiameter) >> 1; + circleY = (boardHeight - circleDiameter) >> 1; + circleXdelta = 0; + circleYdelta = 0; + repaint(); + animThread = new Thread(this); + animThread.start(); + } + break; + case Event.KEY_ACTION: + case Event.KEY_PRESS: + if (event.key == Event.LEFT) + circleXdelta = -SPEED; + else if (event.key == Event.RIGHT) + circleXdelta = SPEED; + else if (event.key == Event.UP) + circleYdelta = -SPEED; + else if (event.key == Event.DOWN) + circleYdelta = SPEED; + break; + case Event.KEY_ACTION_RELEASE: + case Event.KEY_RELEASE: + if (event.key == Event.LEFT && circleXdelta < 0) + circleXdelta = 0; + else if (event.key == Event.RIGHT && circleXdelta > 0) + circleXdelta = 0; + else if (event.key == Event.UP && circleYdelta < 0) + circleYdelta = 0; + else if (event.key == Event.DOWN && circleYdelta > 0) + circleYdelta = 0; + break; + default: + break; + } + return false; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/awt/Demo.java b/libjava/classpath/examples/gnu/classpath/examples/awt/Demo.java new file mode 100644 index 000000000..62bee8f57 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/awt/Demo.java @@ -0,0 +1,1189 @@ +/* Demo.java -- Shows examples of AWT components + Copyright (C) 1998, 1999, 2002, 2004, 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.awt; + +import java.awt.BorderLayout; +import java.awt.Button; +import java.awt.Canvas; +import java.awt.Checkbox; +import java.awt.CheckboxGroup; +import java.awt.CheckboxMenuItem; +import java.awt.Choice; +import java.awt.Color; +import java.awt.Cursor; +import java.awt.Dialog; +import java.awt.Dimension; +import java.awt.DisplayMode; +import java.awt.FileDialog; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.GraphicsDevice; +import java.awt.GraphicsEnvironment; +import java.awt.GridLayout; +import java.awt.Image; +import java.awt.Insets; +import java.awt.Label; +import java.awt.List; +import java.awt.Menu; +import java.awt.MenuBar; +import java.awt.MenuItem; +import java.awt.MenuShortcut; +import java.awt.Panel; +import java.awt.ScrollPane; +import java.awt.TextField; +import java.awt.Toolkit; +import java.awt.Window; +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.StringSelection; +import java.awt.datatransfer.Transferable; +import java.awt.datatransfer.UnsupportedFlavorException; +import java.awt.dnd.DnDConstants; +import java.awt.dnd.DragGestureEvent; +import java.awt.dnd.DragGestureListener; +import java.awt.dnd.DragSource; +import java.awt.dnd.DragSourceContext; +import java.awt.dnd.DragSourceDragEvent; +import java.awt.dnd.DragSourceDropEvent; +import java.awt.dnd.DragSourceEvent; +import java.awt.dnd.DragSourceListener; +import java.awt.dnd.DropTarget; +import java.awt.dnd.DropTargetDragEvent; +import java.awt.dnd.DropTargetDropEvent; +import java.awt.dnd.DropTargetEvent; +import java.awt.dnd.DropTargetListener; +import java.awt.dnd.InvalidDnDOperationException; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.net.URL; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Vector; + +class Demo +{ + public static void main(String args[]) + { + MainWindow f = new MainWindow(); + f.show(); + } + + static interface SubWindow + { + public void init (); + } + + static class PrettyPanel extends Panel + { + Insets myInsets; + + public PrettyPanel () + { + myInsets = new Insets (10, 10, 10, 10); + } + public Insets getInsets () + { + return myInsets; + } + } + + static abstract class PrettyFrame extends Frame + { + public PrettyFrame () + { + ((BorderLayout) getLayout ()).setHgap (5); + ((BorderLayout) getLayout ()).setVgap (5); + } + + public Insets getInsets() + { + Insets oldInsets = super.getInsets (); + return new Insets (oldInsets.top+10, + oldInsets.left+10, + oldInsets.bottom+10, + oldInsets.right+10); + } + } + + static abstract class SubFrame extends PrettyFrame implements SubWindow + { + boolean initted = false; + + public void setVisible (boolean visible) + { + if (!initted && visible) + init(); + super.setVisible (visible); + } + } + + static class MainWindow extends PrettyFrame implements ActionListener + { + Button closeButton; + + Hashtable windows; + Vector buttons; + + void addSubWindow (String name, SubWindow w) + { + Button b = new Button (name); + b.addActionListener (this); + + buttons.addElement (b); + windows.put (b, w); + } + + MainWindow () + { + MenuBar mb = new MenuBar (); + Menu menu = new Menu ("File"); + Menu submenu = new Menu ("Testing", true); + submenu.add (new CheckboxMenuItem ("FooBar")); + submenu.add (new CheckboxMenuItem ("BarFoo")); + menu.add (submenu); + menu.add (new MenuItem("Orange")); + MenuItem quit = new MenuItem("Quit", new MenuShortcut('Q')); + quit.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + System.exit(0); + } + }); + menu.add(quit); + mb.add (menu); + + menu = new Menu("Edit", true); + menu.add(new MenuItem("Cut")); + menu.add(new MenuItem("Copy")); + menu.add(new MenuItem("Paste")); + mb.add (menu); + + Menu helpMenu = new Menu("Help"); + helpMenu.add(new MenuItem("About")); + mb.add(helpMenu); + mb.setHelpMenu(helpMenu); + + setMenuBar (mb); + + String version = System.getProperty("gnu.classpath.version"); + add (new Label ("GNU Classpath " + version), "North"); + + closeButton = new Button ("Close"); + closeButton.addActionListener (this); + closeButton.setFont (new Font ("Serif", Font.BOLD | Font.ITALIC, 18)); + add (closeButton, "South"); + + windows = new Hashtable (); + buttons = new Vector (); + + addSubWindow ("Buttons", new ButtonsWindow ()); + addSubWindow ("Cursors", new CursorsWindow ()); + addSubWindow ("Dialog", new DialogWindow (this)); + addSubWindow ("File", new FileWindow (this)); + addSubWindow ("Labels", new LabelWindow ()); + addSubWindow ("List", new ListWindow ()); + addSubWindow ("Radio Buttons", new RadioWindow ()); + addSubWindow ("TextField", new TextFieldWindow ()); + addSubWindow ("RandomTests", new TestWindow (this)); + addSubWindow ("RoundRect", new RoundRectWindow ()); + addSubWindow ("Animation", new AnimationWindow ()); + addSubWindow ("Resolution", new ResolutionWindow ()); + addSubWindow ("Fullscreen", new FullscreenWindow ()); + addSubWindow ("Drag n' Drop", new DragDropWindow ()); + + Panel sp = new Panel(); + PrettyPanel p = new PrettyPanel(); + p.setLayout (new GridLayout (windows.size(), 1)); + + for (Enumeration e = buttons.elements (); e.hasMoreElements (); ) + { + p.add ((Button) e.nextElement ()); + } + + sp.add (p); + add (sp, "Center"); + + setTitle ("AWT Demo"); + pack(); + } + + public void actionPerformed (ActionEvent evt) + { + Button source = (Button) evt.getSource (); + + if (source==closeButton) + { + dispose(); + System.exit (0); + } + + Window w = (Window) windows.get (source); + if (w.isVisible ()) + w.dispose (); + else + { + if (w instanceof Dialog) + { + w.show(); + } + else + { + w.setVisible (true); + } + } + } + } + + static class ButtonsWindow extends SubFrame implements ActionListener + { + Button b[] = new Button [9]; + + public void init () + { + initted = true; + Panel p = new Panel (); + p.setLayout (new GridLayout (0, 3, 5, 5)); + + for (int i=0; i<9; i++) + { + b[i]=new Button ("button" + (i+1)); + b[i].addActionListener (this); + } + + p.add (b[0]); + p.add (b[6]); + p.add (b[4]); + p.add (b[8]); + p.add (b[1]); + p.add (b[7]); + p.add (b[3]); + p.add (b[5]); + p.add (b[2]); + + add (p, "North"); + + Button cb = new Button ("close"); + cb.addActionListener(new ActionListener () { + public void actionPerformed (ActionEvent e) { + dispose(); + } + }); + add (cb, "South"); + setTitle ("Buttons"); + pack(); + } + + public void actionPerformed (ActionEvent evt) + { + Button source = (Button) evt.getSource (); + + for (int i = 0; i < 9; i++) + { + if (source == b[i]) + { + int i2 = ((i + 1) == 9) ? 0 : (i + 1); + if (b[i2].isVisible()) + b[i2].setVisible(false); + else + b[i2].setVisible(true); + } + } + } + } + + + static class DialogWindow extends Dialog implements SubWindow + { + Label text; + Frame parent; + boolean initted = false; + + public DialogWindow (Frame f) + { + super (f, true); + + this.parent = f; + + addWindowListener (new WindowAdapter () + { + public void windowClosing (WindowEvent e) + { + text.setVisible (false); + hide (); + } + }); + } + + public void setVisible (boolean visible) + { + if (!initted && visible) + init(); + super.setVisible (visible); + } + + public void show () + { + if (!initted) + init(); + super.show (); + } + + public void init () + { + text = new Label ("Dialog Test"); + text.setAlignment (Label.CENTER); + + add (text, "North"); + text.setVisible (false); + + Panel p = new PrettyPanel(); + + Button cb = new Button ("OK"); + cb.addActionListener(new ActionListener () { + public void actionPerformed (ActionEvent e) + { + text.setVisible (false); + hide(); + } + }); + + p.setLayout (new GridLayout (1, 3)); + ((GridLayout) p.getLayout ()).setHgap (5); + ((GridLayout) p.getLayout ()).setVgap (5); + p.add (cb); + + Button toggle = new Button ("Toggle"); + p.add (toggle); + + toggle.addActionListener(new ActionListener () { + public void actionPerformed (ActionEvent e) + { + if (text.isVisible ()) + text.setVisible (false); + else + text.setVisible (true); + doLayout(); + } + }); + + Button subdlg = new Button ("SubDialog"); + p.add (subdlg); + + subdlg.addActionListener(new ActionListener () { + public void actionPerformed (ActionEvent e) + { + DialogWindow sw = new DialogWindow (parent); + sw.show (); + } + }); + + add (p, "South"); + setTitle ("Dialog"); + pack(); + } + } + + static class CursorsWindow extends SubFrame implements ItemListener + { + Choice cursorChoice; + Canvas cursorCanvas; + + public void init () + { + cursorChoice = new Choice(); + cursorChoice.add ("Default"); + cursorChoice.add ("Crosshair"); + cursorChoice.add ("Text"); + cursorChoice.add ("Wait"); + cursorChoice.add ("Southwest Resize"); + cursorChoice.add ("Southeast Resize"); + cursorChoice.add ("Northwest Resize"); + cursorChoice.add ("Northeast Resize"); + cursorChoice.add ("North Resize"); + cursorChoice.add ("South Resize"); + cursorChoice.add ("West Resize"); + cursorChoice.add ("East Resize"); + cursorChoice.add ("Hand"); + cursorChoice.add ("Move"); + + cursorChoice.addItemListener(this); + + add (cursorChoice, "North"); + + cursorCanvas = new Canvas () + { + public void paint (Graphics g) + { + Dimension d = this.getSize(); + g.setColor(Color.white); + g.fillRect(0, 0, d.width, d.height/2); + g.setColor(Color.black); + g.fillRect(0, d.height/2, d.width, d.height/2); + g.setColor(this.getBackground()); + g.fillRect(d.width/3, d.height/3, d.width/3, + d.height/3); + } + }; + + cursorCanvas.setSize (80,80); + + add (cursorCanvas, "Center"); + + Button cb = new Button ("Close"); + cb.addActionListener(new ActionListener () { + public void actionPerformed (ActionEvent e) { + dispose(); + } + }); + + add (cb, "South"); + setTitle ("Cursors"); + pack(); + } + + public void itemStateChanged (ItemEvent e) + { + int index = cursorChoice.getSelectedIndex(); + cursorCanvas.setCursor(Cursor.getPredefinedCursor(index)); + } + } + + static class TextFieldWindow extends SubFrame implements ItemListener + { + Checkbox editable, visible, sensitive; + TextField text; + + public void init () + { + initted = true; + text = new TextField ("hello world"); + add (text, "North"); + + Panel p = new Panel(); + p.setLayout (new GridLayout (3, 1)); + ((GridLayout) p.getLayout ()).setHgap (5); + ((GridLayout) p.getLayout ()).setVgap (5); + + editable = new Checkbox("Editable", true); + p.add (editable); + editable.addItemListener (this); + + visible = new Checkbox("Visible", true); + p.add (visible); + visible.addItemListener (this); + + sensitive = new Checkbox("Sensitive", true); + p.add (sensitive); + sensitive.addItemListener (this); + + add (p, "Center"); + + Button cb = new Button ("Close"); + cb.addActionListener(new ActionListener () { + public void actionPerformed (ActionEvent e) { + dispose(); + } + }); + + add (cb, "South"); + setTitle ("TextField"); + pack(); + } + + public void itemStateChanged (ItemEvent e) + { + boolean on=true; + + if (e.getStateChange () == ItemEvent.DESELECTED) + on=false; + if (e.getSource() == editable) + text.setEditable (on); + if (e.getSource() == visible) + if (on) + text.setEchoChar ((char) 0); + else + text.setEchoChar ('*'); + if (e.getSource() == sensitive) + text.setEnabled (on); + + } + } + + static class FileWindow extends FileDialog implements SubWindow + { + boolean initted = false; + + public FileWindow (MainWindow mw) + { + super (mw); + } + + public void setVisible (boolean visible) + { + if (!initted && visible) + init(); + super.setVisible (visible); + } + + public void init() + { + initted = true; + } + } + + static class LabelWindow extends SubFrame + { + public void init () + { + initted = true; + + Panel p = new Panel(); + p.setLayout (new GridLayout (3, 1)); + ((GridLayout) p.getLayout ()).setHgap (5); + ((GridLayout) p.getLayout ()).setVgap (5); + + p.add (new Label ("left justified label", Label.LEFT)); + p.add (new Label ("center justified label", Label.CENTER)); + p.add (new Label ("right justified label", Label.RIGHT)); + + add (p, "Center"); + + Button cb = new Button ("Close"); + cb.addActionListener(new ActionListener () { + public void actionPerformed (ActionEvent e) { + dispose(); + } + }); + + add (cb, "South"); + setTitle ("Labels"); + pack(); + } + } + + static class ListWindow extends SubFrame + { + public void init () + { + initted = true; + + Panel p = new Panel (); + p.setLayout (new GridLayout (3, 1)); + + List l = new List (5, true); + for (int i = 0; i < 10; i++) + l.add ("List item " + i); + + p.add (l); + + add (p, "Center"); + + Button cb = new Button ("Close"); + cb.addActionListener(new ActionListener () { + public void actionPerformed (ActionEvent e) { + dispose(); + } + }); + + add (cb, "South"); + setTitle ("List"); + pack(); + } + } + + + static class RadioWindow extends SubFrame + { + public void init () + { + initted = true; + + Panel p = new Panel(); + p.setLayout (new GridLayout (3, 1)); + ((GridLayout) p.getLayout ()).setHgap (5); + ((GridLayout) p.getLayout ()).setVgap (5); + + final CheckboxGroup cg = new CheckboxGroup(); + final Checkbox[] boxes = new Checkbox[3]; + for (int i = 0; i < 3; ++i) + { + boxes[i] = new Checkbox("button" + i, cg, i == 0); + p.add(boxes[i]); + } + + add (p, "North"); + + p = new Panel(); + p.setLayout (new GridLayout (1, 3)); + ((GridLayout) p.getLayout ()).setHgap (5); + ((GridLayout) p.getLayout ()).setVgap (5); + + for (int i = 0; i < 3; ++i) + { + final int val = i; + Button tweak = new Button ("Set " + i); + tweak.addActionListener(new ActionListener () + { + public void actionPerformed (ActionEvent e) + { + cg.setSelectedCheckbox(boxes[val]); + } + }); + p.add(tweak); + } + + add (p, "Center"); + + Button cb = new Button ("Close"); + cb.addActionListener(new ActionListener () { + public void actionPerformed (ActionEvent e) { + dispose(); + } + }); + + add (cb, "South"); + setTitle ("Radio Buttons"); + pack(); + } + } + + static class TestWindow extends SubFrame + { + static int xs = 5, ys = 5; + final Frame parent; + + public TestWindow(Frame f) + { + parent = f; + } + + public void init() + { + initted = true; + + addWindowListener (new WindowAdapter () + { + public void windowClosing (WindowEvent e) + { + hide (); + } + }); + + Panel pan = new Panel(); + + final Label l = new Label ("Pithy Message:"); + l.setCursor (Cursor.getPredefinedCursor (Cursor.WAIT_CURSOR)); + pan.add (l); + + TextField tf = new TextField("Hello world!"); + pan.add(tf); + add(pan,"North"); + + final Image img; + URL imageurl; + imageurl = this.getClass() + .getResource("/gnu/classpath/examples/icons/big-warning.png"); + img = Toolkit.getDefaultToolkit().createImage(imageurl); + + final Canvas ch = new Canvas() + { + public void paint (Graphics g) + { + g.drawImage(img, xs + 25, ys + 25, this); + + Font font = new Font ("Serif", Font.PLAIN, 18); + g.setFont (font); + g.setXORMode (Color.red); + + g.drawString("Hi Red!", xs + 15, ys + 10); + g.setColor (Color.blue); + g.drawLine (xs, ys, xs + 100, ys + 100); + + } + }; + ch.setSize(150, 150); + add(ch, "Center"); + + final ScrollPane sp = new ScrollPane(ScrollPane.SCROLLBARS_ALWAYS); + final Panel p = new Panel(); + p.add(new Button("Stop")); + p.add(new Button("evil")); + p.add(new Button("hoarders")); + p.add(new Button("use")); + p.add(new Button("GNU!")); + + sp.add(p); + add(sp, "South"); + + Panel east_panel = new Panel(); + east_panel.setLayout(new GridLayout (0,1)); + + CheckboxGroup group = new CheckboxGroup(); + Checkbox cb = new Checkbox("one", group, true); + east_panel.add(cb); + cb = new Checkbox("two", group, false); + east_panel.add(cb); + + add(east_panel,"East"); + + final Button wb = new Button(); + wb.setLabel("Hello World!"); + wb.addActionListener(new ActionListener() + { + public void actionPerformed (ActionEvent e) + { + l.setText ("Hello World!"); + + final Dialog d = new Dialog(parent); + d.setLayout(new FlowLayout()); + d.setModal(true); + Button b = new Button("foobar"); + b.addMouseListener(new MouseAdapter() + { + public void mousePressed (MouseEvent me) + { + d.hide (); + } + }); + d.add (b); + + List ch = new List(); + ch.add("Ding"); + ch.add("September"); + ch.add("Red"); + ch.add("Quassia"); + ch.add("Pterodactyl"); + d.add(ch); + + d.pack (); + d.show (); + } + }); + + wb.addMouseListener(new MouseAdapter() + { + public void mousePressed(MouseEvent e) { + xs++; + ys++; + ch.repaint (); + } + }); + + add(wb,"West"); + + pack(); + show(); + + sp.setScrollPosition (10,0); + + Toolkit t = Toolkit.getDefaultToolkit(); + t.beep(); + } + } + + static class ResolutionWindow extends SubFrame + { + GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); + + public void init () + { + initted = true; + + setTitle("Change Screen Resolution"); + final List list = new List(); + DisplayMode[] modes = gd.getDisplayModes(); + + for (int i=0;i] [ ...]"); + System.out.println(""); + System.out.println("Options: -i|--iterations= - number of iterations (-1 is infinite; default " + + speed.iterations + ")"); + System.out.println(" -w|--width= - screen width; default " + + DEFAULT_SCREEN_WIDTH); + System.out.println(" -h|--height= - screen height; default " + + DEFAULT_SCREEN_HEIGHT); + System.out.println(" -d|--noDoubleBuffer - disable double-buffering test"); + System.out.println(" -s|--testsize= - size of each test; default " + + DEFAULT_TEST_SIZE); + System.out.println(" -c|--noClipping - disable clipping test"); + System.out.println(" -z|--noZeroClipping - disable clipping to zero test"); + System.out.println(""); + System.out.println("Additional options:"); + System.out.println(" --with-gradients - enable gradients (not compatible with --texture)"); + System.out.println(" --with-stroking - enable random stroking"); + System.out.println(" --texture= - enable texturing with this file (not compatible with --with-gradients)"); + System.out.println(" --composite= - set alpha composite level; -1 for random; default 1.0 (no transparency)"); + System.out.println(" --anti-alias= - set anti-aliasing hint (not all implementations respect this); default off"); + System.out.println(" --x-translate= - set x-axis translation; default 0"); + System.out.println(" --y-translate= - set y-axis translation; default 0"); + System.out.println(" --x-shear= - set x-axis shear; default 0"); + System.out.println(" --y-shear= - set y-axis shear; default 0"); + System.out.println(" --rotate= - set rotation (radians); -1 for random; default: 0 (none)"); + System.out.println(""); + System.out.println("Tests: arc"); + System.out.println(" cubiccurve"); + System.out.println(" ellipse"); + // System.out.println(" generalpath"); + System.out.println(" line"); + System.out.println(" quadcurve"); + System.out.println(" rectangle"); + System.out.println(" roundrectangle"); + System.out.println(" image"); + System.exit(1); + } + else if ((args[i].startsWith("-i=") || args[i].startsWith("--iterations="))) + { + speed.iterations = Integer.parseInt(args[i].substring(args[i].indexOf('=') + 1)); + i += 1; + continue; + } + else if ((args[i].equals("-i") || args[i].equals("--iterations"))) + { + if ((i + 1) >= args.length) + { + System.err.println("ERROR: No argument given for option '" + + args[i] + "'!"); + System.exit(2); + } + speed.iterations = Integer.parseInt(args[i + 1]); + i += 2; + continue; + } + else if ((args[i].startsWith("-w=") || args[i].startsWith("--width="))) + { + speed.screenWidth = Integer.parseInt(args[i].substring(args[i].indexOf('=') + 1)); + i += 1; + continue; + } + else if ((args[i].equals("-w") || args[i].equals("--width"))) + { + if ((i + 1) >= args.length) + { + System.err.println("ERROR: No argument given for option '" + + args[i] + "'!"); + System.exit(2); + } + speed.screenWidth = Integer.parseInt(args[i + 1]); + i += 2; + continue; + } + else if ((args[i].startsWith("-h=") || args[i].startsWith("--height="))) + { + speed.screenHeight = Integer.parseInt(args[i].substring(args[i].indexOf('=') + 1)); + i += 1; + continue; + } + else if ((args[i].equals("-h") || args[i].equals("--height"))) + { + if ((i + 1) >= args.length) + { + System.err.println("ERROR: No argument given for option '" + + args[i] + "'!"); + System.exit(2); + } + speed.screenHeight = Integer.parseInt(args[i + 1]); + i += 2; + continue; + } + else if ((args[i].equals("-d") || args[i].equals("--noDoubleBuffer"))) + { + speed.doubleBufferFlag = false; + i += 1; + continue; + } + else if ((args[i].startsWith("-s=") || args[i].startsWith("--testsize="))) + { + if ((i + 1) >= args.length) + { + System.err.println("ERROR: No argument given for option '" + + args[i] + "'!"); + System.exit(2); + } + speed.testSize = Integer.parseInt(args[i].substring(args[i].indexOf('=') + 1)); + i += 1; + continue; + } + else if ((args[i].equals("-s") || args[i].equals("--testsize"))) + { + if ((i + 1) >= args.length) + { + System.err.println("ERROR: No argument given for option '" + + args[i] + "'!"); + System.exit(2); + } + speed.testSize = Integer.parseInt(args[i + 1]); + i += 2; + continue; + } + else if ((args[i].equals("-c") || args[i].equals("--noClipping"))) + { + speed.noClippingFlag = false; + i += 1; + continue; + } + else if ((args[i].equals("-z") || args[i].equals("--noZeroClipping"))) + { + speed.zeroClippingFlag = false; + i += 1; + continue; + } + else if (args[i].equals("--with-gradients")) + { + speed.gradientFlag = true; + i += 1; + continue; + } + else if (args[i].equals("--with-stroking")) + { + speed.strokeFlag = true; + i += 1; + continue; + } + else if (args[i].startsWith("--texture=")) + { + speed.texture = args[i].substring(args[i].indexOf('=') + 1); + i += 1; + continue; + } + else if (args[i].startsWith("--composite=")) + { + speed.composite = Float.parseFloat(args[i].substring(args[i].indexOf('=') + 1)); + if (speed.composite != - 1 + && (speed.composite < 0 || speed.composite > 1)) + { + System.err.println("ERROR: Invalid value for composite (must be between 0 and 1, or -1 for random)"); + System.exit(2); + } + i += 1; + continue; + } + else if (args[i].startsWith("--anti-alias=")) + { + speed.antialiasFlag = (args[i].substring(args[i].indexOf('=') + 1).equals("on")); + i += 1; + continue; + } + else if (args[i].startsWith("--x-translate=")) + { + speed.xtranslate = Integer.parseInt(args[i].substring(args[i].indexOf('=') + 1)); + i += 1; + continue; + } + else if (args[i].startsWith("--y-translate=")) + { + speed.ytranslate = Integer.parseInt(args[i].substring(args[i].indexOf('=') + 1)); + i += 1; + continue; + } + else if (args[i].startsWith("--x-shear=")) + { + speed.xshear = Double.parseDouble(args[i].substring(args[i].indexOf('=') + 1)); + i += 1; + continue; + } + else if (args[i].startsWith("--y-shear=")) + { + speed.yshear = Double.parseDouble(args[i].substring(args[i].indexOf('=') + 1)); + i += 1; + continue; + } + else if (args[i].startsWith("--rotate=")) + { + speed.rotate = Double.parseDouble(args[i].substring(args[i].indexOf('=') + 1)); + i += 1; + continue; + } + + else if (args[i].equals("--")) + { + endOfOptionsFlag = true; + i += 1; + continue; + } + else if (args[i].startsWith("-")) + { + System.err.println("ERROR: Unknown option '" + args[i] + "'!"); + System.exit(2); + } + } + StringTokenizer tokenizer = new StringTokenizer(args[i], " +,"); + while (tokenizer.hasMoreTokens()) + { + String s = tokenizer.nextToken().toLowerCase(); + if (s.equals("arc")) + awtTests |= J2DTEST_ARC; + else if (s.equals("cubiccurve")) + awtTests |= J2DTEST_CUBICCURVE; + else if (s.equals("ellipse")) + awtTests |= J2DTEST_ELLIPSE; + else if (s.equals("generalpath")) + awtTests |= J2DTEST_GENERALPATH; + else if (s.equals("line")) + awtTests |= J2DTEST_LINE; + else if (s.equals("quadcurve")) + awtTests |= J2DTEST_QUADCURVE; + else if (s.equals("rectangle")) + awtTests |= J2DTEST_RECTANGLE; + else if (s.equals("roundrectangle")) + awtTests |= J2DTEST_ROUNDRECTANGLE; + else if (s.equals("image")) + awtTests |= J2DTEST_IMAGE; + else + { + System.err.println("Unknown AWT test '" + s + "'!"); + System.exit(2); + } + } + i += 1; + } + if (awtTests != J2DTEST_NONE) + speed.awtTests = awtTests; + + // Create graphics. + speed.init(); + final Frame frame = new Frame("J2dGraphicsBenchmark"); + + frame.addWindowListener(new WindowAdapter() + { + public void windowClosing(WindowEvent e) + { + frame.setVisible(false); + System.exit(0); + } + }); + + frame.add(speed, BorderLayout.CENTER); + frame.setSize(speed.screenWidth, speed.screenHeight); + frame.setVisible(true); + + // Insets are correctly set only after the native peer was created. + Insets insets = frame.getInsets(); + // The internal size of the frame should be 320x240. + frame.setSize(320 + insets.right + insets.left, 240 + insets.top + + insets.bottom); + } + + private Image loadImage(String imageName) + { + Image result = null; + logger.logp(Level.INFO, "J2dGraphicsBenchmark", "loadImage", + "Loading image: " + imageName); + URL url = getClass().getResource(imageName); + if (url != null) + { + result = Toolkit.getDefaultToolkit().getImage(url); + prepareImage(result, this); + } + else + { + logger.logp(Level.WARNING, "J2dGraphicsBenchmark", "loadImage", + "Could not locate image resource in class path: " + + imageName); + } + return result; + } + + private BufferedImage loadBufferedImage(String imageName) + { + BufferedImage result = null; + logger.logp(Level.INFO, "J2dGraphicsBenchmark", "loadImage", + "Loading image: " + imageName); + + // Try to load image out of classpath before trying an absolute filename + URL url = getClass().getResource(imageName); + Image img; + if (url != null) + img = Toolkit.getDefaultToolkit().getImage(url); + else + img = Toolkit.getDefaultToolkit().getImage(imageName); + + if (img != null) + { + // Wait for image to load + try + { + MediaTracker tracker = new MediaTracker(this); + tracker.addImage(img, 1); + tracker.waitForAll(); + + prepareImage(img, this); + result = new BufferedImage(img.getWidth(this), img.getHeight(this), + BufferedImage.TYPE_INT_RGB); + result.createGraphics().drawImage(img, 0, 0, this); + } + catch (InterruptedException e) + { + } + catch (IllegalArgumentException e) + { + } + } + + if (result == null) + { + logger.logp(Level.WARNING, "J2dGraphicsBenchmark", "loadBufferedImage", + "Could not locate image resource in class path: " + + imageName); + } + return result; + } + + /** + * Executes the test methods. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + void runTestSet(Graphics2D g, Dimension size) + { + // Any user-specified options (ie set transforms, rendering hints) + prepareGraphics(g); + + if ((awtTests & J2DTEST_ARC) != 0) + { + test_drawArc(g, size); + test_fillArc(g, size); + } + + if ((awtTests & J2DTEST_CUBICCURVE) != 0) + { + test_drawCubicCurve(g, size); + } + + if ((awtTests & J2DTEST_ELLIPSE) != 0) + { + test_drawEllipse(g, size); + test_fillEllipse(g, size); + } + + if ((awtTests & J2DTEST_GENERALPATH) != 0) + { + // Current implementation doesn't work + test_drawGeneralPath(g, size); + test_fillGeneralPath(g, size); + } + + if ((awtTests & J2DTEST_LINE) != 0) + { + test_drawLine(g, size); + } + + if ((awtTests & J2DTEST_QUADCURVE) != 0) + { + test_drawQuadCurve(g, size); + } + + if ((awtTests & J2DTEST_RECTANGLE) != 0) + { + test_drawRectangle(g, size); + test_fillRectangle(g, size); + } + + if ((awtTests & J2DTEST_ROUNDRECTANGLE) != 0) + { + test_drawRoundRectangle(g, size); + test_fillRoundRectangle(g, size); + } + + if ((awtTests & J2DTEST_IMAGE) != 0) + { + test_drawImage(g, size); + test_drawTransparentImage(g, size); + } + } + + /** + * Reset all graphics settings to the standard, default values + * + * @param g the object to apply settings to + */ + private void resetGraphics(Graphics2D g) + { + g.setTransform(new AffineTransform()); + g.setStroke(new BasicStroke()); + g.setComposite(AlphaComposite.SrcOut); + } + + /** + * Sets initial user graphics options + * + * @param g the object to apply settings to + */ + private void prepareGraphics(Graphics2D g) + { + // Transforms + if (affineTransform != null) + g.setTransform(affineTransform); + + else if (xtranslate != 0 || ytranslate != 0 || xshear != 0 || yshear != 0) + { + g.translate(xtranslate, ytranslate); + g.shear(xshear, yshear); + } + + if (rotate > 0) + g.rotate(rotate * Math.PI, screenWidth / 2, screenHeight / 2); + + // Composite (transparency) + if (composite > 0) + { + g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, + composite)); + } + + // Textures + if (texture != null) + g.setPaint(new TexturePaint(textureImage, + new Rectangle(0, 0, textureImage.getWidth(), + textureImage.getHeight()))); + + // Anti-alias setting + if (antialiasFlag) + g.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); + else + g.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_OFF)); + } + + /** + * Gets new random settings + * + * @param g the object to set parameters for + * @param size the screen size + */ + private void setRandom(Graphics2D g, Dimension size) + { + // Set colour / paint + if (gradientFlag) + { + Color c1 = new Color((int) (Math.random() * 254) + 1, + (int) (Math.random() * 254) + 1, + (int) (Math.random() * 254) + 1); + + Color c2 = new Color((int) (Math.random() * 254) + 1, + (int) (Math.random() * 254) + 1, + (int) (Math.random() * 254) + 1); + + g.setPaint(new GradientPaint(0, 0, c1, screenWidth / 5, + screenHeight / 5, c2, true)); + } + + else if (texture == null) + g.setPaint(new Color((int) (Math.random() * 254) + 1, + (int) (Math.random() * 254) + 1, + (int) (Math.random() * 254) + 1)); + + // Set stroke width and options + if (strokeFlag) + { + int cap = (int) (Math.random() * 3 + 1); + if (cap == 1) + cap = BasicStroke.CAP_SQUARE; + else if (cap == 2) + cap = BasicStroke.CAP_BUTT; + else + cap = BasicStroke.CAP_ROUND; + + int join = (int) (Math.random() * 3 + 1); + if (join == 1) + join = BasicStroke.JOIN_MITER; + else if (join == 2) + join = BasicStroke.JOIN_BEVEL; + else + join = BasicStroke.JOIN_ROUND; + + float[] dashes = { 10, 10 }; + g.setStroke(new BasicStroke((int) (Math.random() * 10), cap, join, 10f, + dashes, 0)); + } + + // Composite / transparency + if (composite == - 1) + { + g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, + (float) Math.random())); + } + + // Transformations + if (rotate == - 1) + g.rotate(Math.random() * Math.PI * 2); + } + + /** + * Draws random arcs within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawArc(Graphics2D g, Dimension size) + { + int maxTests = testSize; + int minSize; + long startTime; + long endTime; + minSize = 10; + startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int x = (int) (Math.random() * (size.width - minSize + 1)); + int y = (int) (Math.random() * (size.height - minSize + 1)); + int width = (int) (Math.random() * (size.width - x - minSize) + minSize); + int height = (int) (Math.random() * (size.height - y - minSize) + minSize); + int startAngle = (int) (Math.random() * 360); + int arcAngle = (int) (Math.random() * 360 - startAngle); + + Arc2D arc = new Arc2D.Double(x, y, width, height, startAngle, arcAngle, + Arc2D.OPEN); + g.draw(arc); + } + endTime = System.currentTimeMillis(); + recordTest("draw(Arc2D.Double) " + maxTests + " times", + (endTime - startTime)); + } + + /** + * Draws random filled arcs within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_fillArc(Graphics2D g, Dimension size) + { + int maxTests = testSize; + int minSize; + long startTime; + long endTime; + minSize = 10; + startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int x = (int) (Math.random() * (size.width - minSize + 1)); + int y = (int) (Math.random() * (size.height - minSize + 1)); + int width = (int) (Math.random() * (size.width - x - minSize) + minSize); + int height = (int) (Math.random() * (size.height - y - minSize) + minSize); + int startAngle = (int) (Math.random() * 360); + int arcAngle = (int) (Math.random() * 360); + + Arc2D arc = new Arc2D.Double(x, y, width, height, startAngle, arcAngle, + Arc2D.OPEN); + g.fill(arc); + } + endTime = System.currentTimeMillis(); + recordTest("fill(Arc2D.Double) " + maxTests + " times", + (endTime - startTime)); + } + + /** + * Draws random cubic curves within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawCubicCurve(Graphics2D g, Dimension size) + { + int maxTests = testSize; + int minSize = 10; + long startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int x1 = (int) (Math.random() * (size.width - minSize)); + int y1 = (int) (Math.random() * (size.height - minSize)); + int xc1 = (int) (Math.random() * (size.width - minSize)); + int yc1 = (int) (Math.random() * (size.height - minSize)); + int xc2 = (int) (Math.random() * (size.width - minSize)); + int yc2 = (int) (Math.random() * (size.height - minSize)); + int x2 = (int) (Math.random() * (size.width - minSize)); + int y2 = (int) (Math.random() * (size.height - minSize)); + + CubicCurve2D curve = new CubicCurve2D.Double(x1, y1, xc1, yc1, xc2, + yc2, x2, y2); + g.draw(curve); + } + long endTime = System.currentTimeMillis(); + recordTest("draw(CubicCurve2D.Double) " + maxTests + " times", + (endTime - startTime)); + } + + /** + * Draws random ellipses within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawEllipse(Graphics2D g, Dimension size) + { + int maxTests = testSize; + int minSize = 10; + long startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int x1 = (int) (Math.random() * (size.width - minSize)); + int y1 = (int) (Math.random() * (size.height - minSize)); + int x2 = (int) (Math.random() * (size.width - minSize)); + int y2 = (int) (Math.random() * (size.height - minSize)); + Ellipse2D ellipse = new Ellipse2D.Double(x1, y1, x2, y2); + g.draw(ellipse); + } + long endTime = System.currentTimeMillis(); + recordTest("draw(Ellipse.Double) " + maxTests + " times", + (endTime - startTime)); + } + + /** + * Draws random ellipses within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_fillEllipse(Graphics2D g, Dimension size) + { + int maxTests = testSize; + int minSize = 10; + long startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int x1 = (int) (Math.random() * (size.width - minSize)); + int y1 = (int) (Math.random() * (size.height - minSize)); + int x2 = (int) (Math.random() * (size.width - minSize)); + int y2 = (int) (Math.random() * (size.height - minSize)); + Ellipse2D ellipse = new Ellipse2D.Double(x1, y1, x2, y2); + g.fill(ellipse); + } + long endTime = System.currentTimeMillis(); + recordTest("fill(Ellipse.Double) " + maxTests + " times", + (endTime - startTime)); + } + + // TODO: fix the GeneralPath methods. + /** + * Draws random polygons within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawGeneralPath(Graphics2D g, Dimension size) + { + int maxTests = testSize; + long startTime = System.currentTimeMillis(); + + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int points = (int) (Math.random() * 6) + 2; + GeneralPath shape = new GeneralPath(); + shape.moveTo((float) Math.random() * (size.width), + (float) Math.random() * (size.height)); + for (int j = 0; j < points; j += 1) + { + shape.lineTo((float) (Math.random() * (size.width)), + (float) (Math.random() * (size.height))); + } + g.draw(shape); + } + long endTime = System.currentTimeMillis(); + recordTest("draw(GeneralPath) " + maxTests + " times", + (endTime - startTime)); + } + + /** + * Draws random filled polygons within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_fillGeneralPath(Graphics2D g, Dimension size) + { + int maxTests = testSize; + long startTime = System.currentTimeMillis(); + + GeneralPath shape = new GeneralPath(); + shape.moveTo((float) Math.random() * (size.width), (float) Math.random() + * (size.height)); + + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int points = (int) (Math.random() * 6) + 2; + for (int j = 0; j < points; j += 1) + { + shape.lineTo((float) (Math.random() * (size.width)), + (float) (Math.random() * (size.height))); + } + g.fill(shape); + } + long endTime = System.currentTimeMillis(); + recordTest("fill(GeneralPath) " + maxTests + " times", + (endTime - startTime)); + } + + /** + * Draws random lines within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawLine(Graphics2D g, Dimension size) + { + int maxTests = testSize; + int minSize = 10; + long startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int x1 = (int) (Math.random() * (size.width - minSize)); + int y1 = (int) (Math.random() * (size.height - minSize)); + int x2 = (int) (Math.random() * (size.width - minSize)); + int y2 = (int) (Math.random() * (size.height - minSize)); + Line2D line = new Line2D.Double(x1, y1, x2, y2); + g.draw(line); + } + long endTime = System.currentTimeMillis(); + recordTest("draw(Line2D.Double) " + maxTests + " times", + (endTime - startTime)); + } + + /** + * Draws random quadratic curves within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawQuadCurve(Graphics2D g, Dimension size) + { + int maxTests = testSize; + int minSize = 10; + long startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int x1 = (int) (Math.random() * (size.width - minSize)); + int y1 = (int) (Math.random() * (size.height - minSize)); + int xc = (int) (Math.random() * (size.width - minSize)); + int yc = (int) (Math.random() * (size.height - minSize)); + int x2 = (int) (Math.random() * (size.width - minSize)); + int y2 = (int) (Math.random() * (size.height - minSize)); + + QuadCurve2D curve = new QuadCurve2D.Double(x1, y1, xc, yc, x2, y2); + g.draw(curve); + } + long endTime = System.currentTimeMillis(); + recordTest("draw(QuadCurve2D.Double) " + maxTests + " times", + (endTime - startTime)); + } + + /** + * Draws random rectangles within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawRectangle(Graphics2D g, Dimension size) + { + int maxTests = testSize; + int minSize = 10; + long startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int x1 = (int) (Math.random() * (size.width - minSize)); + int y1 = (int) (Math.random() * (size.height - minSize)); + int x2 = (int) (Math.random() * (size.width - minSize)); + int y2 = (int) (Math.random() * (size.height - minSize)); + Rectangle2D rect = new Rectangle2D.Double(x1, y1, x2, y2); + g.draw(rect); + } + long endTime = System.currentTimeMillis(); + recordTest("draw(Rectangle.Double) " + maxTests + " times", + (endTime - startTime)); + } + + /** + * Draws random rectangles within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_fillRectangle(Graphics2D g, Dimension size) + { + int maxTests = testSize; + int minSize = 10; + long startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int x1 = (int) (Math.random() * (size.width - minSize)); + int y1 = (int) (Math.random() * (size.height - minSize)); + int x2 = (int) (Math.random() * (size.width - minSize)); + int y2 = (int) (Math.random() * (size.height - minSize)); + Rectangle2D rect = new Rectangle2D.Double(x1, y1, x2, y2); + g.fill(rect); + } + long endTime = System.currentTimeMillis(); + recordTest("fill(Rectangle.Double) " + maxTests + " times", + (endTime - startTime)); + } + + /** + * Draws random rounded rectangles within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawRoundRectangle(Graphics2D g, Dimension size) + { + int maxTests = testSize; + int minSize; + long startTime; + long endTime; + minSize = 10; + startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int x = (int) (Math.random() * (size.width - minSize + 1)); + int y = (int) (Math.random() * (size.height - minSize + 1)); + int width = (int) (Math.random() * (size.width - x - minSize) + minSize); + int height = (int) (Math.random() * (size.height - y - minSize) + minSize); + int arcWidth = (int) (Math.random() * (width - 1) + 1); + int arcHeight = (int) (Math.random() * (height - 1) + 5); + RoundRectangle2D rect = new RoundRectangle2D.Double(x, y, width, + height, arcWidth, + arcHeight); + g.draw(rect); + } + endTime = System.currentTimeMillis(); + recordTest("draw(RoundRectangle.Double) " + maxTests + " times", + (endTime - startTime)); + } + + /** + * Draws random filled rounded rectangles within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_fillRoundRectangle(Graphics2D g, Dimension size) + { + int maxTests = testSize; + int minSize; + long startTime; + long endTime; + minSize = 10; + startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int x = (int) (Math.random() * (size.width - minSize + 1)); + int y = (int) (Math.random() * (size.height - minSize + 1)); + int width = (int) (Math.random() * (size.width - x - minSize) + minSize); + int height = (int) (Math.random() * (size.height - y - minSize) + minSize); + int arcWidth = (int) (Math.random() * (width - 1) + 1); + int arcHeight = (int) (Math.random() * (height - 1) + 5); + RoundRectangle2D rect = new RoundRectangle2D.Double(x, y, width, + height, arcWidth, + arcHeight); + g.fill(rect); + } + endTime = System.currentTimeMillis(); + recordTest("fill(RoundRectangle.Double) " + maxTests + " times", + (endTime - startTime)); + } + + /** + * Draws random images within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawImage(Graphics2D g, Dimension size) + { + if (gifTestImage == null) + { + logger.logp(Level.WARNING, "J2dGraphicsBenchmark", "runTestSet", + "Skipping 'test_drawImage' due to missing resource."); + return; + } + + int maxTests = testSize / 2; + if (maxTests == 0) + maxTests = 1; + int imageWidth = gifTestImage.getWidth(this); + int imageHeight = gifTestImage.getHeight(this); + long startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int x = (int) (Math.random() * (size.width - imageWidth + 1)); + int y = (int) (Math.random() * (size.height - imageHeight + 1)); + g.drawImage(gifTestImage, x, y, this); + } + long endTime = System.currentTimeMillis(); + recordTest("drawImage " + maxTests + " times", (endTime - startTime)); + } + + /** + * Draws random transparent images within the given dimensions. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawTransparentImage(Graphics2D g, Dimension size) + { + if (pngTestImage == null) + { + logger.logp(Level.WARNING, "AicasGraphicsBenchmark", "runTestSet", + "Skipping 'drawTransparentImage' due to missing resource."); + return; + } + + int maxTests = testSize / 5; + if (maxTests == 0) + maxTests = 1; + int imageWidth = pngTestImage.getWidth(this); + int imageHeight = pngTestImage.getHeight(this); + long startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int x = (int) (Math.random() * (size.width - imageWidth + 1)); + int y = (int) (Math.random() * (size.height - imageHeight + 1)); + g.drawImage(pngTestImage, x, y, this); + } + long endTime = System.currentTimeMillis(); + recordTest("draw transparent image " + maxTests + " times", + (endTime - startTime)); + } + + private class GraphicsTest + extends Canvas + implements Runnable + { + Thread paintThread; + + boolean done = false; + + boolean doPaint = false; + + boolean withClipping = false; + + public GraphicsTest() + { + paintThread = new Thread(this); + paintThread.start(); + } + + public void run() + { + int runCount = 0; + while (! done) + { + runCount++; + + try + { + synchronized (this) + { + while (! doPaint) + { + try + { + wait(200); + } + catch (InterruptedException exception) + { + return; + } + } + } + + // if (iterations != 0) + // System.out.println("--- run...(" + // + runCount + // + "/" + // + iterations + // + ") ------------------------------------------------------"); + + Graphics g = getGraphics(); + Dimension size = getSize(); + + if (singleBufferFlag) + { + logger.logp(Level.INFO, "J2dGraphicsBenchmark.GraphicsTest", + "run", + "Start testing non-double-buffered drawing"); + + if (noClippingFlag) + runSet_noClipping((Graphics2D) g, size, runCount); + + if (withClippingFlag) + runSet_withClipping((Graphics2D) g, size, runCount); + + if (zeroClippingFlag) + runSet_zeroClipping((Graphics2D) g, size, runCount); + + g.dispose(); + } + + if (doubleBufferFlag) + { + logger.logp(Level.INFO, "J2dGraphicsBenchmark.GraphicsTest", + "run", "Start testing double-buffered drawing"); + Graphics canvas = getGraphics(); + Image doublebuffer = createImage(size.width, size.height); + + if (noClippingFlag) + { + g = doublebuffer.getGraphics(); + runSet_noClipping((Graphics2D) g, size, + "double buffering", runCount); + g.dispose(); + canvas.drawImage(doublebuffer, 0, 0, this); + } + + if (withClippingFlag) + { + g = doublebuffer.getGraphics(); + runSet_withClipping((Graphics2D) g, size, + "double buffering", runCount); + g.dispose(); + canvas.drawImage(doublebuffer, 0, 0, this); + } + + if (zeroClippingFlag) + { + g = doublebuffer.getGraphics(); + runSet_zeroClipping((Graphics2D) g, size, + "double buffering", runCount); + g.dispose(); + canvas.drawImage(doublebuffer, 0, 0, this); + canvas.dispose(); + } + } + + printReport(); + + if (iterations != 1) + { + if (iterations != - 1) + iterations--; + } + else + { + // System.out.println("--- done + // --------------------------------------------------------"); + synchronized (this) + { + doPaint = false; + } + done = true; + } + } + catch (Error error) + { + System.err.println("Error: " + error); + System.exit(129); + } + } + testComplete(); + } + + private void runSet_zeroClipping(Graphics2D g, Dimension size, int runCount) + { + runSet_zeroClipping(g, size, "", runCount); + } + + private void runSet_zeroClipping(Graphics2D g, Dimension size, + String context, int runCount) + { + int clipped_width; + int clipped_height; + int clipped_x; + int clipped_y; + + clipped_width = 0; + clipped_height = 0; + clipped_x = (size.width) / 2; + clipped_y = (size.height) / 2; + + // Reset any transforms from past tests + resetGraphics(g); + + Rectangle fullWindow = new Rectangle(0, 0, size.width, size.height); + g.setClip(fullWindow); + g.setPaint(Color.BLACK); + g.fill(fullWindow); + + Rectangle windowBorder = new Rectangle(0, 0, size.width - 1, + size.width - 1); + g.setPaint(Color.WHITE); + g.draw(windowBorder); + + Rectangle innerBorder = new Rectangle(clipped_x - 1, clipped_y - 1, + clipped_width + 2, + clipped_height + 2); + g.fill(innerBorder); + + Rectangle innerBox = new Rectangle(clipped_x, clipped_y, clipped_width, + clipped_height); + g.clip(innerBox); + g.setPaint(Color.BLACK); + g.fill(fullWindow); + + if (context.equals("")) + setTestContext("(" + runCount + ") clipping to zero"); + else + setTestContext("(" + runCount + ") clipping to zero (" + context + ")"); + + runTestSet(g, size); + } + + private void runSet_withClipping(Graphics2D g, Dimension size, int runCount) + { + runSet_withClipping(g, size, "", runCount); + } + + private void runSet_withClipping(Graphics2D g, Dimension size, + String context, int runCount) + { + int clipped_width = 2 * size.width / 3; + int clipped_height = 2 * size.height / 3; + int clipped_x = (size.width - clipped_width) / 2; + int clipped_y = (size.height - clipped_height) / 2; + + // Reset any transforms from past tests + resetGraphics(g); + + Rectangle fullWindow = new Rectangle(0, 0, size.width, size.height); + g.setClip(fullWindow); + + g.setPaint(Color.BLACK); + g.fill(fullWindow); + + Rectangle windowBorder = new Rectangle(0, 0, size.width - 1, + size.height - 1); + g.setPaint(Color.GREEN); + g.draw(windowBorder); + + Rectangle innerBorder = new Rectangle(clipped_x - 1, clipped_y - 1, + clipped_width + 2, + clipped_height + 2); + g.setPaint(Color.WHITE); + g.fill(innerBorder); + + Rectangle innerBox = new Rectangle(clipped_x, clipped_y, clipped_width, + clipped_height); + g.clip(innerBox); + + g.setPaint(Color.BLACK); + g.fill(fullWindow); + + if (context.equals("")) + setTestContext("(" + runCount + ") with clipping "); + else + setTestContext("(" + runCount + ") with clipping (" + context + ")"); + + runTestSet(g, size); + } + + private void runSet_noClipping(Graphics2D g, Dimension size, int runCount) + { + runSet_noClipping(g, size, "", runCount); + } + + private void runSet_noClipping(Graphics2D g, Dimension size, + String context, int runCount) + { + // Reset any transforms from past tests + resetGraphics(g); + + Rectangle fullWindow = new Rectangle(0, 0, size.width, size.height); + g.setPaint(Color.BLACK); + g.fill(fullWindow); + + if (context.equals("")) + setTestContext("(" + runCount + ") without clipping"); + else + setTestContext("(" + runCount + ") without clipping (" + context + ")"); + + runTestSet(g, size); + } + + public void paint(Graphics g) + { + synchronized (this) + { + doPaint = true; + notify(); + } + } + } +} + +class TestContext +{ +} + +class TestSet +{ + private Map testsMap = new TreeMap(); + + public void putTest(String testName, TestRecorder recoder) + { + testsMap.put(testName, recoder); + } + + public TestRecorder getTest(String testName) + { + return (TestRecorder) testsMap.get(testName); + } + + public Iterator testIterator() + { + return testsMap.keySet().iterator(); + } +} + +class TestRecorder +{ + String test; + + long totalTime = 0; + + long minTime = Long.MAX_VALUE; + + long maxTime = Long.MIN_VALUE; + + int runCount = 0; + + /** + * @return Returns the maxTime. + */ + public final long getMaxTime() + { + return maxTime; + } + + /** + * @return Returns the minTime. + */ + public final long getMinTime() + { + return minTime; + } + + /** + * @return Returns the test name. + */ + public final String getTestName() + { + return test; + } + + public final long getAverage() + { + return (totalTime / runCount); + } + + public TestRecorder(String testName) + { + test = testName; + } + + public void addRun(long time) + { + totalTime += time; + if (minTime > time) + minTime = time; + if (maxTime < time) + maxTime = time; + runCount += 1; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/java2d/J2dBenchmarkGUI.java b/libjava/classpath/examples/gnu/classpath/examples/java2d/J2dBenchmarkGUI.java new file mode 100644 index 000000000..ce12fa1f7 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/java2d/J2dBenchmarkGUI.java @@ -0,0 +1,891 @@ +/* J2dBenchmarkGUI.java -- GUI for java2d benchmarker + Copyright (C) 2006 Free Software Foundation, Inc. + + This file is part of GNU Classpath. + + GNU Classpath is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + GNU Classpath is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. + + Linking this library statically or dynamically with other modules is + making a combined work based on this library. Thus, the terms and + conditions of the GNU General Public License cover the whole + combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent + modules, and to copy and distribute the resulting executable under + terms of your choice, provided that you also meet, for each linked + independent module, the terms and conditions of the license of that + module. An independent module is a module which is not derived from + or based on this library. If you modify this library, you may extend + this exception to your version of the library, but you are not + obligated to do so. If you do not wish to do so, delete this + exception statement from your version. */ + +package gnu.classpath.examples.java2d; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Container; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.GridLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.ArrayList; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogRecord; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.JTextField; +import javax.swing.border.BevelBorder; + +/** + * Extends the J2dBenchmark to provide a GUI for selecting options and tests. + */ +public class J2dBenchmarkGUI + implements ActionListener +{ + + JLabel errorLabel; + + JCheckBox noClipping; + + JCheckBox withClipping; + + JCheckBox zeroClipping; + + JCheckBox singleBuffer; + + JCheckBox doubleBuffer; + + public J2dBenchmarkGUI() + { + super(); + } + + public static void main(String[] args) + { + new J2dBenchmarkGUI().run(); + } + + /** + * Sets up the initial GUI + */ + public void run() + { + // Store all elements in a hashtable so that they can be passed into the + // harness easily. + Hashtable elements = new Hashtable(); + + // Set up frame + final JFrame frame = new JFrame("Java2D benchmark"); + errorLabel = new JLabel(" "); + + JPanel panel = new JPanel(); + panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); + Container content = frame.getContentPane(); + + // Display options for dimensions, iterations, test size, etc + JPanel options = new JPanel(new GridLayout(0, 2)); + + options.add(new JLabel("Height: ")); + JTextField heightField = new JTextField(Integer.toString(J2dBenchmark.DEFAULT_SCREEN_HEIGHT)); + heightField.setColumns(5); + options.add(heightField); + elements.put("height", heightField); + + options.add(new JLabel("Width: ")); + JTextField widthField = new JTextField(Integer.toString(J2dBenchmark.DEFAULT_SCREEN_WIDTH)); + widthField.setColumns(5); + options.add(widthField); + elements.put("width", widthField); + + options.add(new JLabel("Iterations: ")); + JTextField iterField = new JTextField("1"); + iterField.setColumns(5); + options.add(iterField); + elements.put("iterations", iterField); + + options.add(new JLabel("Test size: ")); + JTextField testSizeField = new JTextField(Integer.toString(J2dBenchmark.DEFAULT_TEST_SIZE)); + testSizeField.setColumns(5); + options.add(testSizeField); + elements.put("size", testSizeField); + + options.add(new JLabel("Test without clipping: ")); + noClipping = new JCheckBox("", true); + noClipping.addActionListener(this); + options.add(noClipping); + elements.put("noclip", noClipping); + + options.add(new JLabel("Test with clipping: ")); + withClipping = new JCheckBox("", true); + withClipping.addActionListener(this); + options.add(withClipping); + elements.put("withclip", withClipping); + + options.add(new JLabel("Test with clipping to zero: ")); + zeroClipping = new JCheckBox("", true); + zeroClipping.addActionListener(this); + options.add(zeroClipping); + elements.put("zeroclip", zeroClipping); + + options.add(new JLabel("Run single-buffer test: ")); + singleBuffer = new JCheckBox("", true); + singleBuffer.addActionListener(this); + options.add(singleBuffer); + elements.put("singlebuffer", singleBuffer); + + options.add(new JLabel("Run double-buffer test: ")); + doubleBuffer = new JCheckBox("", true); + doubleBuffer.addActionListener(this); + options.add(doubleBuffer); + elements.put("doublebuffer", doubleBuffer); + + // Allow user to select tests to run + JPanel tests = new JPanel(); + tests.setLayout(new BoxLayout(tests, BoxLayout.PAGE_AXIS)); + tests.setBorder(new BevelBorder(BevelBorder.RAISED)); + tests.add(new JLabel("Shapes to test:")); + + JCheckBox test_arcDraw = new JCheckBox("Arc", true); + tests.add(test_arcDraw); + elements.put("test_arcDraw", test_arcDraw); + + JCheckBox test_ccurveDraw = new JCheckBox("Cubic Curve", true); + tests.add(test_ccurveDraw); + elements.put("test_ccurveDraw", test_ccurveDraw); + + JCheckBox test_ellipseDraw = new JCheckBox("Ellipse", true); + tests.add(test_ellipseDraw); + elements.put("test_ellipseDraw", test_ellipseDraw); + + /* + JCheckBox test_pathDraw = new JCheckBox("General Path", true); + tests.add(test_pathDraw); + elements.put("test_pathDraw", test_pathDraw); + */ + + JCheckBox test_lineDraw = new JCheckBox("Line", true); + tests.add(test_lineDraw); + elements.put("test_lineDraw", test_lineDraw); + + JCheckBox test_qcurveDraw = new JCheckBox("Quadratic Curve", true); + tests.add(test_qcurveDraw); + elements.put("test_qcurveDraw", test_qcurveDraw); + + JCheckBox test_rectDraw = new JCheckBox("Rectangle", true); + tests.add(test_rectDraw); + elements.put("test_rectDraw", test_rectDraw); + + JCheckBox test_rrectDraw = new JCheckBox("Round Rectangle", true); + tests.add(test_rrectDraw); + elements.put("test_rrectDraw", test_rrectDraw); + + JCheckBox test_image = new JCheckBox("Images", true); + tests.add(test_image); + elements.put("test_image", test_image); + + // Additional image-processing options + JPanel extras = new JPanel(); + extras.setBorder(new BevelBorder(BevelBorder.LOWERED)); + GridBagLayout layout = new GridBagLayout(); + GridBagConstraints gbc = new GridBagConstraints(); + gbc.anchor = GridBagConstraints.NORTHWEST; + gbc.insets = new Insets(5, 2, 15, 15); + extras.setLayout(layout); + + // Filling (solid, gradient, or texture) + JPanel opt_Fill = new JPanel(); + opt_Fill.setLayout(new BoxLayout(opt_Fill, BoxLayout.PAGE_AXIS)); + JLabel opt_FillLabel = new JLabel("Filling:"); + opt_FillLabel.setBorder(new BevelBorder(BevelBorder.RAISED)); + opt_Fill.add(opt_FillLabel); + + ButtonGroup opt_FillGroup = new ButtonGroup(); + JRadioButton opt_FillSolid = new JRadioButton("Solid colour", true); + opt_FillSolid.setActionCommand("solid"); + opt_Fill.add(opt_FillSolid); + opt_FillGroup.add(opt_FillSolid); + JRadioButton opt_FillGradient = new JRadioButton("Gradient", false); + opt_FillGradient.setActionCommand("gradient"); + opt_Fill.add(opt_FillGradient); + opt_FillGroup.add(opt_FillGradient); + JRadioButton opt_FillTexture = new JRadioButton("Texture", false); + opt_FillTexture.setActionCommand("texture"); + opt_Fill.add(opt_FillTexture); + opt_FillGroup.add(opt_FillTexture); + JTextField opt_FillTextureFile = new JTextField("texture file"); + opt_FillTextureFile.setAlignmentX(JComponent.LEFT_ALIGNMENT); + opt_Fill.add(opt_FillTextureFile); + elements.put("opt_FillGroup", opt_FillGroup); + elements.put("opt_FillTextureFile", opt_FillTextureFile); + layout.setConstraints(opt_Fill, gbc); + extras.add(opt_Fill); + + // Stroke + JPanel opt_Stroke = new JPanel(); + opt_Stroke.setLayout(new BoxLayout(opt_Stroke, BoxLayout.PAGE_AXIS)); + JLabel opt_StrokeLabel = new JLabel("Stroke:"); + opt_StrokeLabel.setBorder(new BevelBorder(BevelBorder.RAISED)); + opt_Stroke.add(opt_StrokeLabel); + JCheckBox opt_StrokeRandom = new JCheckBox("random", false); + elements.put("opt_StrokeRandom", opt_StrokeRandom); + opt_Stroke.add(opt_StrokeRandom); + gbc.gridwidth = GridBagConstraints.REMAINDER; + layout.setConstraints(opt_Stroke, gbc); + extras.add(opt_Stroke); + + // Anti-Alias + JPanel opt_Alias = new JPanel(); + opt_Alias.setLayout(new BoxLayout(opt_Alias, BoxLayout.PAGE_AXIS)); + JLabel opt_AliasLabel = new JLabel("Anti-Aliasing:"); + opt_AliasLabel.setBorder(new BevelBorder(BevelBorder.RAISED)); + opt_Alias.add(opt_AliasLabel); + JCheckBox opt_AliasOn = new JCheckBox("on", false); + elements.put("opt_AliasOn", opt_AliasOn); + opt_Alias.add(opt_AliasOn); + gbc.gridwidth = 1; + layout.setConstraints(opt_Alias, gbc); + extras.add(opt_Alias); + + // Alpha composite + JPanel opt_Composite = new JPanel(); + opt_Composite.setLayout(new BoxLayout(opt_Composite, BoxLayout.PAGE_AXIS)); + JLabel opt_CompositeLabel = new JLabel("Alpha Composite:"); + opt_CompositeLabel.setBorder(new BevelBorder(BevelBorder.RAISED)); + opt_Composite.add(opt_CompositeLabel); + JTextField opt_CompositeValue = new JTextField("1.0"); + opt_CompositeValue.setAlignmentX(JComponent.LEFT_ALIGNMENT); + elements.put("opt_CompositeValue", opt_CompositeValue); + opt_Composite.add(opt_CompositeValue); + gbc.gridwidth = GridBagConstraints.REMAINDER; + layout.setConstraints(opt_Composite, gbc); + extras.add(opt_Composite); + + // Transformations + // TODO: allow user-defined matrices for AffineTransform + // (backend already has hooks for it, need to create gui) + JLabel opt_TransformLabel = new JLabel("Transformations:"); + opt_TransformLabel.setBorder(new BevelBorder(BevelBorder.RAISED)); + gbc.insets = new Insets(5, 2, 0, 15); + layout.setConstraints(opt_TransformLabel, gbc); + extras.add(opt_TransformLabel); + + JPanel opt_Transform_Translate = new JPanel(new GridLayout(0, 2, 5, 5)); + opt_Transform_Translate.add(new JLabel("x-axis translation ")); + JTextField opt_TransformTranslateX = new JTextField("0"); + opt_TransformTranslateX.setAlignmentX(JComponent.LEFT_ALIGNMENT); + opt_Transform_Translate.add(opt_TransformTranslateX); + elements.put("opt_TransformTranslateX", opt_TransformTranslateX); + opt_Transform_Translate.add(new JLabel("y-axis translation ")); + JTextField opt_TransformTranslateY = new JTextField("0"); + opt_TransformTranslateY.setAlignmentX(JComponent.LEFT_ALIGNMENT); + opt_Transform_Translate.add(opt_TransformTranslateY); + elements.put("opt_TransformTranslateY", opt_TransformTranslateY); + gbc.gridwidth = 1; + gbc.insets = new Insets(0, 2, 5, 15); + layout.setConstraints(opt_Transform_Translate, gbc); + extras.add(opt_Transform_Translate); + + JPanel opt_Transform_Shear = new JPanel(new GridLayout(0, 2, 5, 5)); + opt_Transform_Shear.add(new JLabel("x-axis shear ")); + JTextField opt_TransformShearX = new JTextField("0"); + opt_TransformShearX.setAlignmentX(JComponent.LEFT_ALIGNMENT); + opt_Transform_Shear.add(opt_TransformShearX); + elements.put("opt_TransformShearX", opt_TransformShearX); + opt_Transform_Shear.add(new JLabel("y-axis shear ")); + JTextField opt_TransformShearY = new JTextField("0"); + opt_Transform_Shear.add(opt_TransformShearY); + elements.put("opt_TransformShearY", opt_TransformShearY); + gbc.gridwidth = GridBagConstraints.REMAINDER; + layout.setConstraints(opt_Transform_Shear, gbc); + extras.add(opt_Transform_Shear); + + JPanel opt_Transform_Rotate = new JPanel(new GridLayout(0, 2, 5, 5)); + opt_Transform_Rotate.add(new JLabel("rotation (radians) ")); + JTextField opt_TransformRotate = new JTextField("0"); + opt_Transform_Rotate.add(opt_TransformRotate); + elements.put("opt_TransformRotate", opt_TransformRotate); + layout.setConstraints(opt_Transform_Rotate, gbc); + extras.add(opt_Transform_Rotate); + + // Final submit button + JPanel submit = new JPanel(); + submit.setLayout(new BoxLayout(submit, BoxLayout.PAGE_AXIS)); + + JButton rectButton = new JButton("Run benchmark"); + rectButton.setAlignmentX(JComponent.CENTER_ALIGNMENT); + submit.add(rectButton, BorderLayout.CENTER); + + errorLabel.setAlignmentX(JComponent.CENTER_ALIGNMENT); + errorLabel.setForeground(Color.RED); + submit.add(errorLabel); + + rectButton.addActionListener(new Harness(elements, errorLabel)); + + // Lay it all out + JPanel body = new JPanel(); + body.setLayout(new BoxLayout(body, BoxLayout.LINE_AXIS)); + options.setAlignmentX(JComponent.LEFT_ALIGNMENT); + body.add(options); + body.add(Box.createHorizontalStrut(50)); + tests.setAlignmentX(JComponent.RIGHT_ALIGNMENT); + body.add(tests); + + body.setAlignmentX(JComponent.CENTER_ALIGNMENT); + panel.add(body); + extras.setAlignmentX(JComponent.CENTER_ALIGNMENT); + panel.add(extras); + submit.setAlignmentX(JComponent.CENTER_ALIGNMENT); + panel.add(submit); + + content.add(panel, BorderLayout.CENTER); + + // Leave some breathing space in the frame + frame.pack(); + + frame.addWindowListener(new WindowAdapter() + { + public void windowClosing(WindowEvent e) + { + frame.setVisible(false); + System.exit(0); + } + }); + + frame.show(); + } + + /** + * Handles user events on the options GUI, ensuring that user input is valid + */ + public void actionPerformed(ActionEvent ev) + { + if (! noClipping.isSelected() && ! withClipping.isSelected() + && ! zeroClipping.isSelected()) + errorLabel.setText("You must select at least one clipping option"); + + else if (! singleBuffer.isSelected() && ! doubleBuffer.isSelected()) + errorLabel.setText("You must select at least one buffering option"); + + else + errorLabel.setText(" "); + } + + /** + * Parses GUI input and sets options in the benchmarker + */ + private class Harness + implements ActionListener + { + Hashtable elements; + + JLabel errorLabel; + + /** + * Creates a new Harness object + * + * @param elements Hashtable containing the swing elements from the GUI + * @param errorLabel JLabel on which to display any error messages + */ + public Harness(Hashtable elements, JLabel errorLabel) + { + super(); + + this.elements = elements; + this.errorLabel = errorLabel; + } + + /** + * Handles user button-clicks, parsing the form, setting options, and + * starting the J2dBenchmark + * + * @param ae event that triggered this action + */ + public void actionPerformed(ActionEvent ae) + { + try + { + // Create benchmarker object + final JFrame frame = new JFrame("Java2D benchmark"); + J2dBenchmarkWrapper speed = new J2dBenchmarkWrapper(frame); + + // Set options + speed.setDimensions(Integer.parseInt(((JTextField) elements.get("width")).getText()), + Integer.parseInt(((JTextField) elements.get("height")).getText())); + + speed.setIterations(Integer.parseInt(((JTextField) elements.get("iterations")).getText())); + speed.setTestSize(Integer.parseInt(((JTextField) elements.get("size")).getText())); + + speed.setClipping(((JCheckBox) elements.get("noclip")).isSelected(), + ((JCheckBox) elements.get("withclip")).isSelected(), + ((JCheckBox) elements.get("zeroclip")).isSelected()); + + speed.setBuffers(((JCheckBox) elements.get("singlebuffer")).isSelected(), + ((JCheckBox) elements.get("doublebuffer")).isSelected()); + + // Set additional processing options + speed.setFill(((ButtonGroup) elements.get("opt_FillGroup")).getSelection().getActionCommand(), + ((JTextField) elements.get("opt_FillTextureFile")).getText()); + + speed.setStroke(((JCheckBox) elements.get("opt_StrokeRandom")).isSelected()); + + speed.setAlias(((JCheckBox) elements.get("opt_AliasOn")).isSelected()); + + speed.setComposite(Float.parseFloat(((JTextField) elements.get("opt_CompositeValue")).getText())); + + speed.setTranslation(Integer.parseInt(((JTextField) elements.get("opt_TransformTranslateX")).getText()), + Integer.parseInt(((JTextField) elements.get("opt_TransformTranslateY")).getText())); + + speed.setRotation(Double.parseDouble(((JTextField) elements.get("opt_TransformRotate")).getText())); + + speed.setShear(Double.parseDouble(((JTextField) elements.get("opt_TransformShearX")).getText()), + Double.parseDouble(((JTextField) elements.get("opt_TransformShearY")).getText())); + + // Set tests + int testSuite = 0; + if (((JCheckBox) elements.get("test_arcDraw")).isSelected()) + testSuite |= J2dBenchmarkWrapper.J2DTEST_ARC; + if (((JCheckBox) elements.get("test_ccurveDraw")).isSelected()) + testSuite |= J2dBenchmarkWrapper.J2DTEST_CUBICCURVE; + if (((JCheckBox) elements.get("test_ellipseDraw")).isSelected()) + testSuite |= J2dBenchmarkWrapper.J2DTEST_ELLIPSE; + //if (((JCheckBox)elements.get("test_pathDraw")).isSelected()) + // testSuite |= J2dBenchmarkWrapper.J2DTEST_GENERALPATH; + if (((JCheckBox) elements.get("test_lineDraw")).isSelected()) + testSuite |= J2dBenchmarkWrapper.J2DTEST_LINE; + if (((JCheckBox) elements.get("test_qcurveDraw")).isSelected()) + testSuite |= J2dBenchmarkWrapper.J2DTEST_QUADCURVE; + if (((JCheckBox) elements.get("test_rectDraw")).isSelected()) + testSuite |= J2dBenchmarkWrapper.J2DTEST_RECTANGLE; + if (((JCheckBox) elements.get("test_rrectDraw")).isSelected()) + testSuite |= J2dBenchmarkWrapper.J2DTEST_ROUNDRECTANGLE; + if (((JCheckBox) elements.get("test_image")).isSelected()) + testSuite |= J2dBenchmarkWrapper.J2DTEST_IMAGE; + + if (testSuite != 0) + { + speed.setTests(testSuite); + + String initResult = speed.init(); + + if (initResult == null) + { + // Create graphics. + frame.add(speed, BorderLayout.CENTER); + frame.setSize( + Integer.parseInt(((JTextField) elements.get("width")).getText()), + Integer.parseInt(((JTextField) elements.get("height")).getText())); + frame.setVisible(true); + + // Insets are correctly set only after the native peer was + // created. + Insets insets = frame.getInsets(); + frame.setSize(frame.getWidth() + insets.right + insets.left, + frame.getHeight() + insets.top + insets.bottom); + + // Clear any old error messages + errorLabel.setText(" "); + } + else + errorLabel.setText(initResult); + } + else + errorLabel.setText("Please select at least one test."); + } + catch (NumberFormatException e) + { + errorLabel.setText("Please enter valid integers"); + } + } + } + + /** + * Wrapper for the J2dBenchmark, which outputs the results to a GUI + * instead of the command-line + */ + private class J2dBenchmarkWrapper + extends J2dBenchmark + { + JFrame myFrame; + + ResultsDisplay display; + + /** + * Create new J2dBenchmarkWrapper object + * + * @param frame parent frame + */ + public J2dBenchmarkWrapper(JFrame frame) + { + // Redirect log messages to the custom handler + logger.setUseParentHandlers(false); + display = new ResultsDisplay(); + display.setLevel(Level.INFO); + logger.addHandler(display); + + myFrame = frame; + } + + /** + * Set dimensions of benchmarking canvas + * + * @param width width of canvas + * @param height height of canvas + */ + public void setDimensions(int width, int height) + { + screenHeight = height; + screenWidth = width; + setSize(width, height); + } + + /** + * Set number of iterations + * + * @param it number of iterations + */ + public void setIterations(int it) + { + iterations = it; + } + + /** + * Set size of each test + * + * @param size size of test + */ + public void setTestSize(int size) + { + testSize = size; + } + + /** + * Set clipping options + * + * @param no run test with no clipping + * @param with run test with clipping + * @param zero run test with clipping to zero + */ + public void setClipping(boolean no, boolean with, boolean zero) + { + this.noClippingFlag = no; + this.withClippingFlag = with; + this.zeroClippingFlag = zero; + } + + /** + * Set buffering options + * + * @param single run test without double-buffering + * @param doubleb run test with double-buffering + */ + public void setBuffers(boolean single, boolean doubleb) + { + this.singleBufferFlag = single; + this.doubleBufferFlag = doubleb; + } + + /** + * Set fill options + * + * @param type fill type: "solid", "gradient", or "texture" + * @param file filename to use if texturing + */ + public void setFill(String type, String file) + { + if (type.equals("gradient")) + this.gradientFlag = true; + else if (type.equals("texture")) + { + this.texture = file; + } + } + + /** + * Set stroke options + * + * @param stroke boolean flag to use random stroking or not + */ + public void setStroke(boolean stroke) + { + this.strokeFlag = stroke; + } + + /** + * Set anti-aliasing options + * + * @param alias boolean flag to use anti-aliasing or not + */ + public void setAlias(boolean alias) + { + this.antialiasFlag = alias; + } + + /** + * Set alpha composite + * + * @param alpha alpha composite + */ + public void setComposite(float alpha) + { + this.composite = alpha; + } + + /** + * Set translation values + * + * @param x x-axis translation + * @param y y-axis translation + */ + public void setTranslation(int x, int y) + { + this.xtranslate = x; + this.ytranslate = y; + } + + /** + * Set rotation + * + * @param theta angle to rotate by (radians) + */ + public void setRotation(double theta) + { + this.rotate = theta; + } + + /** + * Set shear values + * + * @param x x-axis shear value + * @param y-axis shear value + */ + public void setShear(double x, double y) + { + this.xshear = x; + this.yshear = y; + } + + /** + * Set tests to run + * + * @param tests bit-shifted list of tests (see J2dBenchmark constants) + */ + public void setTests(int tests) + { + awtTests = tests; + } + + /** + * Saves test report after each iteration + */ + void printReport() + { + // Report test results to the GUI display + ArrayList results = new ArrayList(); + for (Iterator i = testSetMap.testIterator(); i.hasNext();) + { + TestRecorder recorder = testSetMap.getTest((String) i.next()); + + results.add("TEST " + recorder.getTestName() + ": average " + + recorder.getAverage() + "ms [" + recorder.getMinTime() + + "-" + recorder.getMaxTime() + "]"); + } + + display.report(results); + } + + /** + * Disables current frame and displays test results + */ + void testComplete() + { + // Clear benchmarking canvas and display results instead + myFrame.setVisible(false); + + display.show(); + } + } + + /** + * GUI to display results of benchmarking + */ + private class ResultsDisplay + extends Handler + implements ActionListener + { + /** + * Allow user to select results from each iteration + */ + JComboBox iterations; + + /** + * Area to print results in + */ + JTextArea results; + + /** + * Allow user to view summary or full details of test report + */ + JCheckBox details; + + /** + * Store all test results + */ + ArrayList testResults; + + /** + * Store all test details + */ + ArrayList testDetails; + + /** + * Initialize variables + */ + public ResultsDisplay() + { + testResults = new ArrayList(); + testDetails = new ArrayList(); + testDetails.add(new ArrayList()); + } + + /** + * Parse all results and display on a GUI + */ + public void show() + { + // Set up panel + JFrame frame = new JFrame("Java2D benchmark results"); + Container cp = frame.getContentPane(); + + // Non-editable text area for the results + results = new JTextArea(); + results.setEditable(false); + results.setRows(15); + results.setColumns(60); + + // Checkbox to optionally display details (ie log messages) + details = new JCheckBox("Details", false); + details.addActionListener(this); + + // Combo box to allow selection of iteration number + iterations = new JComboBox(); + iterations.addActionListener(this); + for (int i = 0; i < testResults.size(); i++) + iterations.addItem("Iteration #" + (i + 1)); + + // Lay it all out + JPanel topleft = new JPanel(); + topleft.add(new JLabel("View results from: ")); + topleft.add(iterations); + topleft.setAlignmentX(JComponent.LEFT_ALIGNMENT); + details.setAlignmentX(JComponent.RIGHT_ALIGNMENT); + JPanel top = new JPanel(); + top.setLayout(new BoxLayout(top, BoxLayout.LINE_AXIS)); + top.add(topleft); + top.add(details); + + cp.add(top, BorderLayout.NORTH); + cp.add(new JScrollPane(results), BorderLayout.SOUTH); + + frame.pack(); + frame.show(); + } + + /** + * This overrides the logger publish method, which accepts log messages and + * saves them for later display + * + * @param record information about the log event + */ + public void publish(LogRecord record) + { + ((ArrayList) testDetails.get(testDetails.size() - 1)).add(record.getMessage()); + } + + /** + * Accepts a test summary report, generated after each iteration of a test + * + * @param results test results + */ + public void report(ArrayList results) + { + testResults.add(results); + testDetails.add(new ArrayList()); + } + + /** + * Provided as part of the Handler interface; not used + */ + public void flush() + { + } + + /** + * Provided as part of the Handler interface; not used + */ + public void close() + { + } + + /** + * Handle user-generated events on the results GUI + */ + public void actionPerformed(ActionEvent ev) + { + // Display information about the requested iteration + int iteration = iterations.getSelectedIndex(); + String message = ""; + + // Display summary or details, as requested + Iterator it; + if (details.isSelected()) + it = ((ArrayList) testDetails.get(iteration)).iterator(); + else + it = ((ArrayList) testResults.get(iteration)).iterator(); + + // Parse the ArrayList's + while (it.hasNext()) + { + message = message + ((String) it.next() + "\n"); + } + + // Output to screen + results.setText(message); + } + } + +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/java2d/JNIOverhead.java b/libjava/classpath/examples/gnu/classpath/examples/java2d/JNIOverhead.java new file mode 100644 index 000000000..49996499e --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/java2d/JNIOverhead.java @@ -0,0 +1,390 @@ +/* JNIOverhead.java - demonstrator for classpath/gcj fillrect performance issue + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.java2d; + +import gnu.classpath.examples.swing.DemoFactory; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; + +/** + * @author Norman Hendrich + */ +public class JNIOverhead + extends JPanel + implements ActionListener +{ + + static JNIOverhead fillRectDemo; + + LCDCanvas lcd; + Worker worker; + JLabel label; + JCheckBox translate; + JCheckBox lines; + + int nx = 128; + int ny = 64; + int matrix[][], future[][]; + int generation = 0; + + // 20 msec, or 50 repaints per sec (theoretically) + int sleepMillis = 20; + long lastMillis = System.currentTimeMillis(); + + boolean enableRepaints = true; + + /** + * If true, test translation. + */ + boolean testTranslation = false; + + /** + * If true, paint lines rather than rectangles + */ + boolean paintLines; + + public void actionPerformed(ActionEvent e) + { + if (e.getActionCommand().equals("CLOSE")) + { + System.exit(0); + } + } + + public JNIOverhead() + { + setSize(nx, ny); + createContent(); + } + + public void createContent() + { + setLayout(new BorderLayout()); + + JPanel p = new JPanel(new BorderLayout()); + lcd = new LCDCanvas(); + label = new JLabel(); + label.setText("not running"); + + translate = new JCheckBox("translate"); + translate.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent event) + { + testTranslation = translate.isSelected(); + } + }); + + lines = new JCheckBox("lines"); + lines.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent event) + { + paintLines = lines.isSelected(); + } + }); + + JPanel bottom = new JPanel(); + bottom.add(lines); + bottom.add(translate); + + p.add(lcd, BorderLayout.CENTER); + p.add(bottom, BorderLayout.SOUTH); + p.add(label, BorderLayout.NORTH); + add(p); + } + + public void setSize(int _nx,int _ny ) + { + nx = _nx; + ny = _ny; + matrix = new int[nx][ny]; + future = new int[nx][ny]; + } + + public void initFrameContent() + { + JPanel closePanel = new JPanel(); + JButton closeButton = new JButton("Close"); + closeButton.setActionCommand("CLOSE"); + closeButton.addActionListener(this); + closePanel.add(closeButton); + add(closePanel, BorderLayout.SOUTH); + } + + public void setSleepMillis(int millis) + { + sleepMillis = millis; + } + + public class LCDCanvas extends JPanel + { + private int sx, sy; + private Color activePixel = new Color(30, 30, 40); + private Color passivePixel = new Color(200, 180, 240); + private Color gridPixel = new Color(255, 240, 240); + + public LCDCanvas() + { + super(); + sx = 4 * nx; + sy = 4 * ny; + } + + public void paintComponent(Graphics g) + { + // for buffered drawing - not used atm + // g.drawImage( buffer, 0, 0, null ); + long t1 = System.currentTimeMillis(); + + g.setColor(gridPixel); + g.fillRect(0, 0, sx, sy); + + Color pixelColor = null; + + int dx, dy; + + if (paintLines) + { + for (int ix = 0; ix < nx; ix++) + for (int iy = 0; iy < ny; iy++) + { + if (matrix[ix][iy] != 0) + pixelColor = activePixel; + else + pixelColor = passivePixel; + + dx = 4 * ix; + dy = 4 * iy; + g.setColor(pixelColor); + + if (testTranslation) + { + g.translate(dx, dy); + g.drawLine(0, 0, 5, 5); + g.translate(- dx, - dy); + } + else + g.drawLine(dx, dy, dx + 5, dy + 5); + } + } + else + for (int ix = 0; ix < nx; ix++) + { + for (int iy = 0; iy < ny; iy++) + { + if (matrix[ix][iy] != 0) + pixelColor = activePixel; + else + pixelColor = passivePixel; + + dx = 4 * ix; + dy = 4 * iy; + g.setColor(pixelColor); + + if (testTranslation) + { + g.translate(dx, dy); + g.fillRect(0, 0, 3, 3); + g.translate(- dx, - dy); + } + else + g.fillRect(dx, dy, 3, 3); + } + } + + long t2 = System.currentTimeMillis(); + + label.setText("paintComponent took " + (t2 - t1) + " msec. " + "(" + + (nx * ny + 1) + " " + + (paintLines ? "drawLine" : "fillRect") + " calls)"); + + } + + public Dimension getPreferredSize() + { + return new Dimension(sx,sy); + } + + public Dimension getMinimumSize() + { + return new Dimension(sx,sy); + } + } + + public class Worker extends Thread + { + public void run() + { + boolean running = true; + while(running) + { + iteration(); + + if (enableRepaints) + display(); + + if (sleepMillis > 0) + { + try + { + Thread.sleep( sleepMillis ); + } + catch(InterruptedException ie) + { + running = false; + } + } + } + } + } + + /** + * stupid animation algorithm: show binary representation of current + * iteration. + */ + public void iteration() + { + generation++; + + for (int i = 0; i < nx; i++) + { + long tmp1 = 1L << i; + for (int j = 0; j < ny; j++) + { + // count neighbors + long tmp2 = (1L << j); + + + long tmp3 = generation & tmp1 & tmp2; + if (tmp3 != 0) + matrix[i][j] = 1; + else + matrix[i][j] = 0; + } + } + + if ((generation % 100) == 0) + { + long t = System.currentTimeMillis(); + // System.out.println( + // " generation= " + generation + + // " iterations/sec= " + 100.0*1000/(t-lastMillis) ); + lastMillis = t; + } + } + + public void display() + { + lcd.repaint(); + } + + public static void usage() + { + System.out.println( + "Usage: FillRect2 [-sleep ] [-size ] [-nopaint]\n" + + "Example: jamvm FillRect2 -sleep 10 -size 100\n" + ); + System.exit(0); + } + + public static void main(String args[]) + throws Exception + { + fillRectDemo = new JNIOverhead(); + for (int i = 0; i < args.length; i++) + { + if ("-help".equals(args[i])) + { + usage(); + } + if ("-sleep".equals(args[i])) + { + fillRectDemo.setSleepMillis( Integer.parseInt(args[i + 1])); + i++; + } + if ("-size".equals(args[i])) + { + int size = Integer.parseInt(args[i + 1]); + fillRectDemo.setSize(size, size); + i++; + } + if ("-nopaint".equals(args[i])) + { + fillRectDemo.enableRepaints = false; + } + } + + SwingUtilities.invokeLater (new Runnable() + { + public void run() + { + + fillRectDemo.initFrameContent(); + JFrame frame = new JFrame("FillRect performance test"); + frame.getContentPane().add(fillRectDemo); + frame.pack(); + frame.show(); + fillRectDemo.worker = fillRectDemo.new Worker(); + fillRectDemo.worker.start(); + } + }); + } + + /** + * Returns a DemoFactory that creates a SliderDemo. + * + * @return a DemoFactory that creates a SliderDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + fillRectDemo = new JNIOverhead(); + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + fillRectDemo.worker = fillRectDemo.new Worker(); + fillRectDemo.worker.start(); + } + }); + return fillRectDemo; + } + }; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/java2d/bench.c b/libjava/classpath/examples/gnu/classpath/examples/java2d/bench.c new file mode 100644 index 000000000..e5b45aa1c --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/java2d/bench.c @@ -0,0 +1,606 @@ +/* bench.c -- native benchmark for Cairo library (meant to test java2d) + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +#include "bench.h" +#include +#include +#include +#include +#include +#include + +G_DEFINE_TYPE (Benchmark, benchmark, GTK_TYPE_DRAWING_AREA); + +// Needed for the gtk widget, but not used: +static void +benchmark_class_init (BenchmarkClass *klass) +{ +} + +static void +benchmark_init (Benchmark *obj) +{ +} + +// The Arc2D's PathIterator uses some transforms, so we condense the required +// functionality of AffineTransform +static void +doTransform (double rx, double ry, double theta, double *cvec) +{ + // Define identity matrix (corresponds to new AffineTransform()) + double m00 = 1; + double m10 = 0; + double m01 = 0; + double m11 = 1; + double m02 = 0; + double m12 = 0; + + // AffineTransform.scale(rx, ry) + m00 = m00 * rx; + m01 = m01 * ry; + m10 = m10 * rx; + m11 = m11 * ry; + + // AffineTransform.rotate(theta) + double c = cos(theta); + double s = sin(theta); + double n00 = m00 * c + m01 * s; + double n01 = m00 * -s + m01 * c; + double n10 = m10 * c + m11 * s; + double n11 = m10 * -s + m11 * c; + + m00 = n00; + m01 = n01; + m10 = n10; + m11 = n11; + + // AffineTransform.transform(cvec, 0, cvec, 0, 1) + double dstPts[2]; + dstPts[0] = (float) (m00 * cvec[0] + m01 * cvec[1] + m02); + dstPts[1] = (float) (m10 * cvec[0] + m11 * cvec[1] + m12); + cvec[0] = dstPts[0]; + cvec[1] = dstPts[1]; +} + +// Place an arc on the cairo path, simulating java2d's Arc2D +static void +setupArc(cairo_t *cr, GtkWidget *bench, int shift) +{ + double x, y; + + // Normally passed into the Arc2D constructor + x = bench->allocation.x + (rand() % (bench->allocation.width - minSize + 1)); + y = bench->allocation.y + (rand() % (bench->allocation.height - minSize + 1)); + + int angle = rand() % 360; + int length = (rand() % 360) - angle; + int width = rand() % (int)((bench->allocation.width - x - 10) + 10); + int height = rand() % (int)((bench->allocation.height - y - 10) + 10); + + // This is from the ArcPath iterator + double start = angle * (M_PI / 180); + double extent = length * (M_PI / 180); + + if (extent < 0) + { + extent = -extent; + start = 2 * M_PI - extent + start; + } + + int limit; + if (width < 0 || height < 0) // We assume type == 0; ie, Arc2D.OPEN + limit = -1; + else if (extent == 0) + limit = 0; + else if (extent <= M_PI / 2.0) + limit = 1; + else if (extent <= M_PI) + limit = 2; + else if (extent <= 3.0 * (M_PI / 2.0)) + limit = 3; + else + limit = 4; + + // This is from CairoGraphics2D.walkPath + double xnew = 0; + double ynew = 0; + double coords[6]; + + cairo_fill_rule_t cfillrule = CAIRO_FILL_RULE_WINDING; + cairo_set_fill_rule(cr, cfillrule); + + // First iteration will move to the starting point + double rx = width / 2; + double ry = height / 2; + double xmid = x + rx; + double ymid = y + ry; + coords[0] = xmid + rx * cos(start); + coords[1] = ymid - ry * sin(start); + + if (shift == 1) + { + xnew = floor(coords[0]) + 0.5; + ynew = floor(coords[1]) + 0.5; + } + else + { + xnew = coords[0]; + ynew = coords[1]; + } + + cairo_move_to(cr, xnew, ynew); + + // Iterate through segments of the arc + int current; + for (current = 1; current <= limit; current++) + { + // Back to the ArcPath iterator's getCurrent + double kappa = (sqrt(2.0) - 1.0) * (4.0 / 3.0); + double quad = (M_PI / 2.0); + + double curr_begin = start + (current - 1) * quad; + double curr_extent; + + if (start + extent - curr_begin < quad) + curr_extent = (start + extent) - curr_begin; + else + curr_extent = quad; + + double portion_of_a_quadrant = curr_extent / quad; + + double x0 = xmid + rx * cos(curr_begin); + double y0 = ymid - ry * sin(curr_begin); + + double x1 = xmid + rx * cos(curr_begin + curr_extent); + double y1 = ymid - ry * sin(curr_begin + curr_extent); + + double cvec[2]; + double len = kappa * portion_of_a_quadrant; + double angle = curr_begin; + + cvec[0] = 0; + cvec[1] = len; + doTransform(rx, ry, angle, cvec); + coords[0] = x0 + cvec[0]; + coords[1] = y0 - cvec[1]; + + cvec[0] = 0; + cvec[1] = -len; + doTransform(rx, ry, angle, cvec); + doTransform(1, 1, curr_extent, cvec); + coords[2] = x1 + cvec[0]; + coords[3] = y1 - cvec[1]; + + coords[4] = x1; + coords[5] = y1; + + // draw it, from CairoGraphics2D.walkPath + if (shift == 1) + { + xnew = floor(coords[4]) + 0.5; + ynew = floor(coords[5]) + 0.5; + cairo_curve_to(cr, floor(coords[0]) + 0.5, floor(coords[1]) + 0.5, + floor(coords[2]) + 0.5, floor(coords[3]) + 0.5, + xnew, ynew); + } + else + { + xnew = coords[4]; + ynew = coords[5]; + cairo_curve_to(cr, coords[0], coords[1], coords[2], + coords[3], xnew, ynew); + } + } + + // Randomize the colour, just for asthetics =) + cairo_set_source_rgb(cr, (rand() % 100 / (float)100), + (rand() % 100 / (float)100), + (rand() % 100 / (float)100)); + +} + +// Place a beizer curve on the cairo path, simulating java2d's CubicCurve2D +static void +setupCurve(cairo_t *cr, GtkWidget *bench, int shift) +{ + // These are options when creating a new curve + int x1 = bench->allocation.x + (rand() % (bench->allocation.width - minSize)); + int y1 = bench->allocation.y + (rand() % (bench->allocation.height - minSize)); + int xc1 = bench->allocation.x + (rand() % (bench->allocation.width - minSize)); + int yc1 = bench->allocation.y + (rand() % (bench->allocation.height - minSize)); + int xc2 = bench->allocation.x + (rand() % (bench->allocation.width - minSize)); + int yc2 = bench->allocation.y + (rand() % (bench->allocation.height - minSize)); + int x2 = bench->allocation.x + (rand() % (bench->allocation.width - minSize)); + int y2 = bench->allocation.y + (rand() % (bench->allocation.height - minSize)); + + // From CairoGraphics2D.walkPath + double xnew = 0; + double ynew = 0; + double coords[6]; + + cairo_fill_rule_t cfillrule = CAIRO_FILL_RULE_WINDING; + cairo_set_fill_rule(cr, cfillrule); + + // And into CubicCurve's PathIterator... + // start by moving to the starting coordinate + coords[0] = (float) x1; + coords[1] = (float) y1; + + if (shift == 1) + { + xnew = floor(coords[0]) + 0.5; + ynew = floor(coords[1]) + 0.5; + } + else + { + xnew = coords[0]; + ynew = coords[1]; + } + + cairo_move_to(cr, xnew, ynew); + + // Now the curve itself + coords[0] = (float) xc1; + coords[1] = (float) yc1; + coords[2] = (float) xc2; + coords[3] = (float) yc2; + coords[4] = (float) x2; + coords[5] = (float) y2; + + if (shift == 1) + { + xnew = floor(coords[4]) + 0.5; + ynew = floor(coords[5]) + 0.5; + cairo_curve_to(cr, floor(coords[0]) + 0.5, floor(coords[1]) + 0.5, + floor(coords[2]) + 0.5, floor(coords[3]) + 0.5, + xnew, ynew); + } + else + { + xnew = coords[4]; + ynew = coords[5]; + cairo_curve_to(cr, coords[0], coords[1], coords[2], + coords[3], xnew, ynew); + } + + // Randomize colour for asthetics + cairo_set_source_rgb(cr, (rand() % 100 / (float)100), + (rand() % 100 / (float)100), + (rand() % 100 / (float)100)); +} + +// Place a line on the cairo path, simulating java2d's Line2D +static void +setupLine(cairo_t *cr, GtkWidget *bench, int shift) +{ + // These are set when you create a line + int x1 = bench->allocation.x + (rand() % (bench->allocation.width - minSize)); + int y1 = bench->allocation.y + (rand() % (bench->allocation.height - minSize)); + int x2 = bench->allocation.x + (rand() % (bench->allocation.width - minSize)); + int y2 = bench->allocation.y + (rand() % (bench->allocation.height - minSize)); + + // This is from CairoGraphics2D.walkPath + double xnew = 0; + double ynew = 0; + double coords[6]; + + cairo_fill_rule_t cfillrule = CAIRO_FILL_RULE_WINDING; + cairo_set_fill_rule(cr, cfillrule); + + // And into Line2D's PathIterator + coords[0] = (float) x1; + coords[1] = (float) y1; + + if (shift == 1) + { + xnew = floor(coords[0]) + 0.5; + ynew = floor(coords[1]) + 0.5; + } + else + { + xnew = coords[0]; + ynew = coords[1]; + } + + cairo_move_to(cr, xnew, ynew); + + coords[0] = (float) x2; + coords[1] = (float) y2; + + if (shift == 1) + { + xnew = floor(coords[0]) + 0.5; + ynew = floor(coords[1]) + 0.5; + } + else + { + xnew = coords[0]; + ynew = coords[1]; + } + + cairo_line_to(cr, xnew, ynew); + + // Randomize colour for asthetics + cairo_set_source_rgb(cr, (rand() % 100 / (float)100), + (rand() % 100 / (float)100), + (rand() % 100 / (float)100)); +} + +// Place a rectangle on the cairo path, simulating java2d's Rectangle2D +static void +setupRect(cairo_t *cr, GtkWidget *bench, int shift) +{ + // These are set when you create a rectangle + int x1 = bench->allocation.x + (rand() % (bench->allocation.width - minSize)); + int y1 = bench->allocation.y + (rand() % (bench->allocation.height - minSize)); + int x2 = bench->allocation.x + (rand() % (bench->allocation.width - minSize)); + int y2 = bench->allocation.y + (rand() % (bench->allocation.height - minSize)); + + // draw() and fill() have been optimized to ignore the PathIterator. + // We do the same here. + double xnew = 0; + double ynew = 0; + + if (shift == 1) + { + xnew = floor(x1) + 0.5; + ynew = floor(y1) + 0.5; + } + else + { + xnew = x1; + ynew = y1; + } + + cairo_rectangle(cr, x1, y1, x2, y2); + + // Randomize colour for asthetics + cairo_set_source_rgb(cr, (rand() % 100 / (float)100), + (rand() % 100 / (float)100), + (rand() % 100 / (float)100)); +} + +// The real work gets done here: this function is called when the widget +// is drawn on screen. +static void +draw (GtkWidget *bench, cairo_t *cr) +{ + // Setup + struct timeb t1, t2; + int i, timeElapsed; + + cairo_set_line_width(cr, lineWidth); + + if (antialias == 0) + cairo_set_antialias(cr, CAIRO_ANTIALIAS_NONE); + else + cairo_set_antialias(cr, CAIRO_ANTIALIAS_GRAY); + + // Tell the user what's going on + printf("Testing native cairo drawing..\n"); + printf(" Screen size is %d x %d \n", screenWidth, screenHeight); + printf(" Line width is %d\n", lineWidth); + printf(" Test size: %d\n", testSize); + + if (antialias == 0) + printf(" Anti-alias is off\n"); + else + printf(" Anti-alias is on\n"); + + printf("\n"); + fflush(stdout); + + // Draw & fill Arc + if (arcTest == 1) + { + // Draw + ftime(&t1); + for (i = 0; i < testSize; i++) + { + setupArc(cr, bench, 1); + cairo_stroke (cr); + } + + ftime(&t2); + timeElapsed = 1000 * (t2.time - t1.time) + (t2.millitm - t1.millitm); + printf("Draw arc: %d ms\n", timeElapsed); + fflush(stdout); + + // Fill + ftime(&t1); + for (i = 0; i < testSize; i++) + { + setupArc(cr, bench, 0); + cairo_fill (cr); + } + + ftime(&t2); + timeElapsed = 1000 * (t2.time - t1.time) + (t2.millitm - t1.millitm); + printf("Fill arc: %d ms\n", timeElapsed); + } + + // Draw cubic curve + if (curveTest == 1) + { + ftime(&t1); + for (i = 0; i < testSize; i++) + { + setupCurve(cr, bench, 1); + cairo_stroke (cr); + } + + ftime(&t2); + timeElapsed = 1000 * (t2.time - t1.time) + (t2.millitm - t1.millitm); + printf("Draw cubic curve: %d ms\n", timeElapsed); + } + + // Ellipse: skip; this is just a special case of arc + // General path: skip; this doesn't even work in java2d + + // Draw Line + if (lineTest == 1) + { + ftime(&t1); + for (i = 0; i < testSize; i++) + { + setupLine(cr, bench, 1); + cairo_stroke (cr); + } + + ftime(&t2); + timeElapsed = 1000 * (t2.time - t1.time) + (t2.millitm - t1.millitm); + printf("Draw line: %d ms\n", timeElapsed); + } + + // Draw & fill Rectangle + if (rectTest == 1) + { + // Draw + ftime(&t1); + for (i = 0; i < testSize; i++) + { + setupRect(cr, bench, 1); + cairo_stroke (cr); + } + + ftime(&t2); + timeElapsed = 1000 * (t2.time - t1.time) + (t2.millitm - t1.millitm); + printf("Draw rectangle: %d ms\n", timeElapsed); + + // Fill + ftime(&t1); + for (i = 0; i < testSize; i++) + { + setupRect(cr, bench, 0); + cairo_fill (cr); + } + + ftime(&t2); + timeElapsed = 1000 * (t2.time - t1.time) + (t2.millitm - t1.millitm); + printf("Fill rectangle: %d ms\n", timeElapsed); + } + + // Round rectangle: skip, it's just a combination of lines and curves + // Image: skip? + + printf("\n"); +} + +GtkWidget * +benchmark_new (void) +{ + return g_object_new (BENCHMARK_TYPE, NULL); +} + +int +main (int argc, char **argv) +{ + // Set defaults + minSize = 10; + arcTest = 0; + curveTest = 0; + lineTest = 0; + rectTest = 0; + screenWidth = 320; + screenHeight = 240; + testSize = 1000; + antialias = 0; + lineWidth = 1; + + // Process any command-line user options + int i; + for (i = 1; i < argc; i++) + { + // Process options first + if (!strcmp(argv[i], "-a")) + antialias = 1; + else if (!strcmp(argv[i], "-h")) + screenHeight = atoi(argv[++i]); + else if (!strcmp(argv[i], "-l")) + lineWidth = atoi(argv[++i]); + else if (!strcmp(argv[i], "-t")) + testSize = atoi(argv[++i]); + else if (!strcmp(argv[i], "-w")) + screenWidth = atoi(argv[++i]); + else if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--h") + || !strcmp(argv[i], "-help") || !strcmp(argv[i], "--help")) + { + printf("Cairo benchmarker, meant to measure JNI overhead\n"); + printf("Usage: bench [-a] [-h height] [-t test size] [-w width] [tests...]\n"); + printf("\n"); + printf(" Valid options: -a turn on anti-aliasing (default off)\n"); + printf(" -h set screen height (default 240)\n"); + printf(" -l set stroke line width (default 1)\n"); + printf(" -t set test size (default 1000)\n"); + printf(" -w set screen width (default 320)\n"); + printf(" -h | --help\n"); + printf(" Valid tests: arc\n"); + printf(" curve\n"); + printf(" line\n"); + printf(" rect\n"); + printf(" (default: run all)\n"); + exit (0); + } + + // Process tests + else if (!strcmp(argv[i], "arc")) + arcTest = 1; + else if (!strcmp(argv[i], "curve")) + curveTest = 1; + else if (!strcmp(argv[i], "line")) + lineTest = 1; + else if (!strcmp(argv[i], "rect")) + rectTest = 1; + } + + // If no tests were specified, we default to running all of them + if (arcTest == 0 && curveTest == 0 && lineTest == 0 && rectTest == 0) + { + arcTest = 1; + curveTest = 1; + lineTest = 1; + rectTest = 1; + } + + // Set up gtk widget + GtkWidget *window, *bench; + gtk_init (&argc, &argv); + + window = gtk_window_new (GTK_WINDOW_TOPLEVEL); + gtk_window_resize(GTK_WINDOW(window), screenWidth, screenHeight); + gtk_window_set_title(GTK_WINDOW(window), "cairo benchmark"); + + // Set up benchmkar and cairo surface + bench = benchmark_new (); + gtk_container_add (GTK_CONTAINER (window), bench); + gtk_widget_show_all (window); + + cairo_t *cr; + cr = gdk_cairo_create (bench->window); + + // Run tests + draw (bench, cr); + + // Hold output on screen until user exits. + printf("Press any key to exit.\n"); + getchar(); + exit(0); +gtk_main(); +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/java2d/bench.h b/libjava/classpath/examples/gnu/classpath/examples/java2d/bench.h new file mode 100644 index 000000000..aebd50a67 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/java2d/bench.h @@ -0,0 +1,64 @@ +/* bench.h -- native benchmark for Cairo library (meant to test java2d) + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +#ifndef __BENCH_H__ +#define __BENCH_H__ + +#include + +G_BEGIN_DECLS + +#define BENCHMARK_TYPE (benchmark_get_type()) +#define BENCHMARK(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj, BENCHMARK_TYPE, Benchmark) +#define BENCHMARK_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), BENCHMARK_TYPE, BenchmarkClass); +#define IS_BENCHMARK(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), BENCHMARK_TYPE)) +#define IS_BENCHMARK_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), BENCHMARK_TYPE)) +#define BENCHMARK_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), BENCHMARK_TYPE, BenchmarkClass)) + +typedef struct _Benchmark Benchmark; +typedef struct _BenchmarkClass BenchmarkClass; + +struct _Benchmark { + GtkDrawingArea parent; + +}; + +struct _BenchmarkClass { + GtkDrawingAreaClass parent_class; +}; + +GType benchmark_get_type (void); +GtkWidget *benchmark_new (void); + +static int minSize; +static int antialias; +static int arcTest; +static int curveTest; +static int lineTest; +static int rectTest; + +static int screenHeight; +static int screenWidth; +static int testSize; +static int lineWidth; + +G_END_DECLS + +#endif diff --git a/libjava/classpath/examples/gnu/classpath/examples/jawt/DemoJAWT.c b/libjava/classpath/examples/gnu/classpath/examples/jawt/DemoJAWT.c new file mode 100644 index 000000000..ee2d7bfec --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/jawt/DemoJAWT.c @@ -0,0 +1,150 @@ +/* DemoJAWT.c -- native portion of AWT Native Interface demo + Copyright (C) 2005 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +#include "DemoJAWT.h" +#include "jawt_md.h" +#include + +JNIEXPORT void JNICALL +Java_gnu_classpath_examples_jawt_DemoJAWT_paintIt (JNIEnv* env, + jobject canvas, + jobject graphics, + jboolean on) +{ + JAWT awt; + JAWT_DrawingSurface* surface; + JAWT_DrawingSurfaceInfo* surface_info; + JAWT_X11DrawingSurfaceInfo* surface_info_x11; + jint lock; + GC gc; + int c; + char* test_string = "JAWT"; + XColor orange; + XColor yellow; + XColor blue; + Display* display; + Drawable drawable; + Status status; + + awt.version = JAWT_VERSION_1_3; + if (JAWT_GetAWT (env, &awt) == JNI_FALSE) + { + printf ("couldn't find AWT\n"); + return; + } + + surface = awt.GetDrawingSurface (env, canvas); + if (surface == NULL) + { + printf ("drawing surface is NULL\n"); + return; + } + + lock = surface->Lock (surface); + if ((lock & JAWT_LOCK_ERROR) != 0) + { + printf ("couldn't lock drawing surface\n"); + awt.FreeDrawingSurface (surface); + return; + } + + surface_info = surface->GetDrawingSurfaceInfo (surface); + if (surface_info == NULL) + { + printf ("couldn't get surface information\n"); + surface->Unlock (surface); + awt.FreeDrawingSurface (surface); + return; + } + + surface_info_x11 = (JAWT_X11DrawingSurfaceInfo*) surface_info->platformInfo; + + display = surface_info_x11->display; + drawable = surface_info_x11->drawable; + + gc = XCreateGC (display, drawable, 0, 0); + XSetBackground (display, gc, 0); + + orange.red = 254 * 65535 / 255; + orange.green = 90 * 65535 / 255; + orange.blue = 16 * 65535 / 255; + + /* assume color lookups succeed */ + status = XAllocColor (display, DefaultColormap (display, + DefaultScreen (display)), + &orange); + + if (!status) + { + printf ("color allocation failed\n"); + goto cleanup; + } + + yellow.red = 255 * 65535 / 255; + yellow.green = 255 * 65535 / 255; + yellow.blue = 0 * 65535 / 255; + + XAllocColor (display, DefaultColormap (display, + DefaultScreen (display)), + &yellow); + + if (!status) + { + printf ("color allocation failed\n"); + goto cleanup; + } + + blue.red = 16 * 65535 / 255; + blue.green = 30 * 65535 / 255; + blue.blue = 137 * 65535 / 255; + + XAllocColor (display, DefaultColormap (display, + DefaultScreen (display)), + &blue); + + if (!status) + { + printf ("color allocation failed\n"); + goto cleanup; + } + + for (c = 5; c >= 0; c--) + { + if (c % 2 == on) + XSetForeground (display, gc, yellow.pixel); + else + XSetForeground (display, gc, orange.pixel); + + XFillArc (display, drawable, gc, 140 - c * 15, 140 - c * 15, c * 30, c * 30, 0, 360 * 64); + } + + XSetForeground (display, gc, blue.pixel); + XDrawString (display, drawable, + gc, 129, 145, test_string, strlen (test_string)); + + cleanup: + XFreeGC (display, gc); + + surface->FreeDrawingSurfaceInfo (surface_info); + + surface->Unlock (surface); + + awt.FreeDrawingSurface (surface); +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/jawt/DemoJAWT.java b/libjava/classpath/examples/gnu/classpath/examples/jawt/DemoJAWT.java new file mode 100644 index 000000000..c8f931ece --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/jawt/DemoJAWT.java @@ -0,0 +1,77 @@ +/* DemoJAWT.java -- AWT Native Interface demo + Copyright (C) 2005 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.jawt; + +import java.awt.*; +import java.awt.event.*; + +public class DemoJAWT extends Canvas +{ + static + { + System.loadLibrary ("DemoJAWT"); + } + + public native void paintIt (Graphics g, boolean on); + + public void paint (Graphics g) + { + paintIt (g, on); + } + + private boolean on; + + public static void main (String[] args) + { + Frame f = new Frame ("GNU Classpath JAWT Demo"); + + f.setBounds (0, 0, 300, 300); + + f.setResizable (false); + + DemoJAWT jawtDemo = new DemoJAWT (); + f.add (jawtDemo); + + f.addWindowListener (new WindowAdapter () + { + public void windowClosing (WindowEvent evt) + { + System.exit (0); + } + }); + + f.show (); + + while (true) + { + try + { + Thread.sleep (500); + } + catch (InterruptedException ie) + { + // ignored + } + jawtDemo.on = ! jawtDemo.on; + f.repaint(); + } + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/management/TestBeans.java b/libjava/classpath/examples/gnu/classpath/examples/management/TestBeans.java new file mode 100644 index 000000000..381dca448 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/management/TestBeans.java @@ -0,0 +1,40 @@ +/* TestBeans.java -- Tests the dynamic interface of the beans. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.management; + +import java.lang.management.ManagementFactory; + +import java.util.Set; + +import javax.management.MBeanServer; +import javax.management.ObjectName; + +public class TestBeans +{ + public static void main(String[] args) + throws Exception + { + MBeanServer server = ManagementFactory.getPlatformMBeanServer(); + Set names = server.queryNames(null, null); + for (ObjectName name : names) + System.out.println(server.getMBeanInfo(name)); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/management/TestClassLoading.java b/libjava/classpath/examples/gnu/classpath/examples/management/TestClassLoading.java new file mode 100644 index 000000000..8465510ac --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/management/TestClassLoading.java @@ -0,0 +1,77 @@ +/* TestClassLoading.java -- Tests the class loading bean. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.management; + +import java.lang.management.ClassLoadingMXBean; +import java.lang.management.ManagementFactory; + +import static java.lang.management.ManagementFactory.CLASS_LOADING_MXBEAN_NAME; + +import javax.management.Attribute; +import javax.management.MBeanServer; +import javax.management.ObjectName; + +public class TestClassLoading +{ + public static void main(String[] args) + throws Exception + { + System.out.println("Testing locally..."); + ClassLoadingMXBean bean = ManagementFactory.getClassLoadingMXBean(); + System.out.println("Bean: " + bean); + System.out.println("Loaded classes: " + bean.getLoadedClassCount()); + System.out.println("Unloaded classes: " + bean.getUnloadedClassCount()); + System.out.println("Total loaded classes: " + bean.getTotalLoadedClassCount()); + boolean verbosity = bean.isVerbose(); + System.out.println("Verbose class output: " + (verbosity ? "yes" : "no")); + System.out.println("Changing verbose setting..."); + bean.setVerbose(!verbosity); + System.out.println("Verbose class output: " + (bean.isVerbose() ? "yes" : "no")); + System.out.println("Testing via the server..."); + MBeanServer server = ManagementFactory.getPlatformMBeanServer(); + ObjectName classBean = new ObjectName(CLASS_LOADING_MXBEAN_NAME); + System.out.println("Bean: " + classBean); + System.out.println("Loaded classes: " + server.getAttribute(classBean, "LoadedClassCount")); + System.out.println("Unloaded classes: " + server.getAttribute(classBean, + "UnloadedClassCount")); + System.out.println("Total loaded classes: " + server.getAttribute(classBean, + "TotalLoadedClassCount")); + verbosity = (Boolean) server.getAttribute(classBean, "Verbose"); + System.out.println("Verbose class output: " + (verbosity ? "yes" : "no")); + System.out.println("Changing verbose setting..."); + server.setAttribute(classBean, new Attribute("Verbose", !verbosity)); + System.out.println("Verbose class output: " + ((Boolean) + server.getAttribute(classBean, "Verbose") ? + "yes" : "no")); + System.out.println("Testing via the proxy..."); + bean = ManagementFactory.newPlatformMXBeanProxy(server, CLASS_LOADING_MXBEAN_NAME, + ClassLoadingMXBean.class); + System.out.println("Bean: " + bean); + System.out.println("Loaded classes: " + bean.getLoadedClassCount()); + System.out.println("Unloaded classes: " + bean.getUnloadedClassCount()); + System.out.println("Total loaded classes: " + bean.getTotalLoadedClassCount()); + verbosity = bean.isVerbose(); + System.out.println("Verbose class output: " + (verbosity ? "yes" : "no")); + System.out.println("Changing verbose setting..."); + bean.setVerbose(!verbosity); + System.out.println("Verbose class output: " + (bean.isVerbose() ? "yes" : "no")); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/management/TestCompilation.java b/libjava/classpath/examples/gnu/classpath/examples/management/TestCompilation.java new file mode 100644 index 000000000..b8c44752f --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/management/TestCompilation.java @@ -0,0 +1,48 @@ +/* TestCompilation.java -- Tests the compilation bean. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.management; + +import java.lang.management.ManagementFactory; +import java.lang.management.CompilationMXBean; + +public class TestCompilation +{ + + public static void main(String[] args) + { + CompilationMXBean bean = ManagementFactory.getCompilationMXBean(); + if (bean == null) + { + System.out.println("The compilation bean is not supported by this VM."); + System.exit(-1); + } + System.out.println("Bean: " + bean); + System.out.println("JIT compiler name: " + bean.getName()); + boolean timeMonitoring = bean.isCompilationTimeMonitoringSupported(); + System.out.println("Compilation time monitoring supported: " + timeMonitoring); + if (timeMonitoring) + { + System.out.println("Compilation time: " + + bean.getTotalCompilationTime() + "ms"); + } + } + +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/management/TestGarbageCollector.java b/libjava/classpath/examples/gnu/classpath/examples/management/TestGarbageCollector.java new file mode 100644 index 000000000..ddb22c30c --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/management/TestGarbageCollector.java @@ -0,0 +1,50 @@ +/* TestGarbageCollector.java -- Tests the garbage collector beans. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.management; + +import java.lang.management.GarbageCollectorMXBean; +import java.lang.management.ManagementFactory; + +import java.util.Arrays; +import java.util.Iterator; + +public class TestGarbageCollector +{ + + public static void main(String[] args) + { + Iterator beans = ManagementFactory.getGarbageCollectorMXBeans().iterator(); + while (beans.hasNext()) + { + GarbageCollectorMXBean bean = (GarbageCollectorMXBean) beans.next(); + System.out.println("Bean: " + bean); + System.out.println("Name: " + bean.getName()); + System.out.println("Memory pool names: " + + Arrays.toString(bean.getMemoryPoolNames())); + System.out.println("Is valid: " + + (bean.isValid() ? "yes" : "no")); + System.out.println("Collection count: " + + bean.getCollectionCount()); + System.out.println("Collection time: " + + bean.getCollectionTime() + "ms"); + } + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/management/TestMemory.java b/libjava/classpath/examples/gnu/classpath/examples/management/TestMemory.java new file mode 100644 index 000000000..7a5065f14 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/management/TestMemory.java @@ -0,0 +1,52 @@ +/* TestMemory.java -- Tests the memory bean. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.management; + +import java.lang.management.MemoryMXBean; +import java.lang.management.ManagementFactory; + +public class TestMemory +{ + public static void main(String[] args) + { + MemoryMXBean bean = ManagementFactory.getMemoryMXBean(); + System.out.println("Bean: " + bean); + System.out.println("Heap memory usage: " + + bean.getHeapMemoryUsage()); + System.out.println("Non-heap memory usage: " + + bean.getNonHeapMemoryUsage()); + System.out.println("Objects pending finalization: " + + bean.getObjectPendingFinalizationCount()); + System.out.println("Running garbage collector via bean..."); + bean.gc(); + System.out.println("Heap memory usage: " + + bean.getHeapMemoryUsage()); + System.out.println("Non-heap memory usage: " + + bean.getNonHeapMemoryUsage()); + System.out.println("Objects pending finalization: " + + bean.getObjectPendingFinalizationCount()); + boolean verbosity = bean.isVerbose(); + System.out.println("Verbose memory output: " + (verbosity ? "yes" : "no")); + System.out.println("Changing verbose setting..."); + bean.setVerbose(!verbosity); + System.out.println("Verbose memory output: " + (bean.isVerbose() ? "yes" : "no")); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/management/TestMemoryManager.java b/libjava/classpath/examples/gnu/classpath/examples/management/TestMemoryManager.java new file mode 100644 index 000000000..8e98acd4c --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/management/TestMemoryManager.java @@ -0,0 +1,46 @@ +/* TestMemoryManager.java -- Tests the memory manager beans. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.management; + +import java.lang.management.ManagementFactory; +import java.lang.management.MemoryManagerMXBean; + +import java.util.Arrays; +import java.util.Iterator; + +public class TestMemoryManager +{ + + public static void main(String[] args) + { + Iterator beans = ManagementFactory.getMemoryManagerMXBeans().iterator(); + while (beans.hasNext()) + { + MemoryManagerMXBean bean = (MemoryManagerMXBean) beans.next(); + System.out.println("Bean: " + bean); + System.out.println("Name: " + bean.getName()); + System.out.println("Memory pool names: " + + Arrays.toString(bean.getMemoryPoolNames())); + System.out.println("Is valid: " + + (bean.isValid() ? "yes" : "no")); + } + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/management/TestMemoryPool.java b/libjava/classpath/examples/gnu/classpath/examples/management/TestMemoryPool.java new file mode 100644 index 000000000..a5e24fd50 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/management/TestMemoryPool.java @@ -0,0 +1,91 @@ +/* TestMemoryPool.java -- Tests the memory pool beans. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.management; + +import java.lang.management.ManagementFactory; +import java.lang.management.MemoryPoolMXBean; +import java.util.Arrays; +import java.util.Iterator; + +public class TestMemoryPool +{ + + /** + * 1mb in bytes + */ + private static final int MB = 1 << 20; + + public static void main(String[] args) + { + Iterator beans = ManagementFactory.getMemoryPoolMXBeans().iterator(); + while (beans.hasNext()) + { + MemoryPoolMXBean bean = (MemoryPoolMXBean) beans.next(); + System.out.println("Bean: " + bean); + System.out.println("Name: " + bean.getName()); + System.out.println("Collection usage: " + bean.getCollectionUsage()); + boolean collectionUsage = bean.isCollectionUsageThresholdSupported(); + System.out.println("Collection usage threshold supported: " + + collectionUsage); + if (collectionUsage) + { + System.out.println("Collection usage threshold: " + + bean.getCollectionUsageThreshold()); + System.out.println("Setting collection usage threshold to 1MB (" + + MB + " bytes)"); + bean.setCollectionUsageThreshold(MB); + System.out.println("Collection usage threshold: " + + bean.getCollectionUsageThreshold()); + System.out.println("Collection usage threshold count: " + + bean.getCollectionUsageThresholdCount()); + System.out.println("Collection usage threshold exceeded: " + + (bean.isCollectionUsageThresholdExceeded() + ? "yes" : "no")); + } + System.out.println("Memory manager names: " + + Arrays.toString(bean.getMemoryManagerNames())); + System.out.println("Peak usage: " + bean.getPeakUsage()); + System.out.println("Current usage: " + bean.getUsage()); + System.out.println("Resetting peak usage..."); + bean.resetPeakUsage(); + System.out.println("Peak usage: " + bean.getPeakUsage()); + System.out.println("Current usage: " + bean.getUsage()); + boolean usage = bean.isUsageThresholdSupported(); + System.out.println("Usage threshold supported: " + usage); + if (usage) + { + System.out.println("Usage threshold: " + + bean.getUsageThreshold()); + System.out.println("Setting usage threshold to 1MB (" + + MB + " bytes)"); + bean.setUsageThreshold(MB); + System.out.println("Usage threshold: " + + bean.getUsageThreshold()); + System.out.println("Usage threshold count: " + + bean.getUsageThresholdCount()); + System.out.println("Usage threshold exceeded: " + + (bean.isUsageThresholdExceeded() + ? "yes" : "no")); + } + System.out.println("Valid: " + (bean.isValid() ? "yes" : "no")); + } + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/management/TestOS.java b/libjava/classpath/examples/gnu/classpath/examples/management/TestOS.java new file mode 100644 index 000000000..fe09346fd --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/management/TestOS.java @@ -0,0 +1,38 @@ +/* TestOS.java -- Tests the OS bean. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.management; + +import java.lang.management.ManagementFactory; +import java.lang.management.OperatingSystemMXBean; + +public class TestOS +{ + public static void main(String[] args) + { + OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); + System.out.println("Bean: " + osBean); + System.out.println("OS Name: " + osBean.getName()); + System.out.println("OS Version: " + osBean.getVersion()); + System.out.println("Architecture: " + osBean.getArch()); + System.out.println("Processors: " + osBean.getAvailableProcessors()); + System.out.println("System Load Average: " + osBean.getSystemLoadAverage()); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/management/TestRuntime.java b/libjava/classpath/examples/gnu/classpath/examples/management/TestRuntime.java new file mode 100644 index 000000000..2a629ca83 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/management/TestRuntime.java @@ -0,0 +1,54 @@ +/* TestRuntime.java -- Tests the runtime bean. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.management; + +import java.lang.management.ManagementFactory; +import java.lang.management.RuntimeMXBean; + +import java.util.Date; + +public class TestRuntime +{ + + public static void main(String[] args) + { + RuntimeMXBean vmBean = ManagementFactory.getRuntimeMXBean(); + System.out.println("Bean: " + vmBean); + boolean bootClassPath = vmBean.isBootClassPathSupported(); + System.out.println("Boot Class Path Supported: " + bootClassPath); + if (bootClassPath) + System.out.println("Boot Class Path: " + vmBean.getBootClassPath()); + System.out.println("Class Path: " + vmBean.getClassPath()); + System.out.println("Input Arguments: " + vmBean.getInputArguments()); + System.out.println("Library Path: " + vmBean.getLibraryPath()); + System.out.println("Management Spec. Version: " + vmBean.getManagementSpecVersion()); + System.out.println("Name: " + vmBean.getName()); + System.out.println("Spec Name: " + vmBean.getSpecName()); + System.out.println("Spec Vendor: " + vmBean.getSpecVendor()); + System.out.println("Spec Version: " + vmBean.getSpecVersion()); + System.out.println("Start Time: " + new Date(vmBean.getStartTime())); + System.out.println("System Properties: " + vmBean.getSystemProperties()); + System.out.println("Uptime: " + vmBean.getUptime() + "ms"); + System.out.println("VM Name: " + vmBean.getVmName()); + System.out.println("VM Vendor: " + vmBean.getVmVendor()); + System.out.println("VM Version: " + vmBean.getVmVersion()); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/management/TestThread.java b/libjava/classpath/examples/gnu/classpath/examples/management/TestThread.java new file mode 100644 index 000000000..ff57ee5ff --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/management/TestThread.java @@ -0,0 +1,118 @@ +/* TestThread.java -- Tests the thread bean. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.management; + +import java.lang.management.ManagementFactory; +import java.lang.management.ThreadInfo; +import java.lang.management.ThreadMXBean; + +import java.util.Arrays; + +public class TestThread +{ + + public static void main(String[] args) + { + ThreadMXBean bean = ManagementFactory.getThreadMXBean(); + System.out.println("Bean: " + bean); + System.out.println("Monitor deadlocked threads: " + bean.findMonitorDeadlockedThreads()); + long[] ids = bean.getAllThreadIds(); + System.out.println("Live thread ids: " + Arrays.toString(ids)); + boolean currentTimeMonitoring = bean.isCurrentThreadCpuTimeSupported(); + System.out.println("Current thread CPU time monitoring supported: " + currentTimeMonitoring); + if (currentTimeMonitoring) + { + boolean timeEnabled = bean.isThreadCpuTimeEnabled(); + System.out.println("Is time monitoring enabled... " + + (timeEnabled ? "yes" : "no")); + if (!timeEnabled) + { + System.out.println("Enabling..."); + bean.setThreadCpuTimeEnabled(true); + timeEnabled = bean.isThreadCpuTimeEnabled(); + System.out.println("Should now be enabled... " + + (timeEnabled ? "yes" : "no")); + } + if (timeEnabled) + { + System.out.println("Current thread CPU time: " + + bean.getCurrentThreadCpuTime() + + "ns"); + System.out.println("Current thread user time: " + + bean.getCurrentThreadUserTime() + + "ns"); + } + } + System.out.println("Daemon thread count: " + bean.getDaemonThreadCount()); + System.out.println("Peak thread count: " + bean.getPeakThreadCount()); + System.out.println("Resetting..."); + bean.resetPeakThreadCount(); + System.out.println("Peak thread count: " + bean.getPeakThreadCount()); + System.out.println("Thread count: " + bean.getThreadCount()); + boolean timeMonitoring = bean.isThreadCpuTimeSupported(); + System.out.println("Thread CPU time monitoring supported: " + timeMonitoring); + if (timeMonitoring) + { + for (int a = 0; a < ids.length; ++a) + { + System.out.println("Thread " + a + + " CPU time: " + + bean.getThreadCpuTime(ids[a]) + "ns"); + System.out.println("Thread " + + a + " user time: " + + bean.getThreadUserTime(ids[a]) + "ns"); + } + } + System.out.println("Current thread info: " + + bean.getThreadInfo(Thread.currentThread().getId())); + System.out.println("All thread info: " + Arrays.toString(bean.getThreadInfo(ids))); + System.out.println("Total started threads: " + bean.getTotalStartedThreadCount()); + boolean contentionMonitoring = bean.isThreadContentionMonitoringSupported(); + System.out.println("Thread contention monitoring supported: " + contentionMonitoring); + if (contentionMonitoring) + { + boolean contentionEnabled = bean.isThreadContentionMonitoringEnabled(); + System.out.println("Thread contention monitoring shouldn't be enabled... " + + (contentionEnabled ? "but it is" : "true")); + if (!contentionEnabled) + { + System.out.println("Enabling..."); + bean.setThreadContentionMonitoringEnabled(true); + contentionEnabled = bean.isThreadContentionMonitoringEnabled(); + System.out.println("Should now be enabled... " + + (contentionEnabled ? "it is" : "nope")); + } + if (contentionEnabled) + { + ThreadInfo[] info = bean.getThreadInfo(ids); + for (int a = 0; a < info.length; ++a) + { + System.out.println("Blocked time for thread " + + info[a].getThreadId() + ": " + + info[a].getBlockedTime() + "ms"); + System.out.println("Waited time for thread " + + info[a].getThreadId() + ": " + + info[a].getWaitedTime() + "ms"); + } + } + } + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/midi/Demo.java b/libjava/classpath/examples/gnu/classpath/examples/midi/Demo.java new file mode 100644 index 000000000..81c71dc11 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/midi/Demo.java @@ -0,0 +1,137 @@ +/* Demo.java -- And example of MIDI support + Copyright (C) 2005 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.midi; + +import java.awt.*; +import java.awt.event.*; +import java.util.*; +import javax.sound.midi.*; + +/** + * An example how javax.sound.midi facilities work. + */ +public class Demo extends Frame implements ItemListener +{ + Choice midiInChoice = new Choice(); + Choice midiOutChoice = new Choice(); + + MidiDevice inDevice = null; + MidiDevice outDevice = null; + + ArrayList inDevices = new ArrayList(); + ArrayList outDevices = new ArrayList(); + + public Demo () throws Exception + { + MenuBar mb = new MenuBar (); + Menu menu = new Menu ("File"); + MenuItem quit = new MenuItem("Quit", new MenuShortcut('Q')); + quit.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + System.exit(0); + } + }); + menu.add (quit); + mb.add(menu); + + setTitle("synthcity: the GNU Classpath MIDI Demo"); + setLayout(new FlowLayout()); + + MidiDevice.Info[] infos = MidiSystem.getMidiDeviceInfo(); + + for (int i = 0; i < infos.length; i++) + { + MidiDevice device = MidiSystem.getMidiDevice(infos[i]); + if (device.getMaxReceivers() > 0) + { + midiOutChoice.addItem(infos[i].getDescription()); + outDevices.add(device); + } + if (device.getMaxTransmitters() > 0) + { + midiInChoice.addItem(infos[i].getDescription()); + inDevices.add(device); + } + } + + setMenuBar (mb); + add(new Label("MIDI IN: ")); + add(midiInChoice); + add(new Label(" MIDI OUT: ")); + add(midiOutChoice); + + midiInChoice.addItemListener(this); + midiOutChoice.addItemListener(this); + + pack(); + show(); + } + + public void itemStateChanged (ItemEvent e) + { + try + { + if (e.getItemSelectable() == midiInChoice) + { + if (inDevice != null) + inDevice.close(); + inDevice = (MidiDevice) + inDevices.get(midiInChoice.getSelectedIndex()); + } + + if (e.getItemSelectable() == midiOutChoice) + { + if (outDevice != null) + outDevice.close(); + outDevice = (MidiDevice) + outDevices.get(midiOutChoice.getSelectedIndex()); + } + + if (inDevice != null && outDevice != null) + { + if (! inDevice.isOpen()) + inDevice.open(); + if (! outDevice.isOpen()) + outDevice.open(); + Transmitter t = inDevice.getTransmitter(); + if (t == null) + System.err.println (inDevice + ".getTransmitter() == null"); + Receiver r = outDevice.getReceiver(); + if (r == null) + System.err.println (outDevice + ".getReceiver() == null"); + + if (t != null && r != null) + t.setReceiver (r); + } + } + catch (Exception ex) + { + ex.printStackTrace(); + } + } + + public static void main (String args[]) throws Exception + { + new Demo(); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/print/Demo.java b/libjava/classpath/examples/gnu/classpath/examples/print/Demo.java new file mode 100644 index 000000000..fb4d74373 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/print/Demo.java @@ -0,0 +1,391 @@ +/* Demo.java -- Simple Java Print Service Demo + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.print; + +import java.awt.BorderLayout; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.util.HashSet; +import java.util.Iterator; + +import javax.print.DocFlavor; +import javax.print.DocPrintJob; +import javax.print.PrintException; +import javax.print.PrintService; +import javax.print.PrintServiceLookup; +import javax.print.ServiceUI; +import javax.print.SimpleDoc; +import javax.print.attribute.Attribute; +import javax.print.attribute.HashPrintRequestAttributeSet; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JFileChooser; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTabbedPane; +import javax.swing.JTextField; + + +/** + * A simple demo showing the use of the Java Print Service API. + * @author Wolfgang Baer (WBaer@gmx.de) + */ +public class Demo extends JFrame + implements ActionListener +{ + // The discovered print services + private static PrintService[] services; + + // variables for the PrintPanel demo + private HashPrintRequestAttributeSet atts; + private PrintService dialogSelectedService; + private JTextField dialogSelectedService_Tf; + private JList dialogSelectedServiceAtts; + private JComboBox dialogSelectedServicedocFormat; + private JTextField selectedFileTf; + private File selectedFile; + + // variables for the PrintServicePanel demo + private JComboBox serviceBox; + private JList docFormat; + private JList attCategories; + + static + { + // lookup all services without any constraints + services = PrintServiceLookup.lookupPrintServices(null, null); + } + + /** + * Constructs the Print Demo + * @param title - the demo title. + */ + public Demo(String title) + { + super(title); + JPanel content = new JPanel(new BorderLayout()); + + JTabbedPane tabbed = new JTabbedPane(); + tabbed.addTab("Discover print services", createPrintServicePanel()); + tabbed.addTab("Print a file", createPrintPanel()); + + JPanel closePanel = new JPanel(); + JButton closeButton = new JButton("Close"); + closeButton.setActionCommand("CLOSE"); + closeButton.addActionListener(this); + closePanel.add(closeButton); + + content.add(tabbed, BorderLayout.CENTER); + content.add(closePanel, BorderLayout.SOUTH); + getContentPane().add(content); + } + + private JPanel createPrintServicePanel() + { + JPanel panel = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + + c.insets = new Insets(5,5,5,5); + c.gridx = 0; + c.gridy = 0; + c.anchor = GridBagConstraints.WEST; + c.fill = GridBagConstraints.HORIZONTAL; + JLabel serviceBoxLb = new JLabel("Available print services: "); + panel.add(serviceBoxLb, c); + + c.gridx = 1; + c.gridy = 0; + serviceBox = new JComboBox(services); + serviceBox.setActionCommand("SERVICE"); + serviceBox.addActionListener(this); + panel.add(serviceBox, c); + + c.gridx = 0; + c.gridy = 1; + JLabel docFormatLb = new JLabel("Supported DocFormat: "); + panel.add(docFormatLb, c); + + c.gridx = 1; + c.gridy = 1; + docFormat = new JList(services[0].getSupportedDocFlavors()); + docFormat.setVisibleRowCount(3); + JScrollPane scrollPane = new JScrollPane(docFormat); + panel.add(scrollPane, c); + + c.gridx = 0; + c.gridy = 2; + JLabel categoriesLb = new JLabel("Supported Attribute categories: "); + panel.add(categoriesLb, c); + + c.gridx = 1; + c.gridy = 2; + attCategories = new JList(services[0].getSupportedAttributeCategories()); + attCategories.setVisibleRowCount(3); + JScrollPane scrollPane2 = new JScrollPane(attCategories); + panel.add(scrollPane2, c); + + return panel; + } + + private JPanel createPrintPanel() + { + JPanel panel = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + + c.insets = new Insets(5,5,5,5); + c.gridx = 0; + c.gridy = 0; + c.gridwidth = 2; + JButton serviceBtn = new JButton("Show print dialog ..."); + serviceBtn.addActionListener(this); + panel.add(serviceBtn, c); + + c.gridx = 0; + c.gridy = 1; + c.gridwidth = 1; + c.anchor = GridBagConstraints.WEST; + c.fill = GridBagConstraints.HORIZONTAL; + JLabel selectedLb = new JLabel("Selected print service: "); + panel.add(selectedLb, c); + + c.gridx = 1; + c.gridy = 1; + dialogSelectedService_Tf = new JTextField(25); + panel.add(dialogSelectedService_Tf, c); + + c.gridx = 0; + c.gridy = 2; + JLabel selectedAttsLb = new JLabel("Selected Attributes: "); + panel.add(selectedAttsLb, c); + + c.gridx = 1; + c.gridy = 2; + c.weighty = 1.5; + c.fill = GridBagConstraints.BOTH; + dialogSelectedServiceAtts = new JList(); + dialogSelectedServiceAtts.setVisibleRowCount(3); + JScrollPane scrollPane = new JScrollPane(dialogSelectedServiceAtts); + panel.add(scrollPane, c); + + c.gridx = 0; + c.gridy = 3; + c.fill = GridBagConstraints.HORIZONTAL; + JLabel fileLb = new JLabel("File to print: "); + panel.add(fileLb, c); + + c.gridx = 1; + c.gridy = 3; + selectedFileTf = new JTextField(25); + panel.add(selectedFileTf, c); + + c.gridx = 2; + c.gridy = 3; + c.fill = GridBagConstraints.NONE; + JButton fileBt = new JButton("Choose file"); + fileBt.addActionListener(this); + panel.add(fileBt, c); + + c.gridx = 0; + c.gridy = 4; + c.fill = GridBagConstraints.HORIZONTAL; + JLabel docFormatLb = new JLabel("Document format of file: "); + panel.add(docFormatLb, c); + + c.gridx = 1; + c.gridy = 4; + dialogSelectedServicedocFormat = new JComboBox(); + panel.add(dialogSelectedServicedocFormat, c); + + c.gridx = 0; + c.gridy = 5; + c.gridwidth = 2; + c.anchor = GridBagConstraints.CENTER; + c.fill = GridBagConstraints.NONE; + JButton printBt = new JButton("Print"); + printBt.setActionCommand("PRINT"); + printBt.addActionListener(this); + panel.add(printBt, c); + + return panel; + } + + /** + * Simple action control - only one listener + * @param event + */ + public void actionPerformed(ActionEvent event) + { + if (event.getActionCommand().equals("CLOSE")) + { + System.exit(0); + } + else if (event.getActionCommand().equals("Choose file")) + { + JFileChooser chooser = new JFileChooser(); + chooser.showOpenDialog(this); + + selectedFile = chooser.getSelectedFile(); + + if (selectedFile != null) + selectedFileTf.setText(selectedFile.getName()); + else + selectedFileTf.setText("None selected"); + } + else if (event.getActionCommand().equals("Show print dialog ...")) + { + atts = new HashPrintRequestAttributeSet(); + dialogSelectedService = ServiceUI.printDialog(null, 50, 50, services, + null, null, atts); + + if (dialogSelectedService != null) + { + dialogSelectedService_Tf.setText(dialogSelectedService.getName()); + + // we do not want to have the class representation in the dialog + // as we later always use an InputStream to open the file selected + + // use set to remove duplicates + DocFlavor[] docflavors = dialogSelectedService.getSupportedDocFlavors(); + HashSet set = new HashSet(); + for (int i=0; i < docflavors.length; i++) + { + String charset = docflavors[i].getParameter("charset"); + String mimetype = docflavors[i].getMediaType() + "/" + docflavors[i].getMediaSubtype(); + if (charset != null) + mimetype += "; charset=" + charset; + set.add(mimetype); + } + + dialogSelectedServicedocFormat.removeAllItems(); + for (Iterator it = set.iterator(); it.hasNext(); ) + dialogSelectedServicedocFormat.addItem(it.next()); + } + else + dialogSelectedService_Tf.setText("None selected"); + + Attribute[] attsArray = atts.toArray(); + String[] attsSTr = new String[attsArray.length]; + for (int i = 0; i < attsSTr.length; i++) + attsSTr[i] = attsArray[i].getName() + " - " + attsArray[i].toString(); + + dialogSelectedServiceAtts.setListData(attsSTr); + + validate(); + } + else if (event.getActionCommand().equals("PRINT")) + { + if (selectedFile != null && dialogSelectedService != null) + { + DocPrintJob job = dialogSelectedService.createPrintJob(); + + // choose correct docflavor + String mimetype = (String) dialogSelectedServicedocFormat.getSelectedItem(); + + DocFlavor flavor = null; + if (mimetype.equals(DocFlavor.INPUT_STREAM.GIF.getMimeType())) + flavor = DocFlavor.INPUT_STREAM.GIF; + else if (mimetype.equals(DocFlavor.INPUT_STREAM.AUTOSENSE.getMimeType())) + flavor = DocFlavor.INPUT_STREAM.AUTOSENSE; + else if (mimetype.equals(DocFlavor.INPUT_STREAM.JPEG.getMimeType())) + flavor = DocFlavor.INPUT_STREAM.JPEG; + else if (mimetype.equals(DocFlavor.INPUT_STREAM.PCL.getMimeType())) + flavor = DocFlavor.INPUT_STREAM.PCL; + else if (mimetype.equals(DocFlavor.INPUT_STREAM.PDF.getMimeType())) + flavor = DocFlavor.INPUT_STREAM.PDF; + else if (mimetype.equals(DocFlavor.INPUT_STREAM.PNG.getMimeType())) + flavor = DocFlavor.INPUT_STREAM.PNG; + else if (mimetype.equals(DocFlavor.INPUT_STREAM.POSTSCRIPT.getMimeType())) + flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT; + else if (mimetype.equals(DocFlavor.INPUT_STREAM.TEXT_HTML_HOST.getMimeType())) + flavor = DocFlavor.INPUT_STREAM.TEXT_HTML_HOST; + else if (mimetype.equals(DocFlavor.INPUT_STREAM.TEXT_PLAIN_HOST.getMimeType())) + flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_HOST; + else + flavor = new DocFlavor(mimetype, "java.io.InputStream"); + + try + { + SimpleDoc doc = new SimpleDoc(new FileInputStream(selectedFile), flavor, null); + job.print(doc, atts); + } + catch (FileNotFoundException e) + { + JOptionPane.showMessageDialog(this, "The file was not found."); + e.printStackTrace(); + } + catch (PrintException e) + { + JOptionPane.showMessageDialog(this, e, "PrintException", JOptionPane.ERROR_MESSAGE); + e.printStackTrace(); + } + } + else + JOptionPane.showMessageDialog(this, "Please select a file to print using the FileChooser", "No file selected", JOptionPane.INFORMATION_MESSAGE); + } + else if (event.getActionCommand().equals("SERVICE")) + { // A new service was selected + PrintService selected = (PrintService) serviceBox.getSelectedItem(); + + DocFlavor[] flavors = selected.getSupportedDocFlavors(); + docFormat.setListData(flavors); + attCategories.setListData(selected.getSupportedAttributeCategories()); + } + } + + /** + * Main method. + * @param args - nothing defined. + */ + public static void main(String[] args) + { + Demo app = new Demo("GNU Classpath printing demo"); + app.pack(); + app.setVisible(true); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/sound/AudioPlayerSample.java b/libjava/classpath/examples/gnu/classpath/examples/sound/AudioPlayerSample.java new file mode 100644 index 000000000..4518e25b1 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/sound/AudioPlayerSample.java @@ -0,0 +1,222 @@ +/* AudioPlayerSample.java -- Simple Java Audio Player + Copyright (C) 2007 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ +package gnu.classpath.examples.sound; + +import java.io.File; +import java.io.IOException; +import java.util.Map; + +import javax.sound.sampled.AudioFormat; +import javax.sound.sampled.AudioInputStream; +import javax.sound.sampled.AudioSystem; +import javax.sound.sampled.DataLine; +import javax.sound.sampled.LineUnavailableException; +import javax.sound.sampled.SourceDataLine; +import javax.sound.sampled.UnsupportedAudioFileException; + +/** + * A simple demo to show the use of the Java Sound API. + * It plays the given file (up to the end, so don't pass the 26 minutes long + * Pink Floyd's Echoes unless you really want!!). + * + * See: http://jsresources.org/examples/SimpleAudioPlayer.java.html + * + * @author Mario Torre + */ +public class AudioPlayerSample +{ + private static final int EXTERNAL_BUFFER_SIZE = 128000; + + /** + * @param args + */ + public static void main(String[] args) + { + if (args.length < 1) + { + System.out.println("Radio Classpath -: Usage: " + + "AudioPlayerSample [file]"); + return; + } + + String file = args[0]; + + System.out.println("Welcome to Radio Classpath, only great music for you!"); + System.out.println("Today's DJ Tap The WaterDroplet"); + + // now create the AudioInputStream + AudioInputStream audioInputStream = null; + try + { + audioInputStream = AudioSystem.getAudioInputStream(new File(file)); + } + catch (UnsupportedAudioFileException e) + { + // This happen when the subsystem is unable to parse the kind of + // audio file we are submitting + // See the README for supported audio file types under Classpath + // for the version you are using. + e.printStackTrace(); + return; + } + catch (IOException e) + { + e.printStackTrace(); + return; + } + + // get informations about the kind of file we are about to play + AudioFormat audioFormat = audioInputStream.getFormat(); + + System.out.println("Playing file: " + file); + System.out.println("format: " + audioFormat.toString()); + + System.out.print("Additional properties: "); + + // now, we try to get all the properties we have in this AudioFormat + // and display them + Map properties = audioFormat.properties(); + if (properties.size() < 0) + { + System.out.println("none"); + } + else + { + System.out.println("found #" + properties.size() + " properties"); + for (String key : properties.keySet()) + { + System.out.println(key + ": " + properties.get(key)); + } + } + + // let's setup things for playing + // first, we require a Line. As we are doing playing, we will ask for a + // SourceDataLine + SourceDataLine line = null; + + // To get the source line, we first need to build an Info object + // this is done in one line: + DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat); + + System.out.println("searching line..."); + + // usually, if a backend can parse a file type, it can also + // create a line to handle it, but that's not guaranteed + // so we need to take care and to handle a possible + // LineUnavailableException + try + { + line = (SourceDataLine) AudioSystem.getLine(info); + + System.out.println("line found, opening..."); + + // once created, a line must be opened to let data flow + // though it. + line.open(audioFormat); + } + catch (LineUnavailableException e) + { + // in a real application you should signal that in a kindly way to + // your users + e.printStackTrace(); + return; + } + catch (Exception e) + { + e.printStackTrace(); + return; + } + + // an open line pass data to the backend only when it is in + // a state called "started" ("playing" or "play" in some other + // framework) + System.out.print("starting line... "); + + line.start(); + System.out.println("done"); + + // now we can start reading data from the AudioStream and writing + // data to the pipeline. The Java Sound API is rather low level + // so let you pass up to one byte of data at a time + // (with some constraints, refer to the API documentation to know more) + // We will do some buffering. You may want to check the frame size + // to allow a better buffering, also. + + System.out.println("now playing..."); + + int nBytesRead = 0; + byte[] abData = new byte[EXTERNAL_BUFFER_SIZE]; + while (nBytesRead != - 1) + { + try + { + nBytesRead = audioInputStream.read(abData, 0, abData.length); + } + catch (IOException e) + { + e.printStackTrace(); + } + + if (nBytesRead >= 0) + { + // this method returns the number of bytes actuall written + // to the line. You may want to use this number to check + // for events, display the current position (give also a + // look to the API for other ways of doing that) etc.. + line.write(abData, 0, nBytesRead); + } + } + + System.out.print("stream finished, draining line... "); + + // call this method to ensure that all the data in the internal buffer + // reach the audio backend, otherwise your application will + // cut the last frames of audio data (and users will not enjoy the last + // seconds of their precious music) + line.drain(); + + // Once done, we can close the line. Note that a line, once closed + // may not be reopened (depends on the backend, in some cases a "reopen", + // if allowed, really opens a new line, reallocating all the resources) + + System.out.println("line drained, now exiting"); + line.close(); + + System.out.println("We hope you enjoyed Radio Classpath!"); + } + +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/BrowserEditorKit.java b/libjava/classpath/examples/gnu/classpath/examples/swing/BrowserEditorKit.java new file mode 100644 index 000000000..a929683b8 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/BrowserEditorKit.java @@ -0,0 +1,56 @@ +/* BrowserEditorKit.java -- A tweaked editor kit for the browser + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.swing; + +import javax.swing.text.html.HTMLEditorKit; + +/** + * A tweaked editor kit for out browser. + */ +public class BrowserEditorKit + extends HTMLEditorKit +{ + public BrowserEditorKit() + { + super(); + // Turn off automatic form submission so that we can receive notification + // instead and can update out location field. + setAutoFormSubmission(false); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/ButtonDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/ButtonDemo.java new file mode 100644 index 000000000..8b05dac13 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/ButtonDemo.java @@ -0,0 +1,319 @@ +/* ButtonDemo.java -- An example showing various buttons in Swing. + Copyright (C) 2005, 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. +*/ + + +package gnu.classpath.examples.swing; + +import java.awt.BorderLayout; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.BorderFactory; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JToggleButton; +import javax.swing.SwingConstants; +import javax.swing.SwingUtilities; +import javax.swing.plaf.metal.MetalIconFactory; + +/** + * A simple button demo showing various buttons in different states. + */ +public class ButtonDemo + extends JPanel + implements ActionListener +{ + + private JCheckBox buttonState; + private JButton button1; + private JButton button2; + private JButton button3; + private JButton button4; + + private JCheckBox toggleState; + private JToggleButton toggle1; + private JToggleButton toggle2; + private JToggleButton toggle3; + private JToggleButton toggle4; + + private JCheckBox checkBoxState; + private JCheckBox checkBox1; + private JCheckBox checkBox2; + private JCheckBox checkBox3; + + private JCheckBox radioState; + private JRadioButton radio1; + private JRadioButton radio2; + private JRadioButton radio3; + + /** + * Creates a new demo instance. + */ + public ButtonDemo() + { + createContent(); + // initFrameContent() is only called (from main) when running this app + // standalone + } + + /** + * When the demo is run independently, the frame is displayed, so we should + * initialise the content panel (including the demo content and a close + * button). But when the demo is run as part of the Swing activity board, + * only the demo content panel is used, the frame itself is never displayed, + * so we can avoid this step. + */ + void initFrameContent() + { + JPanel closePanel = new JPanel(); + JButton closeButton = new JButton("Close"); + closeButton.setActionCommand("CLOSE"); + closeButton.addActionListener(this); + closePanel.add(closeButton); + add(closePanel, BorderLayout.SOUTH); + } + + /** + * Returns a panel with the demo content. The panel + * uses a BorderLayout(), and the BorderLayout.SOUTH area + * is empty, to allow callers to add controls to the + * bottom of the panel if they want to (a close button is + * added if this demo is being run as a standalone demo). + */ + private void createContent() + { + setLayout(new BorderLayout()); + JPanel panel = new JPanel(new GridLayout(4, 1)); + panel.add(createButtonPanel()); + panel.add(createTogglePanel()); + panel.add(createCheckBoxPanel()); + panel.add(createRadioPanel()); + add(panel); + } + + private JPanel createButtonPanel() + { + JPanel panel = new JPanel(new BorderLayout()); + this.buttonState = new JCheckBox("Enabled", true); + this.buttonState.setActionCommand("BUTTON_STATE"); + this.buttonState.addActionListener(this); + panel.add(this.buttonState, BorderLayout.EAST); + + JPanel buttonPanel = new JPanel(); + buttonPanel.setBorder(BorderFactory.createTitledBorder("JButton")); + this.button1 = new JButton("Button 1"); + + this.button2 = new JButton("Button 2"); + this.button2.setIcon(MetalIconFactory.getInternalFrameDefaultMenuIcon()); + + this.button3 = new JButton("Button 3"); + this.button3.setIcon(MetalIconFactory.getFileChooserHomeFolderIcon()); + this.button3.setHorizontalTextPosition(SwingConstants.CENTER); + this.button3.setVerticalTextPosition(SwingConstants.BOTTOM); + + this.button4 = new JButton("Button 4"); + this.button4.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); + this.button4.setText(null); + + buttonPanel.add(button1); + buttonPanel.add(button2); + buttonPanel.add(button3); + buttonPanel.add(button4); + + panel.add(buttonPanel); + + return panel; + } + + private JPanel createTogglePanel() + { + JPanel panel = new JPanel(new BorderLayout()); + + this.toggleState = new JCheckBox("Enabled", true); + this.toggleState.setActionCommand("TOGGLE_STATE"); + this.toggleState.addActionListener(this); + + panel.add(this.toggleState, BorderLayout.EAST); + + JPanel buttonPanel = new JPanel(); + buttonPanel.setBorder(BorderFactory.createTitledBorder("JToggleButton")); + + this.toggle1 = new JToggleButton("Toggle 1"); + + this.toggle2 = new JToggleButton("Toggle 2"); + this.toggle2.setIcon(MetalIconFactory.getInternalFrameDefaultMenuIcon()); + + this.toggle3 = new JToggleButton("Toggle 3"); + this.toggle3.setIcon(MetalIconFactory.getFileChooserHomeFolderIcon()); + this.toggle3.setHorizontalTextPosition(SwingConstants.CENTER); + this.toggle3.setVerticalTextPosition(SwingConstants.BOTTOM); + + this.toggle4 = new JToggleButton("Toggle 4"); + this.toggle4.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); + this.toggle4.setText(null); + + ButtonGroup toggleGroup = new ButtonGroup(); + toggleGroup.add(toggle1); + toggleGroup.add(toggle2); + toggleGroup.add(toggle3); + toggleGroup.add(toggle4); + + buttonPanel.add(toggle1); + buttonPanel.add(toggle2); + buttonPanel.add(toggle3); + buttonPanel.add(toggle4); + + panel.add(buttonPanel); + + return panel; + } + + private JPanel createCheckBoxPanel() + { + JPanel panel = new JPanel(new BorderLayout()); + + this.checkBoxState = new JCheckBox("Enabled", true); + this.checkBoxState.setActionCommand("CHECKBOX_STATE"); + this.checkBoxState.addActionListener(this); + + panel.add(this.checkBoxState, BorderLayout.EAST); + + JPanel buttonPanel = new JPanel(); + buttonPanel.setBorder(BorderFactory.createTitledBorder("JCheckBox")); + this.checkBox1 = new JCheckBox("CheckBox 1"); + + this.checkBox2 = new JCheckBox("CheckBox 2"); + + this.checkBox3 = new JCheckBox("CheckBox 3"); + + buttonPanel.add(checkBox1); + buttonPanel.add(checkBox2); + buttonPanel.add(checkBox3); + + panel.add(buttonPanel); + + return panel; + } + + private JPanel createRadioPanel() + { + JPanel panel = new JPanel(new BorderLayout()); + + this.radioState = new JCheckBox("Enabled", true); + this.radioState.setActionCommand("RADIO_STATE"); + this.radioState.addActionListener(this); + panel.add(this.radioState, BorderLayout.EAST); + + JPanel buttonPanel = new JPanel(); + buttonPanel.setBorder(BorderFactory.createTitledBorder("JRadioButton")); + this.radio1 = new JRadioButton("Radio 1"); + + this.radio2 = new JRadioButton("Radio 2"); + + this.radio3 = new JRadioButton("Radio 3"); + + ButtonGroup radioGroup = new ButtonGroup(); + radioGroup.add(radio1); + radioGroup.add(radio2); + radioGroup.add(radio3); + + buttonPanel.add(radio1); + buttonPanel.add(radio2); + buttonPanel.add(radio3); + + panel.add(buttonPanel); + + return panel; + } + + public void actionPerformed(ActionEvent e) + { + if (e.getActionCommand().equals("BUTTON_STATE")) + { + button1.setEnabled(buttonState.isSelected()); + button2.setEnabled(buttonState.isSelected()); + button3.setEnabled(buttonState.isSelected()); + button4.setEnabled(buttonState.isSelected()); + } + else if (e.getActionCommand().equals("TOGGLE_STATE")) + { + toggle1.setEnabled(toggleState.isSelected()); + toggle2.setEnabled(toggleState.isSelected()); + toggle3.setEnabled(toggleState.isSelected()); + toggle4.setEnabled(toggleState.isSelected()); + } + else if (e.getActionCommand().equals("CHECKBOX_STATE")) + { + checkBox1.setEnabled(checkBoxState.isSelected()); + checkBox2.setEnabled(checkBoxState.isSelected()); + checkBox3.setEnabled(checkBoxState.isSelected()); + } + else if (e.getActionCommand().equals("RADIO_STATE")) + { + radio1.setEnabled(radioState.isSelected()); + radio2.setEnabled(radioState.isSelected()); + radio3.setEnabled(radioState.isSelected()); + } + else if (e.getActionCommand().equals("CLOSE")) + { + System.exit(0); + } + } + + public static void main(String[] args) + { + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + ButtonDemo app = new ButtonDemo(); + app.initFrameContent(); + JFrame frame = new JFrame("ButtonDemo"); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + } + }); + } + + /** + * Returns a DemoFactory that creates a ButtonDemo. + * + * @return a DemoFactory that creates a ButtonDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new ButtonDemo(); + } + }; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/ComboBoxDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/ComboBoxDemo.java new file mode 100644 index 000000000..682af0bdd --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/ComboBoxDemo.java @@ -0,0 +1,386 @@ +/* ComboBoxDemo.java -- An example showing various combo boxes in Swing. + Copyright (C) 2005, 2006, Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. +*/ + + +package gnu.classpath.examples.swing; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.BorderFactory; +import javax.swing.DefaultListCellRenderer; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; +import javax.swing.plaf.metal.MetalIconFactory; + +/** + * A simple demo showing various combo boxes in different states. + */ +public class ComboBoxDemo + extends JPanel + implements ActionListener +{ + + class CustomCellRenderer extends DefaultListCellRenderer + { + public Component getListCellRendererComponent(JList list, + Object value, + int index, + boolean isSelected, + boolean cellHasFocus) + { + DefaultListCellRenderer result = (DefaultListCellRenderer) + super.getListCellRendererComponent(list, value, index, isSelected, + cellHasFocus); + Icon icon = (Icon) value; + result.setIcon(icon); + result.setText("Index = " + index); + return result; + } + } + + private JCheckBox comboState1; + private JComboBox combo1; + private JComboBox combo2; + + private JCheckBox comboState2; + private JComboBox combo3; + private JComboBox combo4; + + private JCheckBox comboState3; + private JComboBox combo5; + private JComboBox combo6; + + private JCheckBox comboState4; + private JComboBox combo7; + private JComboBox combo8; + + private JCheckBox comboState5; + private JComboBox combo9; + private JComboBox combo10; + + private JCheckBox comboState6; + private JComboBox combo11; + private JComboBox combo12; + + /** + * Creates a new demo instance. + */ + public ComboBoxDemo() + { + super(); + createContent(); + } + + /** + * When the demo is run independently, the frame is displayed, so we should + * initialise the content panel (including the demo content and a close + * button). But when the demo is run as part of the Swing activity board, + * only the demo content panel is used, the frame itself is never displayed, + * so we can avoid this step. + */ + void initFrameContent() + { + JPanel closePanel = new JPanel(); + JButton closeButton = new JButton("Close"); + closeButton.setActionCommand("CLOSE"); + closeButton.addActionListener(this); + closePanel.add(closeButton); + add(closePanel, BorderLayout.SOUTH); + } + + /** + * Returns a panel with the demo content. The panel + * uses a BorderLayout(), and the BorderLayout.SOUTH area + * is empty, to allow callers to add controls to the + * bottom of the panel if they want to (a close button is + * added if this demo is being run as a standalone demo). + */ + private void createContent() + { + setLayout(new BorderLayout()); + JPanel panel = new JPanel(new GridLayout(6, 1)); + panel.add(createPanel1()); + panel.add(createPanel2()); + panel.add(createPanel3()); + panel.add(createPanel4()); + panel.add(createPanel5()); + panel.add(createPanel6()); + add(panel); + } + + private JPanel createPanel1() + { + JPanel panel = new JPanel(new BorderLayout()); + this.comboState1 = new JCheckBox("Enabled", true); + this.comboState1.setActionCommand("COMBO_STATE1"); + this.comboState1.addActionListener(this); + panel.add(this.comboState1, BorderLayout.EAST); + + JPanel controlPanel = new JPanel(); + controlPanel.setBorder(BorderFactory.createTitledBorder("Regular: ")); + this.combo1 = new JComboBox(new Object[] {"Australia", "New Zealand", + "England"}); + + this.combo2 = new JComboBox(new Object[] {"Australia", "New Zealand", + "England"}); + this.combo2.setEditable(true); + + controlPanel.add(combo1); + controlPanel.add(combo2); + + panel.add(controlPanel); + + return panel; + } + + private JPanel createPanel2() + { + JPanel panel = new JPanel(new BorderLayout()); + this.comboState2 = new JCheckBox("Enabled", true); + this.comboState2.setActionCommand("COMBO_STATE2"); + this.comboState2.addActionListener(this); + panel.add(this.comboState2, BorderLayout.EAST); + + JPanel controlPanel = new JPanel(); + controlPanel.setBorder(BorderFactory.createTitledBorder("Large Font: ")); + this.combo3 = new JComboBox(new Object[] {"Australia", "New Zealand", + "England"}); + this.combo3.setFont(new Font("Dialog", Font.PLAIN, 20)); + + this.combo4 = new JComboBox(new Object[] {"Australia", "New Zealand", + "England"}); + this.combo4.setEditable(true); + this.combo4.setFont(new Font("Dialog", Font.PLAIN, 20)); + + controlPanel.add(combo3); + controlPanel.add(combo4); + + panel.add(controlPanel); + + return panel; + } + + private JPanel createPanel3() + { + JPanel panel = new JPanel(new BorderLayout()); + this.comboState3 = new JCheckBox("Enabled", true); + this.comboState3.setActionCommand("COMBO_STATE3"); + this.comboState3.addActionListener(this); + panel.add(this.comboState3, BorderLayout.EAST); + + JPanel controlPanel = new JPanel(); + controlPanel.setBorder(BorderFactory.createTitledBorder("Colored Background: ")); + this.combo5 = new JComboBox(new Object[] {"Australia", "New Zealand", + "England"}); + this.combo5.setBackground(Color.yellow); + + this.combo6 = new JComboBox(new Object[] {"Australia", "New Zealand", + "England"}); + this.combo6.setEditable(true); + this.combo6.setBackground(Color.yellow); + + controlPanel.add(combo5); + controlPanel.add(combo6); + + panel.add(controlPanel); + + return panel; + } + + /** + * This panel contains combo boxes that are empty. + * + * @return A panel. + */ + private JPanel createPanel4() + { + JPanel panel = new JPanel(new BorderLayout()); + this.comboState4 = new JCheckBox("Enabled", true); + this.comboState4.setActionCommand("COMBO_STATE4"); + this.comboState4.addActionListener(this); + panel.add(this.comboState4, BorderLayout.EAST); + + JPanel controlPanel = new JPanel(); + controlPanel.setBorder(BorderFactory.createTitledBorder("Empty: ")); + this.combo7 = new JComboBox(); + this.combo8 = new JComboBox(); + this.combo8.setEditable(true); + + controlPanel.add(combo7); + controlPanel.add(combo8); + + panel.add(controlPanel); + + return panel; + } + + /** + * This panel contains combo boxes that are narrow but contain long text + * items. + * + * @return A panel. + */ + private JPanel createPanel5() + { + JPanel panel = new JPanel(new BorderLayout()); + this.comboState5 = new JCheckBox("Enabled", true); + this.comboState5.setActionCommand("COMBO_STATE5"); + this.comboState5.addActionListener(this); + panel.add(this.comboState5, BorderLayout.EAST); + + JPanel controlPanel = new JPanel(); + controlPanel.setBorder(BorderFactory.createTitledBorder("Narrow: ")); + this.combo9 = new JComboBox(new Object[] { + "A really long item that will be truncated when displayed"}); + this.combo9.setPreferredSize(new Dimension(100, 30)); + this.combo10 = new JComboBox(new Object[] { + "A really long item that will be truncated when displayed"}); + this.combo10.setPreferredSize(new Dimension(100, 30)); + this.combo10.setEditable(true); + + controlPanel.add(combo9); + controlPanel.add(combo10); + + panel.add(controlPanel); + + return panel; + } + + /** + * This panel contains combo boxes with a custom renderer. + * + * @return A panel. + */ + private JPanel createPanel6() + { + JPanel panel = new JPanel(new BorderLayout()); + this.comboState6 = new JCheckBox("Enabled", true); + this.comboState6.setActionCommand("COMBO_STATE6"); + this.comboState6.addActionListener(this); + panel.add(this.comboState6, BorderLayout.EAST); + + JPanel controlPanel = new JPanel(); + controlPanel.setBorder(BorderFactory.createTitledBorder("Custom Renderer: ")); + this.combo11 = new JComboBox(new Object[] { + MetalIconFactory.getFileChooserHomeFolderIcon(), + MetalIconFactory.getFileChooserNewFolderIcon()}); + this.combo11.setPreferredSize(new Dimension(100, 30)); + this.combo11.setRenderer(new CustomCellRenderer()); + this.combo12 = new JComboBox(new Object[] { + MetalIconFactory.getFileChooserHomeFolderIcon(), + MetalIconFactory.getFileChooserNewFolderIcon()}); + this.combo12.setPreferredSize(new Dimension(100, 30)); + this.combo12.setRenderer(new CustomCellRenderer()); + this.combo12.setEditable(true); + + controlPanel.add(combo11); + controlPanel.add(combo12); + + panel.add(controlPanel); + + return panel; + } + + public void actionPerformed(ActionEvent e) + { + if (e.getActionCommand().equals("COMBO_STATE1")) + { + combo1.setEnabled(comboState1.isSelected()); + combo2.setEnabled(comboState1.isSelected()); + } + else if (e.getActionCommand().equals("COMBO_STATE2")) + { + combo3.setEnabled(comboState2.isSelected()); + combo4.setEnabled(comboState2.isSelected()); + } + else if (e.getActionCommand().equals("COMBO_STATE3")) + { + combo5.setEnabled(comboState3.isSelected()); + combo6.setEnabled(comboState3.isSelected()); + } + else if (e.getActionCommand().equals("COMBO_STATE4")) + { + combo7.setEnabled(comboState4.isSelected()); + combo8.setEnabled(comboState4.isSelected()); + } + else if (e.getActionCommand().equals("COMBO_STATE5")) + { + combo9.setEnabled(comboState5.isSelected()); + combo10.setEnabled(comboState5.isSelected()); + } + else if (e.getActionCommand().equals("COMBO_STATE6")) + { + combo11.setEnabled(comboState6.isSelected()); + combo12.setEnabled(comboState6.isSelected()); + } + else if (e.getActionCommand().equals("CLOSE")) + { + System.exit(0); + } + } + + public static void main(String[] args) + { + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + ComboBoxDemo app = new ComboBoxDemo(); + app.initFrameContent(); + JFrame frame = new JFrame(); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + } + }); + } + + /** + * Returns a DemoFactory that creates a ComboBoxDemo. + * + * @return a DemoFactory that creates a ComboBoxDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new ComboBoxDemo(); + } + }; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/Demo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/Demo.java new file mode 100644 index 000000000..772df6a3b --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/Demo.java @@ -0,0 +1,629 @@ +/* SwingDemo.java -- An example of using the javax.swing UI. + Copyright (C) 2003, 2004, 2005, 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. +*/ + + +package gnu.classpath.examples.swing; + +import gnu.classpath.examples.java2d.JNIOverhead; + +import java.awt.*; +import java.awt.event.*; + +import javax.swing.*; + +import javax.swing.plaf.basic.BasicLookAndFeel; +import javax.swing.plaf.metal.DefaultMetalTheme; +import javax.swing.plaf.metal.MetalLookAndFeel; +import javax.swing.plaf.metal.MetalTheme; +import javax.swing.plaf.metal.OceanTheme; + +import java.lang.reflect.Method; +import java.net.URL; + +public class Demo +{ + JFrame frame; + + /** + * The main desktop. This is package private to avoid synthetic accessor + * method. + */ + JDesktopPane desktop; + + /** + * The themes menu. This is implemented as a field so that the L&F switcher + * can disable the menu when a non-Metal L&F is selected. + */ + JMenu themesMenu; + + static Color blueGray = new Color(0xdc, 0xda, 0xd5); + + private static Icon stockIcon(String s) + { + return getIcon("/gnu/classpath/examples/icons/stock-" + s + ".png", s); + } + + static Icon bigStockIcon(String s) + { + return getIcon("/gnu/classpath/examples/icons/big-" + s + ".png", s); + } + + static Icon getIcon(String location, String name) + { + URL url = Demo.class.getResource(location); + if (url == null) System.err.println("WARNING " + location + " not found."); + return new ImageIcon(url, name); + } + + private JMenuBar mkMenuBar() + { + JMenuBar bar = new JMenuBar(); + + JMenu file = new JMenu("File"); + JMenu edit = new JMenu("Edit"); + JMenu help = new JMenu("Help"); + + file.setMnemonic(KeyEvent.VK_F); + edit.setMnemonic(KeyEvent.VK_E); + help.setMnemonic(KeyEvent.VK_H); + + file.add(new JMenuItem("New", stockIcon("new"))); + file.add(new JMenuItem("Open", stockIcon("open"))); + + JMenu recent = new JMenu("Recent Files..."); + recent.add(new JMenuItem("war-and-peace.txt")); + recent.add(new JMenuItem("taming-of-shrew.txt")); + recent.add(new JMenuItem("sun-also-rises.txt")); + file.add(recent); + file.add(new JMenuItem("Save", stockIcon("save"))); + file.add(new JMenuItem("Save as...", stockIcon("save-as"))); + + JMenuItem exit = new JMenuItem("Exit", stockIcon("quit")); + exit.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + System.exit(1); + } + }); + + file.add(exit); + + edit.add(new JMenuItem("Cut", stockIcon("cut"))); + edit.add(new JMenuItem("Copy", stockIcon("copy"))); + edit.add(new JMenuItem("Paste", stockIcon("paste"))); + + JMenu preferences = new JMenu("Preferences..."); + preferences.add(new JCheckBoxMenuItem("Microphone Active", + stockIcon("mic"))); + preferences.add(new JCheckBoxMenuItem("Check Spelling", + stockIcon("spell-check"))); + preferences.add(new JCheckBoxMenuItem("World Peace")); + preferences.add(new JSeparator()); + preferences.add(new JRadioButtonMenuItem("Radio Button")); + edit.add(preferences); + + JMenu examples = new JMenu("Examples"); + examples.add(new JMenuItem(new PopupAction("Buttons", + ButtonDemo.createDemoFactory()))); + examples.add(new JMenuItem(new PopupAction("Slider", + SliderDemo.createDemoFactory()))); + examples.add(new JMenuItem(new PopupAction("ProgressBar", + ProgressBarDemo.createDemoFactory()))); + examples.add(new JMenuItem(new PopupAction("Scrollbar", + ScrollBarDemo.createDemoFactory()))); + examples.add(new JMenuItem(new PopupAction("Spinner", + SpinnerDemo.createDemoFactory()))); + examples.add(new JMenuItem(new PopupAction("TextField", + TextFieldDemo.createDemoFactory()))); + examples.add(new JMenuItem(new PopupAction("TextArea", + TextAreaDemo.createDemoFactory()))); + examples.add(new JMenuItem(new PopupAction("FileChooser", + FileChooserDemo.createDemoFactory()))); + + examples.add(new JMenuItem(new PopupAction("ComboBox", + ComboBoxDemo.createDemoFactory()))); + + examples.add(new JMenuItem(new PopupAction("Table", + TableDemo.createDemoFactory()))); + examples.add(new JMenuItem(new PopupAction("List", + ListDemo.createDemoFactory()))); + examples.add(new JMenuItem(new PopupAction("TabbedPane", + TabbedPaneDemo.createDemoFactory()))); + examples.add(new JMenuItem(new PopupAction("Tree", + TreeDemo.createDemoFactory()))); + examples.add(new JMenuItem(new PopupAction("Theme Editor", + MetalThemeEditor.createDemoFactory()))); + + examples.add(new JMenuItem(new PopupAction("DocumentFilter", + DocumentFilterDemo.createDemoFactory()))); + + examples.add(new JMenuItem(new PopupAction("NavigationFilter", + NavigationFilterDemo.createDemoFactory()))); + examples.add(new JMenuItem(new PopupAction("JNI Overhead", + JNIOverhead.createDemoFactory()))); + examples.add(new JMenuItem(new PopupAction("HTML Demo", + HtmlDemo.createDemoFactory()))); + + + final JMenuItem vmMenu; + + help.add(new JMenuItem("just play with the widgets")); + help.add(new JMenuItem("and enjoy the sensation of")); + help.add(new JMenuItem("your neural connections growing")); + help.add(new JSeparator()); + help.add(vmMenu = new JMenuItem("Really, which VM is this running on?")); + vmMenu.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent ae) + { + String message = "This is " + + System.getProperty("java.vm.name") + + " Version " + + System.getProperty("java.vm.version") + + " distributed by " + + System.getProperty("java.vm.vendor") + + "."; + + String gnuClasspath = System.getProperty("gnu.classpath.version"); + if(gnuClasspath != null) + message += "\nThe runtime's libraries are " + + "kindly provided by the " + + "members of GNU Classpath and are in version " + + gnuClasspath + "."; + + JOptionPane.showMessageDialog(vmMenu, message); + } + }); + + // Installs the BasicLookAndFeel. + UIManager.installLookAndFeel("(Basic Look And Feel)", + InstantiableBasicLookAndFeel.class.getName()); + + // Create L&F menu. + JMenu lafMenu = new JMenu("Look and Feel"); + ButtonGroup lafGroup = new ButtonGroup(); + UIManager.LookAndFeelInfo[] lafs = UIManager.getInstalledLookAndFeels(); + String currentLaf = UIManager.getLookAndFeel().getClass().getName(); + for (int i = 0; i < lafs.length; ++i) + { + UIManager.LookAndFeelInfo laf = lafs[i]; + ChangeLAFAction action = new ChangeLAFAction(laf); + JRadioButtonMenuItem lafItem = new JRadioButtonMenuItem(action); + boolean selected = laf.getClassName().equals(currentLaf); + lafItem.setSelected(selected); + lafMenu.add(lafItem); + + lafGroup.add(lafItem); + } + + // Create themes menu. + themesMenu = new JMenu("Themes"); + ButtonGroup themesGroup = new ButtonGroup(); + + // In order to make the demo runable on a 1.4 type VM we have to avoid calling + // MetalLookAndFeel.getCurrentTheme(). We simply check whether this method exists + // and is public. + Method m = null; + try + { + m = MetalLookAndFeel.class.getMethod("getCurrentTheme", null); + } + catch (NoSuchMethodException nsme) + { + // Ignore it. + } + + if (m != null) + { + JRadioButtonMenuItem ocean = + new JRadioButtonMenuItem(new ChangeThemeAction(new OceanTheme())); + ocean.setSelected(MetalLookAndFeel.getCurrentTheme() instanceof OceanTheme); + themesMenu.add(ocean); + themesGroup.add(ocean); + + JRadioButtonMenuItem steel = + new JRadioButtonMenuItem(new ChangeThemeAction(new DefaultMetalTheme())); + ocean.setSelected(MetalLookAndFeel.getCurrentTheme() + instanceof DefaultMetalTheme); + themesMenu.add(steel); + themesGroup.add(steel); + } + else + { + themesMenu.setEnabled(false); + } + + bar.add(file); + bar.add(edit); + bar.add(examples); + bar.add(lafMenu); + bar.add(themesMenu); + bar.add(help); + return bar; + } + + private static void triggerDialog(final JButton but, final String dir) + { + but.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + JOptionPane.showConfirmDialog(but, + "Sure you want to go " + dir + "?", + "Confirm", + JOptionPane.OK_CANCEL_OPTION, + JOptionPane.QUESTION_MESSAGE, + bigStockIcon("warning")); + } + }); + } + + static JToolBar mkToolBar() + { + JToolBar bar = new JToolBar(); + + JButton b = mkButton(stockIcon("go-back")); + triggerDialog(b, "back"); + bar.add(b); + + b = mkButton(stockIcon("go-down")); + triggerDialog(b, "down"); + bar.add(b); + + b = mkButton(stockIcon("go-forward")); + triggerDialog(b, "forward"); + bar.add(b); + return bar; + } + + static String halign2str(int a) + { + switch (a) + { + case SwingConstants.CENTER: + return "Center"; + case SwingConstants.RIGHT: + return "Right"; + case SwingConstants.LEFT: + return "Left"; + default: + return "Unknown"; + } + } + + private static JButton mkButton(String title, Icon icon, + int hAlign, int vAlign, + int hPos, int vPos) + { + JButton b; + if (icon == null) + b = new JButton(title); + else if (title == null) + b = new JButton(icon); + else + b = new JButton(title, icon); + + b.setToolTipText(title); + if (hAlign != -1) b.setHorizontalAlignment(hAlign); + if (vAlign != -1) b.setVerticalAlignment(vAlign); + if (hPos != -1) b.setHorizontalTextPosition(hPos); + if (vPos != -1) b.setVerticalTextPosition(vPos); + return b; + } + + static JButton mkButton(String title) + { + return mkButton(title, null, -1, -1, -1, -1); + } + + static JButton mkButton(Icon i) + { + return mkButton(null, i, -1, -1, -1, -1); + } + + public Demo() + { + frame = new JFrame("Swing Activity Board"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setJMenuBar(mkMenuBar()); + JComponent component = (JComponent) frame.getContentPane(); + component.setLayout(new BorderLayout()); + component.add(mkToolBar(), BorderLayout.NORTH); + JPanel main = new JPanel(); + main.setLayout(new BoxLayout(main, BoxLayout.Y_AXIS)); + desktop = createDesktop(); + main.add(desktop); + main.add(mkButtonBar()); + component.add(main, BorderLayout.CENTER); + frame.pack(); + frame.show(); + } + + public static class LaterMain + implements Runnable + { + public void run() + { + new Demo(); + } + } + + public static void main(String args[]) + { + SwingUtilities.invokeLater(new LaterMain()); + } + + private static JButton mkBigButton(String title) + { + JButton b = new JButton(title); + b.setMargin(new Insets(5,5,5,5)); + return b; + } + + static JButton mkDisposerButton(final JFrame c) + { + JButton close = mkBigButton("Close"); + close.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + c.dispose(); + } + }); + return close; + } + + public static JColorChooser mkColorChooser() + { + return new JColorChooser(); + } + + /** + * This action brings up a new Window with the specified content. + */ + private class PopupAction + extends AbstractAction + { + /** + * The component to be shown. + */ + private DemoFactory demoFactory; + + /** + * Creates a new PopupAction with the specified name and showing the + * component created by the specified DemoFactory when activated. + * + * @param n the name of the action + * @param factory the demo factory + */ + PopupAction(String n, DemoFactory factory) + { + putValue(NAME, n); + demoFactory = factory; + } + + /** + * Brings up the new window showing the component stored in the + * constructor. + * + * @param e the action event that triggered the action + */ + public void actionPerformed(ActionEvent e) + { + JInternalFrame frame = new JInternalFrame((String) getValue(NAME)); + frame.setClosable(true); + frame.setIconifiable(true); + frame.setMaximizable(true); + frame.setResizable(true); + frame.setContentPane(demoFactory.createDemo()); + frame.pack(); + desktop.add(frame); + frame.setVisible(true); + } + } + + private JPanel mkButtonBar() + { + JPanel panel = new JPanel(new GridLayout(3, 1, 5, 5)); + panel.add(new JButton(new PopupAction("Buttons", + ButtonDemo.createDemoFactory()))); + panel.add(new JButton(new PopupAction("Slider", + SliderDemo.createDemoFactory()))); + panel.add(new JButton(new PopupAction("ProgressBar", + ProgressBarDemo.createDemoFactory()))); + panel.add(new JButton(new PopupAction("ScrollBar", + ScrollBarDemo.createDemoFactory()))); + panel.add(new JButton(new PopupAction("Spinner", + SpinnerDemo.createDemoFactory()))); + panel.add(new JButton(new PopupAction("TextField", + TextFieldDemo.createDemoFactory()))); + panel.add(new JButton(new PopupAction("TextArea", + TextAreaDemo.createDemoFactory()))); + panel.add(new JButton(new PopupAction("FileChooser", + FileChooserDemo.createDemoFactory()))); + panel.add(new JButton(new PopupAction("ComboBox", + ComboBoxDemo.createDemoFactory()))); + panel.add(new JButton(new PopupAction("Table", + TableDemo.createDemoFactory()))); + panel.add(new JButton(new PopupAction("List", + ListDemo.createDemoFactory()))); + panel.add(new JButton(new PopupAction("TabbedPane", + TabbedPaneDemo.createDemoFactory()))); + panel.add(new JButton(new PopupAction("Tree", + TreeDemo.createDemoFactory()))); + panel.add(new JButton(new PopupAction("Theme Editor", + MetalThemeEditor.createDemoFactory()))); + panel.add(new JButton(new PopupAction("JNI Overhead", + JNIOverhead.createDemoFactory()))); + panel.add(new JButton(new PopupAction("HTML", + HtmlDemo.createDemoFactory()))); + + JButton exitDisposer = mkDisposerButton(frame); + panel.add(exitDisposer); + + panel.setMaximumSize(new Dimension(Integer.MAX_VALUE, + panel.getPreferredSize().height)); + exitDisposer.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + System.exit(1); + } + }); + return panel; + } + + /** + * Creates and returns the main desktop. + * + * @return the main desktop + */ + private JDesktopPane createDesktop() + { + JDesktopPane d = new DemoDesktop(); + d.setPreferredSize(new Dimension(900, 500)); + return d; + } + + /** + * This Action is used to switch Metal themes. + */ + class ChangeThemeAction extends AbstractAction + { + /** + * The theme to switch to. + */ + MetalTheme theme; + + /** + * Creates a new ChangeThemeAction for the specified theme. + * + * @param t the theme to switch to + */ + ChangeThemeAction(MetalTheme t) + { + theme = t; + putValue(NAME, t.getName()); + } + + /** + * Changes the theme to the one specified in the constructor. + * + * @param event the action event that triggered this action + */ + public void actionPerformed(ActionEvent event) + { + MetalLookAndFeel.setCurrentTheme(theme); + try + { + // Only switch theme if we have a metal L&F. It is still necessary + // to install a new MetalLookAndFeel instance. + if (UIManager.getLookAndFeel() instanceof MetalLookAndFeel) + UIManager.setLookAndFeel(new MetalLookAndFeel()); + } + catch (UnsupportedLookAndFeelException ex) + { + ex.printStackTrace(); + } + SwingUtilities.updateComponentTreeUI(frame); + } + + } + + /** + * This Action is used to switch Metal themes. + */ + class ChangeLAFAction extends AbstractAction + { + /** + * The theme to switch to. + */ + private UIManager.LookAndFeelInfo laf; + + /** + * Creates a new ChangeLAFAction for the specified L&F. + * + * @param l the L&F to switch to + */ + ChangeLAFAction(UIManager.LookAndFeelInfo l) + { + laf = l; + putValue(NAME, laf.getName()); + } + + /** + * Changes the theme to the one specified in the constructor. + * + * @param event the action event that triggered this action + */ + public void actionPerformed(ActionEvent event) + { + try + { + UIManager.setLookAndFeel(laf.getClassName()); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + + SwingUtilities.updateComponentTreeUI(frame); + themesMenu.setEnabled(laf.getClassName() + .equals("javax.swing.plaf.metal.MetalLookAndFeel")); + } + } + + /** + * An implementation of BasicLookAndFeel which can be instantiated. + * + * @author Robert Schuster (robertschuster@fsfe.org) + * + */ + public static class InstantiableBasicLookAndFeel extends BasicLookAndFeel + { + public String getDescription() + { + return "An instantiable implementation of BasicLookAndFeel"; + } + + public String getID() + { + return "instantiableBasicLookAndFeel"; + } + + public String getName() + { + return "Instantiable Basic Look And Feel"; + } + + public boolean isNativeLookAndFeel() + { + return false; + } + + public boolean isSupportedLookAndFeel() + { + return true; + } + } + +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/DemoDesktop.java b/libjava/classpath/examples/gnu/classpath/examples/swing/DemoDesktop.java new file mode 100644 index 000000000..edfaf36b2 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/DemoDesktop.java @@ -0,0 +1,82 @@ +/* DemoDesktop.java -- A custom desktop for the demo + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.swing; + +import java.awt.Graphics; + +import javax.swing.ImageIcon; +import javax.swing.JDesktopPane; + +/** + * A customized Desktop for the GNU Classpath Swing demo that paints the + * GNU Classpath Icon in the middle of the desktop. + * + * @author Roman Kennke (kennke@aicas.com) + */ +public class DemoDesktop + extends JDesktopPane +{ + + /** + * The icon that's painted centered on the desktop. + */ + private ImageIcon image; + + /** + * Creates a new desktop. + */ + DemoDesktop() + { + super(); + String badge = "/gnu/classpath/examples/icons/badge.png"; + image = new ImageIcon(getClass().getResource(badge)); + } + + /** + * Paints the desktop including the icon. + * + * @param g the graphics to use for painting + */ + protected void paintComponent(Graphics g) + { + super.paintComponent(g); + image.paintIcon(this, g, (getWidth() - image.getIconWidth()) / 2, + (getHeight() - image.getIconHeight()) / 2); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/DemoFactory.java b/libjava/classpath/examples/gnu/classpath/examples/swing/DemoFactory.java new file mode 100644 index 000000000..0bbd0220a --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/DemoFactory.java @@ -0,0 +1,57 @@ +/* DemoFactory.java -- Creates components used as separate Swing demos + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.swing; + +import javax.swing.JComponent; + +/** + * Creates components used in the Swing demo as separate demos. + * + * @author Roman Kennke (kennke@aicas.de) + */ +public interface DemoFactory +{ + + /** + * Creates the component that should be as demo application. + * + * @return the component that should be as demo application + */ + JComponent createDemo(); +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/DocumentFilterDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/DocumentFilterDemo.java new file mode 100644 index 000000000..58db99110 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/DocumentFilterDemo.java @@ -0,0 +1,288 @@ +/* DpocumentFilterDemo.java -- An example for the DocumentFilter class. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. +*/ + + +package gnu.classpath.examples.swing; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.GridLayout; +import java.awt.Toolkit; +import java.awt.datatransfer.Clipboard; +import java.awt.datatransfer.StringSelection; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.SwingUtilities; +import javax.swing.text.AbstractDocument; +import javax.swing.text.AttributeSet; +import javax.swing.text.BadLocationException; +import javax.swing.text.DocumentFilter; + +/** + * A demonstration of the javax.swing.text.DocumentFilter class. + * + *

Similar to a dialog in a popular programming IDE the user can insert + * a CVS URL into a textfield and the filter will split the components apart + * and will put them into the right textfields saving the user a lot of + * typing time.

+ * + * @author Robert Schuster + */ +public class DocumentFilterDemo + extends JPanel + implements ActionListener +{ + JTextField target; + + JTextField host; + JTextField repositoryPath; + JTextField user; + JTextField password; + JComboBox connectionType; + + /** + * Creates a new demo instance. + */ + public DocumentFilterDemo() + { + createContent(); + // initFrameContent() is only called (from main) when running this app + // standalone + } + + /** + * When the demo is run independently, the frame is displayed, so we should + * initialise the content panel (including the demo content and a close + * button). But when the demo is run as part of the Swing activity board, + * only the demo content panel is used, the frame itself is never displayed, + * so we can avoid this step. + */ + void initFrameContent() + { + JPanel closePanel = new JPanel(); + JButton closeButton = new JButton("Close"); + closeButton.setActionCommand("CLOSE"); + closeButton.addActionListener(this); + closePanel.add(closeButton); + add(closePanel, BorderLayout.SOUTH); + } + + private void createContent() + { + setLayout(new BorderLayout()); + + JPanel panel = new JPanel(new GridLayout(7, 2)); + panel.add(new JLabel("CVS URL:")); + panel.add(target = new JTextField(20)); + target.setBackground(Color.RED); + + panel.add(new JLabel("Host:")); + panel.add(host = new JTextField(20)); + + panel.add(new JLabel("Repository Path:")); + panel.add(repositoryPath = new JTextField(20)); + + panel.add(new JLabel("Username:")); + panel.add(user = new JTextField(20)); + + panel.add(new JLabel("Password:")); + panel.add(password = new JTextField(20)); + + panel.add(new JLabel("Connection Type:")); + panel.add(connectionType = new JComboBox()); + + JButton helpButton = new JButton("Help"); + panel.add(helpButton); + + helpButton.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent ae) + { + JOptionPane.showMessageDialog(DocumentFilterDemo.this, + "Paste a CVS URL into the red " + + "textfield.\nIf you do not want to " + + "look up a CVS URL yourself click " + + "on the 'provide me an example' " + + "button.\nThis will paste a proper " + + "string into your clipboard."); + } + }); + + JButton exampleButton = new JButton("Provide me an example!"); + panel.add(exampleButton); + exampleButton.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent ae) + { + try + { + Toolkit tk = Toolkit.getDefaultToolkit(); + Clipboard cb = tk.getSystemSelection(); + StringSelection selection + = new StringSelection(":extssh:gnu@cvs.savannah.gnu.org:" + + "/cvs/example/project"); + + cb.setContents(selection, selection); + + // Confirm success with a beep. + tk.beep(); + } + catch (IllegalStateException ise) + { + JOptionPane.showMessageDialog(DocumentFilterDemo.this, + "Clipboard is currently" + + " unavailable.", + "Error", + JOptionPane.ERROR_MESSAGE); + } + } + }); + + connectionType.addItem("pserver"); + connectionType.addItem("ext"); + connectionType.addItem("extssh"); + + add(panel); + + AbstractDocument doc = (AbstractDocument) target.getDocument(); + doc.setDocumentFilter(new CVSFilter()); + } + + public void actionPerformed(ActionEvent e) + { + if (e.getActionCommand().equals("CLOSE")) + System.exit(0); + + } + + public static void main(String[] args) + { + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + DocumentFilterDemo app = new DocumentFilterDemo(); + app.initFrameContent(); + JFrame frame = new JFrame("DocumentFilterDemo"); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + } + }); + } + + /** + * Returns a DemoFactory that creates a DocumentFilterDemo. + * + * @return a DemoFactory that creates a DocumentFilterDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new DocumentFilterDemo(); + } + }; + } + + class CVSFilter extends DocumentFilter + { + // example: pserver:anonymous@cvs.sourceforge.net:/cvsroot/fmj + String cvsPattern = ":?(pserver|ext|extssh):(\\w)+(:(\\w)+)?@(\\w|\\.)+:/(\\w|/)*"; + + public void insertString(DocumentFilter.FilterBypass fb, + int offset, String string, + AttributeSet attr) + throws BadLocationException + { + filterString(fb, offset, 0, string, attr, true); + } + + public void replace(DocumentFilter.FilterBypass fb, + int offset, int length, + String string, + AttributeSet attr) + throws BadLocationException + { + filterString(fb, offset, length, string, attr, false); + } + + public void filterString(DocumentFilter.FilterBypass fb, + int offset, int length, String string, + AttributeSet attr, boolean insertion) + throws BadLocationException + { + if(string.matches(cvsPattern)) + { + // Split off the connection type part. + String[] result = string.split(":", 2); + + // If the string contained a leading colon, result[0] + // will be empty at that point. We simply repeat the split + // operation on the remaining string and continue. + if(result[0].equals("")) + result = result[1].split(":", 2); + + connectionType.setSelectedItem(result[0]); + + // Split off the username and password part + result = result[1].split("@", 2); + + // Break username and password in half + String[] userCredentials = result[0].split(":"); + user.setText(userCredentials[0]); + + // If the result has two entries the second one will + // be the password. + if (userCredentials.length == 2) + password.setText(userCredentials[1]); + + // Now break the host part apart. + result = result[1].split(":"); + + host.setText(result[0]); + + repositoryPath.setText(result[1]); + } + + // The unmodified string is put into the document. + if (insertion) + fb.insertString(offset, string, attr); + else + fb.replace(offset, length, string, attr); + } + + } + +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/FileChooserDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/FileChooserDemo.java new file mode 100644 index 000000000..444453bf5 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/FileChooserDemo.java @@ -0,0 +1,264 @@ +/* FileChooserDemo.java -- An example showing file choosers in Swing. + Copyright (C) 2005, 2006, Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. +*/ + +package gnu.classpath.examples.swing; + +import java.awt.BorderLayout; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; + +import javax.swing.BorderFactory; +import javax.swing.DefaultListModel; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JFileChooser; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.SwingUtilities; +import javax.swing.filechooser.FileFilter; + +/** + * A simple demo showing the {@link JFileChooser} component used in different + * ways. + */ +public class FileChooserDemo + extends JPanel + implements ActionListener +{ + /** + * A file filter for Java source files. + */ + static class JavaFileFilter extends FileFilter + { + public String getDescription() + { + return "Java Source Files (.java)"; + } + public boolean accept(File f) + { + if (f != null) + { + return f.getName().endsWith(".java") || f.isDirectory(); + } + else + return false; + } + } + + /** A label to display the selected file. */ + JLabel selectedFileLabel; + + /** + * A list showing the selected files (where multi selections are + * allowed). + */ + JList selectedFilesList; + + /** A label to display the return code for the JFileChooser. */ + JLabel returnCodeLabel; + + /** + * Creates a new demo instance. + */ + public FileChooserDemo() + { + super(); + createContent(); + } + + /** + * When the demo is run independently, the frame is displayed, so we should + * initialise the content panel (including the demo content and a close + * button). But when the demo is run as part of the Swing activity board, + * only the demo content panel is used, the frame itself is never displayed, + * so we can avoid this step. + */ + void initFrameContent() + { + JPanel closePanel = new JPanel(); + JButton closeButton = new JButton("Close"); + closeButton.setActionCommand("CLOSE"); + closeButton.addActionListener(this); + closePanel.add(closeButton); + add(closePanel, BorderLayout.SOUTH); + } + + /** + * Returns a panel with the demo content. The panel + * uses a BorderLayout(), and the BorderLayout.SOUTH area + * is empty, to allow callers to add controls to the + * bottom of the panel if they want to (a close button is + * added if this demo is being run as a standalone demo). + */ + private void createContent() + { + setLayout(new BorderLayout()); + + // create a panel of buttons to select the different styles of file + // chooser... + JPanel buttonPanel = new JPanel(new GridLayout(5, 1)); + JButton openButton = new JButton("Open..."); + openButton.setActionCommand("OPEN"); + openButton.addActionListener(this); + buttonPanel.add(openButton); + JButton saveButton = new JButton("Save..."); + saveButton.setActionCommand("SAVE"); + saveButton.addActionListener(this); + buttonPanel.add(saveButton); + JButton queryButton = new JButton("Select Directory..."); + queryButton.setActionCommand("SELECT_DIRECTORY"); + queryButton.addActionListener(this); + buttonPanel.add(queryButton); + JButton openJavaButton = new JButton("Open Java file..."); + openJavaButton.setActionCommand("OPEN_JAVA"); + openJavaButton.addActionListener(this); + buttonPanel.add(openJavaButton); + JButton openMultiButton = new JButton("Open multiple files..."); + openMultiButton.setActionCommand("OPEN_MULTI"); + openMultiButton.addActionListener(this); + buttonPanel.add(openMultiButton); + add(buttonPanel, BorderLayout.WEST); + + // create a panel to display the selected file(s) and the return code + JPanel displayPanel = new JPanel(new BorderLayout()); + + selectedFileLabel = new JLabel("-"); + selectedFileLabel.setBorder(BorderFactory.createTitledBorder("Selected File/Directory: ")); + displayPanel.add(selectedFileLabel, BorderLayout.NORTH); + + selectedFilesList = new JList(); + JScrollPane sp = new JScrollPane(selectedFilesList); + sp.setBorder(BorderFactory.createTitledBorder("Selected Files: ")); + displayPanel.add(sp); + + returnCodeLabel = new JLabel("0"); + returnCodeLabel.setBorder(BorderFactory.createTitledBorder("Return Code:")); + displayPanel.add(returnCodeLabel, BorderLayout.SOUTH); + + add(displayPanel); + } + + /** + * When the user clicks on a button, launch the appropriate file chooser + * and report the results. + * + * @param e the event. + */ + public void actionPerformed(ActionEvent e) + { + int option = 0; + File selectedFile = null; + File[] selectedFiles = new File[0]; + + if (e.getActionCommand().equals("CLOSE")) + { + System.exit(0); + } + else if (e.getActionCommand().equals("OPEN")) + { + JFileChooser chooser = new JFileChooser(); + option = chooser.showOpenDialog(this); + selectedFile = chooser.getSelectedFile(); + selectedFiles = chooser.getSelectedFiles(); + } + else if (e.getActionCommand().equals("OPEN_MULTI")) + { + JFileChooser chooser = new JFileChooser(); + chooser.setMultiSelectionEnabled(true); + option = chooser.showOpenDialog(this); + selectedFile = chooser.getSelectedFile(); + selectedFiles = chooser.getSelectedFiles(); + } + else if (e.getActionCommand().equals("OPEN_JAVA")) + { + JFileChooser chooser = new JFileChooser(); + chooser.setAcceptAllFileFilterUsed(false); + chooser.setFileFilter(new JavaFileFilter()); + option = chooser.showOpenDialog(this); + selectedFile = chooser.getSelectedFile(); + selectedFiles = chooser.getSelectedFiles(); + } + else if (e.getActionCommand().equals("SAVE")) + { + JFileChooser chooser = new JFileChooser(); + option = chooser.showSaveDialog(this); + selectedFile = chooser.getSelectedFile(); + selectedFiles = chooser.getSelectedFiles(); + } + else if (e.getActionCommand().equals("SELECT_DIRECTORY")) + { + JFileChooser chooser = new JFileChooser(); + chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + option = chooser.showDialog(this, "Select"); + selectedFile = chooser.getSelectedFile(); + selectedFiles = chooser.getSelectedFiles(); + } + + // display the selection and return code + if (selectedFile != null) + selectedFileLabel.setText(selectedFile.toString()); + else + selectedFileLabel.setText("null"); + DefaultListModel listModel = new DefaultListModel(); + for (int i = 0; i < selectedFiles.length; i++) + listModel.addElement(selectedFiles[i]); + selectedFilesList.setModel(listModel); + returnCodeLabel.setText(Integer.toString(option)); + } + + public static void main(String[] args) + { + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + FileChooserDemo app = new FileChooserDemo(); + app.initFrameContent(); + JFrame frame = new JFrame("FileChooser Demo"); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + } + }); + } + + /** + * Returns a DemoFactory that creates a FileChooserDemo. + * + * @return a DemoFactory that creates a FileChooserDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new FileChooserDemo(); + } + }; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/HtmlDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/HtmlDemo.java new file mode 100644 index 000000000..20977b218 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/HtmlDemo.java @@ -0,0 +1,379 @@ +/* HtmlDemo.java -- HTML viewer demo + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.swing; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.util.LinkedList; + +import javax.swing.BoxLayout; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JEditorPane; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextField; +import javax.swing.JTextPane; +import javax.swing.JToolBar; +import javax.swing.SwingUtilities; +import javax.swing.event.HyperlinkEvent; +import javax.swing.event.HyperlinkListener; +import javax.swing.text.html.FormSubmitEvent; + +/** + * Parses and displays HTML content. + * + * @author Audrius Meskauskas (audriusa@bioinformatics.org) + */ +public class HtmlDemo extends JPanel +{ + + private class LoadActionListener + implements ActionListener + { + + public void actionPerformed(ActionEvent event) + { + String urlStr = url.getText(); + try + { + setPage(new URL(url.getText())); + } + catch (MalformedURLException ex) + { + // Do something more useful here. + ex.printStackTrace(); + } + } + } + + /** + * Setting this to true causes the parsed element structure to be dumped. + */ + private static final boolean DEBUG = true; + + /** + * The URL entry field. + */ + JTextField url = new JTextField(); + + JTextPane html = new JTextPane(); + + int n; + + /** + * The browsing history. + * + * Package private to avoid accessor method. + */ + LinkedList history; + + public HtmlDemo() + { + super(); + history = new LinkedList(); + createContent(); + } + + /** + * Returns a panel with the demo content. The panel uses a BorderLayout(), and + * the BorderLayout.SOUTH area is empty, to allow callers to add controls to + * the bottom of the panel if they want to (a close button is added if this + * demo is being run as a standalone demo). + */ + private void createContent() + { + setLayout(new BorderLayout()); + + JEditorPane.registerEditorKitForContentType("text/html", + BrowserEditorKit.class.getName()); + html.setEditable(false); + html.addHyperlinkListener(new HyperlinkListener() + { + + public void hyperlinkUpdate(HyperlinkEvent event) + { + if (event instanceof FormSubmitEvent) + { + submitForm((FormSubmitEvent) event); + } + else + { + URL u = event.getURL(); + if (u != null) + { + setPage(u); + } + } + } + + }); + + JScrollPane scroller = new JScrollPane(html); + JPanel urlPanel = new JPanel(); + urlPanel.setLayout(new BoxLayout(urlPanel, BoxLayout.X_AXIS)); + url.setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE)); + LoadActionListener action = new LoadActionListener(); + url.addActionListener(action); + urlPanel.add(url); + JButton loadButton = new JButton("go"); + urlPanel.add(loadButton); + loadButton.addActionListener(action); + + // Setup control panel. + JToolBar controlPanel = createToolBar(); + JPanel browserPanel = new JPanel(); + browserPanel.setLayout(new BorderLayout()); + browserPanel.add(urlPanel, BorderLayout.NORTH); + browserPanel.add(scroller, BorderLayout.CENTER); + add(controlPanel, BorderLayout.NORTH); + add(browserPanel, BorderLayout.CENTER); + + // Load start page. + try + { + URL startpage = getClass().getResource("welcome.html"); + html.setPage(startpage); + url.setText(startpage.toString()); + history.addLast(startpage); + } + catch (Exception ex) + { + System.err.println("couldn't load page: "/* + startpage*/); + ex.printStackTrace(); + } + setPreferredSize(new Dimension(800, 600)); + } + + + /** + * Creates the toolbar with the control buttons. + * + * @return the toolbar with the control buttons + */ + JToolBar createToolBar() + { + JToolBar tb = new JToolBar(); + Icon backIcon = Demo.getIcon("/gnu/classpath/examples/icons/back.png", + "back"); + JButton back = new JButton(backIcon); + back.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent ev) + { + if (history.size() > 1) + { + URL last = (URL) history.removeLast(); + last = (URL) history.getLast(); + url.setText(last.toString()); + try + { + html.setPage(last); + } + catch (IOException ex) + { + // Do something more useful. + ex.printStackTrace(); + } + } + } + }); + tb.add(back); + Icon reloadIcon = Demo.getIcon("/gnu/classpath/examples/icons/reload.png", + "reload"); + JButton reload = new JButton(reloadIcon); + reload.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent ev) + { + if (history.size() > 0) + { + URL last = (URL) history.getLast(); + url.setText(last.toString()); + try + { + html.setPage(last); + } + catch (IOException ex) + { + // Do something more useful. + ex.printStackTrace(); + } + } + } + }); + tb.add(reload); + return tb; + } + + /** + * The executable method to display the editable table. + * + * @param args + * unused. + */ + public static void main(String[] args) + { + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + HtmlDemo demo = new HtmlDemo(); + JFrame frame = new JFrame(); + frame.getContentPane().add(demo); + frame.setSize(new Dimension(750, 480)); + frame.setVisible(true); + } + }); + } + + /** + * Helper method to navigate to a new URL. + * + * @param u the new URL to navigate to + */ + void setPage(URL u) + { + try + { + url.setText(u.toString()); + html.setPage(u); + history.addLast(u); + } + catch (IOException ex) + { + // Do something more useful here. + ex.printStackTrace(); + } + } + + /** + * Submits a form when a FormSubmitEvent is received. The HTML API + * provides automatic form submit but when this is enabled we don't + * receive any notification and can't update our location field. + * + * @param ev the form submit event + */ + void submitForm(FormSubmitEvent ev) + { + URL url = ev.getURL(); + String data = ev.getData(); + FormSubmitEvent.MethodType method = ev.getMethod(); + if (method == FormSubmitEvent.MethodType.POST) + { + try + { + URLConnection conn = url.openConnection(); + postData(conn, data); + } + catch (IOException ex) + { + // Deal with this. + ex.printStackTrace(); + } + } + else + { + try + { + url = new URL(url.toString() + "?" + data); + } + catch (MalformedURLException ex) + { + ex.printStackTrace(); + } + } + setPage(url); + } + + /** + * Posts the form data for forms with HTTP POST method. + * + * @param conn the connection + * @param data the form data + */ + private void postData(URLConnection conn, String data) + { + conn.setDoOutput(true); + PrintWriter out = null; + try + { + out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream())); + out.print(data); + out.flush(); + } + catch (IOException ex) + { + // Deal with this! + ex.printStackTrace(); + } + finally + { + if (out != null) + out.close(); + } + } + + /** + * Returns a DemoFactory that creates a HtmlDemo. + * + * @return a DemoFactory that creates a HtmlDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new HtmlDemo(); + } + }; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/ListDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/ListDemo.java new file mode 100644 index 000000000..8caa1dc62 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/ListDemo.java @@ -0,0 +1,231 @@ +/* ListDemo.java -- Demostrates JList + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.swing; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.DefaultListCellRenderer; +import javax.swing.DefaultListModel; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; +import javax.swing.ListCellRenderer; +import javax.swing.SwingUtilities; + +public class ListDemo + extends JPanel + implements ActionListener +{ + + private static class LabelCellRenderer + extends DefaultListCellRenderer + { + public Component getListCellRendererComponent(JList list, + Object value, + int index, + boolean isSelected, + boolean cellHasFocus) + { + Component c = super.getListCellRendererComponent(list, value, index, + isSelected, + cellHasFocus); + return c; + } + } + + private static class CheckCellRenderer + extends JCheckBox + implements ListCellRenderer + { + public Component getListCellRendererComponent(JList list, + Object value, + int index, + boolean isSelected, + boolean cellHasFocus) + { + setSelected(isSelected); + setText(value.toString()); + + return this; + } + } + + ListDemo() + { + super(); + createContent(); + } + + private void createContent() + { + + String foo[] = new String[] { + "non alcoholic ", + "carbonated ", + "malted ", + "fresh squeezed ", + "imported ", + "high fructose ", + "enriched " + }; + + String bar[] = new String[] { + "orange juice", + "ginger beer", + "yak milk", + "corn syrup", + "herbal remedy" + }; + + final DefaultListModel mod = new DefaultListModel(); + final JList list1 = new JList(mod); + final JList list2 = new JList(mod); + + list2.setSelectionModel(list1.getSelectionModel()); + for (int i = 0; i < bar.length; ++i) + for (int j = 0; j < foo.length; ++j) + mod.addElement(foo[j] + bar[i]); + + list1.setCellRenderer(new LabelCellRenderer()); + list2.setCellRenderer(new CheckCellRenderer()); + + JButton add = new JButton("add element"); + add.addActionListener(new ActionListener() + { + int i = 0; + public void actionPerformed(ActionEvent e) + { + mod.addElement("new element " + i); + ++i; + } + }); + + JButton del = new JButton("delete selected"); + del.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + for (int i = 0; i < mod.getSize(); ++i) + if (list1.isSelectedIndex(i)) + mod.remove(i); + } + }); + + + JSplitPane splitter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); + splitter.add(new JScrollPane(list1), JSplitPane.LEFT); + splitter.add(new JScrollPane(list2), JSplitPane.RIGHT); + + setLayout(new BorderLayout()); + JPanel p2 = new JPanel(); + p2.setLayout(new GridLayout(1, 2)); + p2.add(add); + p2.add(del); + + add(p2, BorderLayout.NORTH); + add(splitter, BorderLayout.CENTER); + } + + public void actionPerformed(ActionEvent e) + { + if (e.getActionCommand().equals("CLOSE")) + { + System.exit(0); + } + } + + /** + * When the demo is run independently, the frame is displayed, so we should + * initialise the content panel (including the demo content and a close + * button). But when the demo is run as part of the Swing activity board, + * only the demo content panel is used, the frame itself is never displayed, + * so we can avoid this step. + */ + void initFrameContent() + { + JPanel closePanel = new JPanel(); + JButton closeButton = new JButton("Close"); + closeButton.setActionCommand("CLOSE"); + closeButton.addActionListener(this); + closePanel.add(closeButton); + add(closePanel, BorderLayout.SOUTH); + } + + public static void main(String[] args) + { + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + ListDemo app = new ListDemo(); + app.initFrameContent(); + JFrame frame = new JFrame("List Demo"); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + } + }); + } + + /** + * Returns a DemoFactory that creates a ListDemo. + * + * @return a DemoFactory that creates a ListDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new ListDemo(); + } + }; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/MetalThemeEditor.java b/libjava/classpath/examples/gnu/classpath/examples/swing/MetalThemeEditor.java new file mode 100644 index 000000000..1360f9b59 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/MetalThemeEditor.java @@ -0,0 +1,585 @@ +/* MetalThemeEditor.java -- Edit themes using this application + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.swing; + +import gnu.javax.swing.plaf.metal.CustomizableTheme; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Graphics; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.Window; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JColorChooser; +import javax.swing.JComponent; +import javax.swing.JFileChooser; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.plaf.metal.MetalLookAndFeel; + +/** + * This application serves two purposes: 1. demonstrate the color chooser + * component, 2. make creating new Metal themes as easy as possible. + * + * @author Roman Kennke (kennke@aicas.com) + */ +public class MetalThemeEditor + extends JPanel +{ + /** + * An icon to display a chosen color in a button. + */ + private class ColorIcon implements Icon + { + /** + * The color to be shown on the icon. + */ + Color color; + + /** + * Creates a new ColorIcon. + * + * @param c the color to be displayed + */ + ColorIcon(Color c) + { + color = c; + } + + /** + * Returns the icon height, which is 10. + * + * @return 10 + */ + public int getIconHeight() + { + return 10; + } + + /** + * Returns the icon width, which is 30. + * + * @return 30 + */ + public int getIconWidth() + { + return 30; + } + + /** + * Paints the icon. + * + * @param c the component to paint on + * @param g the graphics to use + * @param x the x location + * @param y the y location + */ + public void paintIcon(Component c, Graphics g, int x, int y) + { + g.setColor(color); + g.fillRect(x, y, 30, 10); + } + + } + + /** + * Opens up a color chooser and lets the user select a color for the theme. + */ + private class ChooseColorAction implements ActionListener + { + + /** + * The button that will get updated when a new color is selected. + */ + private JButton button; + + /** + * Specifies which color of the theme should be updated. See constants in + * the MetalThemeEditor class. + */ + private int colorType; + + /** + * Creates a new ChooseColorAction. The specified button will have its + * icon updated to the new color if appropriate. + * + * @param b the button to update + * @param type the color type to update + */ + ChooseColorAction(JButton b, int type) + { + button = b; + colorType = type; + } + + /** + * Opens a color chooser and lets the user select a color. + */ + public void actionPerformed(ActionEvent event) + { + Color c = JColorChooser.showDialog(button, "Choose a color", + getColor(colorType)); + if (c != null) + { + setColor(colorType, c); + button.setIcon(new ColorIcon(c)); + } + } + } + + /** + * Denotes the primary1 color of the theme. + */ + private static final int PRIMARY1 = 0; + + /** + * Denotes the primary2 color of the theme. + */ + private static final int PRIMARY2 = 1; + + /** + * Denotes the primary3 color of the theme. + */ + private static final int PRIMARY3 = 2; + + /** + * Denotes the secondary1 color of the theme. + */ + private static final int SECONDARY1 = 3; + + /** + * Denotes the secondary2 color of the theme. + */ + private static final int SECONDARY2 = 4; + + /** + * Denotes the secondary3 color of the theme. + */ + private static final int SECONDARY3 = 5; + + /** + * The theme that is edited. + */ + CustomizableTheme theme; + + /** + * Creates a new instance of the MetalThemeEditor. + */ + MetalThemeEditor() + { + theme = new CustomizableTheme(); + setBorder(BorderFactory.createEmptyBorder(12, 12, 11, 11)); + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + add(createConfigurationPanel()); + add(Box.createVerticalStrut(17)); + add(createButtonPanel()); + } + + /** + * Creates the main panel of the MetalThemeEditor. This is the upper + * area where the colors can be selected. + * + * @return the main panel + */ + private JPanel createConfigurationPanel() + { + JPanel p = new JPanel(); + p.setLayout(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + c.weightx = 1; + c.weighty = 0; + c.fill = GridBagConstraints.HORIZONTAL; + Insets labelInsets = new Insets(0, 0, 11, 6); + Insets buttonInsets = new Insets(0, 0, 11, 0); + + // Primary 1 + JLabel primary1Label = new JLabel("Primary 1:"); + c.gridx = 0; + c.gridy = 0; + c.insets = labelInsets; + p.add(primary1Label, c); + + Icon p1Icon = new ColorIcon(theme.getPrimary1()); + JButton primary1Button = new JButton(p1Icon); + primary1Button.addActionListener(new ChooseColorAction(primary1Button, + PRIMARY1)); + //c.weightx = 0; + c.gridx = 1; + c.insets = buttonInsets; + p.add(primary1Button, c); + primary1Label.setLabelFor(primary1Button); + + // Primary 2 + JLabel primary2Label = new JLabel("Primary 2:"); + c.gridx = 0; + c.gridy = 1; + c.insets = labelInsets; + p.add(primary2Label, c); + + Icon p2Icon = new ColorIcon(theme.getPrimary2()); + JButton primary2Button = new JButton(p2Icon); + primary2Button.addActionListener(new ChooseColorAction(primary2Button, + PRIMARY2)); + c.gridx = 1; + c.insets = buttonInsets; + p.add(primary2Button, c); + primary2Label.setLabelFor(primary2Button); + + // Primary 3 + JLabel primary3Label = new JLabel("Primary 3:"); + c.gridx = 0; + c.gridy = 2; + c.insets = labelInsets; + p.add(primary3Label, c); + + Icon p3Icon = new ColorIcon(theme.getPrimary3()); + JButton primary3Button = new JButton(p3Icon); + primary3Button.addActionListener(new ChooseColorAction(primary3Button, + PRIMARY3)); + c.gridx = 1; + c.insets = buttonInsets; + p.add(primary3Button, c); + primary3Label.setLabelFor(primary3Button); + + // Secondary 1 + JLabel secondary1Label = new JLabel("Secondary 1:"); + c.gridx = 0; + c.gridy = 3; + c.insets = labelInsets; + p.add(secondary1Label, c); + + Icon s1Icon = new ColorIcon(theme.getSecondary1()); + JButton secondary1Button = new JButton(s1Icon); + secondary1Button.addActionListener(new ChooseColorAction(secondary1Button, + SECONDARY1)); + c.gridx = 1; + c.insets = buttonInsets; + p.add(secondary1Button, c); + secondary1Label.setLabelFor(secondary1Button); + + // Secondary 2 + JLabel secondary2Label = new JLabel("Secondary 2:"); + c.gridx = 0; + c.gridy = 4; + c.insets = labelInsets; + p.add(secondary2Label, c); + + Icon s2Icon = new ColorIcon(theme.getSecondary2()); + JButton secondary2Button = new JButton(s2Icon); + secondary2Button.addActionListener(new ChooseColorAction(secondary2Button, + SECONDARY2)); + c.gridx = 1; + c.insets = buttonInsets; + p.add(secondary2Button, c); + secondary2Label.setLabelFor(secondary2Button); + + // Secondary 3 + JLabel secondary3Label = new JLabel("Secondary 3:"); + c.gridx = 0; + c.gridy = 5; + c.insets = labelInsets; + p.add(secondary3Label, c); + + Icon s3Icon = new ColorIcon(theme.getSecondary3()); + JButton secondary3Button = new JButton(s3Icon); + secondary3Button.addActionListener(new ChooseColorAction(secondary3Button, + SECONDARY3)); + c.gridx = 1; + c.insets = buttonInsets; + p.add(secondary3Button, c); + secondary3Label.setLabelFor(secondary3Button); + + return p; + } + + /** + * Creates the button panel at the bottom of the MetalThemeEditor. + * + * @return the button panel + */ + private JPanel createButtonPanel() + { + JPanel p = new JPanel(); + p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS)); + p.add(Box.createHorizontalGlue()); + + JButton applyButton = new JButton("Apply"); + applyButton.addActionListener + (new ActionListener() + { + public void actionPerformed(ActionEvent ev) + { + try + { + CustomizableTheme copy = (CustomizableTheme) theme.clone(); + MetalLookAndFeel.setCurrentTheme(copy); + UIManager.setLookAndFeel(new MetalLookAndFeel()); + Window w = SwingUtilities.getWindowAncestor(MetalThemeEditor.this); + SwingUtilities.updateComponentTreeUI(w); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + } + }); + p.add(applyButton); + + p.add(Box.createHorizontalStrut(5)); + + JButton exportButton = new JButton("Export as Java File"); + exportButton.addActionListener + (new ActionListener() + { + public void actionPerformed(ActionEvent ev) + { + export(); + } + }); + p.add(exportButton); + + return p; + } + + /** + * Exports the current theme as Java source file. This will prompt the user + * to choose a filename. + */ + void export() + { + JFileChooser chooser = new JFileChooser(); + int confirm = chooser.showSaveDialog(this); + if (confirm == JFileChooser.APPROVE_OPTION) + exportToFile(chooser.getSelectedFile()); + } + + /** + * Writes out the current configured Metal theme as Java source file. + * + * @param file the file to write into + */ + void exportToFile(File file) + { + String fileName = file.getName(); + if (! fileName.endsWith(".java")) + { + JOptionPane.showMessageDialog(this, + "Filename does not denote a Java source file", + "Invalid filename", + JOptionPane.ERROR_MESSAGE); + return; + } + + String className = fileName.substring(0, fileName.length() - 5); + Color p1 = theme.getPrimary1(); + Color p2 = theme.getPrimary2(); + Color p3 = theme.getPrimary3(); + Color s1 = theme.getSecondary1(); + Color s2 = theme.getSecondary2(); + Color s3 = theme.getSecondary3(); + + try + { + FileOutputStream out = new FileOutputStream(file); + Writer writer = new OutputStreamWriter(out); + writer.write("import javax.swing.plaf.ColorUIResource;\n"); + writer.write("import javax.swing.plaf.metal.DefaultMetalTheme;\n"); + writer.write("public class " + className + " extends DefaultMetalTheme\n"); + writer.write("{\n"); + writer.write(" protected ColorUIResource getPrimary1()\n"); + writer.write(" {\n"); + writer.write(" return new ColorUIResource(" + p1.getRGB() + ");\n"); + writer.write(" }\n"); + writer.write(" protected ColorUIResource getPrimary2()\n"); + writer.write(" {\n"); + writer.write(" return new ColorUIResource(" + p2.getRGB() + ");\n"); + writer.write(" }\n"); + writer.write(" protected ColorUIResource getPrimary3()\n"); + writer.write(" {\n"); + writer.write(" return new ColorUIResource(" + p3.getRGB() + ");\n"); + writer.write(" }\n"); + writer.write(" protected ColorUIResource getSecondary1()\n"); + writer.write(" {\n"); + writer.write(" return new ColorUIResource(" + s1.getRGB() + ");\n"); + writer.write(" }\n"); + writer.write(" protected ColorUIResource getSecondary2()\n"); + writer.write(" {\n"); + writer.write(" return new ColorUIResource(" + s2.getRGB() + ");\n"); + writer.write(" }\n"); + writer.write(" protected ColorUIResource getSecondary3()\n"); + writer.write(" {\n"); + writer.write(" return new ColorUIResource(" + s3.getRGB() + ");\n"); + writer.write(" }\n"); + writer.write("}\n"); + writer.close(); + out.close(); + } + catch (FileNotFoundException ex) + { + ex.printStackTrace(); + } + catch (IOException ex) + { + ex.printStackTrace(); + } + + } + + /** + * Returns the color of the theme with the specified type. For the possible + * types see the constants of this class. + * + * @param colorType the color type to fetch from the theme + * + * @return the current color of the specified type + * + * @throws IllegalArgumentException for illegal color types + */ + Color getColor(int colorType) + { + Color color = null; + switch (colorType) + { + case PRIMARY1: + color = theme.getPrimary1(); + break; + case PRIMARY2: + color = theme.getPrimary2(); + break; + case PRIMARY3: + color = theme.getPrimary3(); + break; + case SECONDARY1: + color = theme.getSecondary1(); + break; + case SECONDARY2: + color = theme.getSecondary2(); + break; + case SECONDARY3: + color = theme.getSecondary3(); + break; + default: + throw new IllegalArgumentException("Unknown color type: " + colorType); + } + return color; + } + + /** + * Sets the color of the specified type in the current theme. + * + * @param colorType the color type + * @param color the color to set + * + * @throws IllegalArgumentException for illegal color types + */ + void setColor(int colorType, Color color) + { + switch (colorType) + { + case PRIMARY1: + theme.setPrimary1(color); + break; + case PRIMARY2: + theme.setPrimary2(color); + break; + case PRIMARY3: + theme.setPrimary3(color); + break; + case SECONDARY1: + theme.setSecondary1(color); + break; + case SECONDARY2: + theme.setSecondary2(color); + break; + case SECONDARY3: + theme.setSecondary3(color); + break; + default: + throw new IllegalArgumentException("Illegal color type: " + colorType); + } + } + + /** + * The entry point to the application. + * + * @param args ignored + */ + public static void main(String[] args) + { + JFrame f = new JFrame("MetalThemeEditor"); + f.setContentPane(new MetalThemeEditor()); + f.pack(); + f.setVisible(true); + } + + /** + * Returns a DemoFactory that creates a MetalThemeEditor. + * + * @return a DemoFactory that creates a MetalThemeEditor + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new MetalThemeEditor(); + } + }; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/MiniDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/MiniDemo.java new file mode 100644 index 000000000..aa8424804 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/MiniDemo.java @@ -0,0 +1,233 @@ +/* MiniDemo.java -- A Swing demo suitable for embedded environments + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.swing; + +import java.awt.BorderLayout; +import java.awt.Font; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTabbedPane; +import javax.swing.JTextField; +import javax.swing.SwingUtilities; +import javax.swing.plaf.metal.DefaultMetalTheme; +import javax.swing.plaf.metal.MetalIconFactory; +import javax.swing.plaf.metal.MetalLookAndFeel; + +/** + * A Swing demo suitable for embedded environments (e.g. small display, + * b/w graphics etc). + * + * @author Roman Kennke (kennke@aicas.com) + */ +public class MiniDemo extends JFrame +{ + + /** + * Creates a new MiniDemo instance. + */ + MiniDemo() + { + createGUI(); + } + + private void createGUI() + { + JTabbedPane tabPane = new JTabbedPane(JTabbedPane.TOP, + JTabbedPane.SCROLL_TAB_LAYOUT); + + // Setup scrolling list in first tab. + Object[] listData = new Object[]{"Milk", "Beer", "Wine", "Water", + "Orange juice", "Tea", "Coffee", "Whiskey", + "Lemonade", "Apple juice", "Gin Tonic", + "Pangalactic Garleblaster", "Coke"}; + JList list = new JList(listData); + JScrollPane sp = new JScrollPane(list); + tabPane.addTab("List", sp); + + // Setup some buttons in the second tab. + JPanel buttonPanel = new JPanel(); + buttonPanel.setLayout(new GridLayout(4, 1)); + // JButtons + JPanel jButtonPanel = new JPanel(); + jButtonPanel.setLayout(new BorderLayout()); + final JCheckBox buttonState1 = new JCheckBox("Enabled", true); + jButtonPanel.add(buttonState1, BorderLayout.EAST); + JPanel jButtonContainer = new JPanel(); + final JButton jButton1 = new JButton("JButton"); + final JButton jButton2 = + new JButton(MetalIconFactory.getInternalFrameDefaultMenuIcon()); + jButtonContainer.add(jButton1); + jButtonContainer.add(jButton2); + jButtonPanel.add(jButtonContainer, BorderLayout.CENTER); + buttonState1.addActionListener( + new ActionListener() + { + public void actionPerformed(ActionEvent ev) + { + boolean enabled = buttonState1.isSelected(); + jButton1.setEnabled(enabled); + jButton2.setEnabled(enabled); + } + }); + buttonPanel.add(jButtonPanel); + // JToggleButtons + JPanel jToggleButtonPanel = new JPanel(); + jToggleButtonPanel.setLayout(new BorderLayout()); + final JCheckBox buttonState2 = new JCheckBox("Enabled", true); + jToggleButtonPanel.add(buttonState2, BorderLayout.EAST); + JPanel jToggleButtonContainer = new JPanel(); + final JButton jToggleButton1 = new JButton("JToggleButton"); + final JButton jToggleButton2 = + new JButton(MetalIconFactory.getInternalFrameDefaultMenuIcon()); + jToggleButtonContainer.add(jToggleButton1); + jToggleButtonContainer.add(jToggleButton2); + jToggleButtonPanel.add(jToggleButtonContainer, BorderLayout.CENTER); + buttonState2.addActionListener( + new ActionListener() + { + public void actionPerformed(ActionEvent ev) + { + boolean enabled = buttonState2.isSelected(); + jToggleButton1.setEnabled(enabled); + jToggleButton2.setEnabled(enabled); + } + }); + buttonPanel.add(jToggleButtonPanel); + tabPane.addTab("Buttons", buttonPanel); + + // ComboBoxes + JPanel comboBoxPanel = new JPanel(); + JComboBox comboBox = new JComboBox(listData); + comboBoxPanel.add(comboBox); + tabPane.add("ComboBox", comboBoxPanel); + + // TextFields + JPanel textFieldPanel = new JPanel(); + textFieldPanel.setLayout(new BoxLayout(textFieldPanel, BoxLayout.Y_AXIS)); + textFieldPanel.add(Box.createVerticalStrut(70)); + JPanel leftAlignedPanel = new JPanel(new BorderLayout()); + JPanel textFieldPanel1 = new JPanel(); + textFieldPanel1.setLayout(new BoxLayout(textFieldPanel1, + BoxLayout.X_AXIS)); + final JTextField textfield1 = new JTextField("Hello World!"); + textfield1.setHorizontalAlignment(JTextField.LEFT); + textfield1.setFont(new Font("Dialog", Font.PLAIN, 8)); + textFieldPanel1.add(textfield1); + final JTextField textfield2 = new JTextField("Hello World!"); + textfield2.setHorizontalAlignment(JTextField.LEFT); + textfield2.setFont(new Font("Dialog", Font.ITALIC, 12)); + textFieldPanel1.add(textfield2); + final JTextField textfield3 = new JTextField("Hello World!"); + textfield3.setHorizontalAlignment(JTextField.LEFT); + textfield3.setFont(new Font("Dialog", Font.BOLD, 14)); + textFieldPanel1.add(textfield3); + leftAlignedPanel.add(textFieldPanel1); + JPanel statePanel = new JPanel(); + statePanel.setLayout(new BoxLayout(statePanel, BoxLayout.Y_AXIS)); + statePanel.add(Box.createVerticalGlue()); + final JCheckBox enabled1 = new JCheckBox("enabled"); + enabled1.setSelected(true); + enabled1.addActionListener( + new ActionListener() + { + public void actionPerformed(ActionEvent ev) + { + boolean enabled = enabled1.isSelected(); + textfield1.setEnabled(enabled); + textfield2.setEnabled(enabled); + textfield3.setEnabled(enabled); + } + }); + statePanel.add(enabled1); + final JCheckBox editable1 = new JCheckBox("editable"); + editable1.setSelected(true); + editable1.addActionListener( + new ActionListener() + { + public void actionPerformed(ActionEvent ev) + { + boolean editable = editable1.isSelected(); + textfield1.setEditable(editable); + textfield2.setEditable(editable); + textfield3.setEditable(editable); + } + }); + statePanel.add(editable1); + statePanel.add(Box.createVerticalGlue()); + leftAlignedPanel.add(statePanel, BorderLayout.EAST); + textFieldPanel.add(leftAlignedPanel); + System.err.println(leftAlignedPanel.getPreferredSize()); + textFieldPanel.add(Box.createVerticalStrut(70)); + //panel.add(rightAlignedPanel); + tabPane.add("TextField", textFieldPanel); + setContentPane(tabPane); + } + + /** + * Starts the demo application. + * + * @param args the command line arguments (ignored) + */ + public static void main(String[] args) + { + SwingUtilities.invokeLater(new Runnable() { + public void run() + { + MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme()); + MiniDemo demo = new MiniDemo(); + demo.setSize(320, 200); + demo.setUndecorated(true); + demo.setVisible(true); + demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + } + }); + } + +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/NavigationFilterDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/NavigationFilterDemo.java new file mode 100644 index 000000000..761c57528 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/NavigationFilterDemo.java @@ -0,0 +1,205 @@ +/* NavigationFilterDemo.java -- An example for the NavigationFilter class. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. +*/ + + +package gnu.classpath.examples.swing; + +import java.awt.BorderLayout; +import java.awt.Point; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JTextArea; +import javax.swing.SwingConstants; +import javax.swing.SwingUtilities; +import javax.swing.text.BadLocationException; +import javax.swing.text.JTextComponent; +import javax.swing.text.NavigationFilter; +import javax.swing.text.Position; +import javax.swing.text.Utilities; + +/** + * A demonstration of the javax.swing.text.NavigationFilter class. + * + *

It shows a NavigationFilter which lets you walk word-wise + * through a text.

+ * + * @author Robert Schuster + */ +public class NavigationFilterDemo + extends JPanel + implements ActionListener +{ + + JTextArea textArea; + + /** + * Creates a new demo instance. + */ + public NavigationFilterDemo() + { + createContent(); + // initFrameContent() is only called (from main) when running this app + // standalone + } + + /** + * When the demo is run independently, the frame is displayed, so we should + * initialise the content panel (including the demo content and a close + * button). But when the demo is run as part of the Swing activity board, + * only the demo content panel is used, the frame itself is never displayed, + * so we can avoid this step. + */ + void initFrameContent() + { + JPanel closePanel = new JPanel(); + JButton closeButton = new JButton("Close"); + closeButton.setActionCommand("CLOSE"); + closeButton.addActionListener(this); + closePanel.add(closeButton); + add(closePanel, BorderLayout.SOUTH); + } + + private void createContent() + { + setLayout(new BorderLayout()); + + add(textArea = new JTextArea(10, 20)); + + textArea.setWrapStyleWord(true); + + textArea.setLineWrap(true); + + textArea.setNavigationFilter(new WordFilter()); + + textArea.setText("GNU Classpath, Essential Libraries for Java, " + + "is a GNU project to create free core class " + + "libraries for use with virtual machines and " + + "compilers for the java programming language."); + } + + public void actionPerformed(ActionEvent e) + { + if (e.getActionCommand().equals("CLOSE")) + System.exit(0); + + } + + public static void main(String[] args) + { + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + NavigationFilterDemo app = new NavigationFilterDemo(); + app.initFrameContent(); + JFrame frame = new JFrame("NavigationFilterDemo"); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + } + }); + } + + /** + * Returns a DemoFactory that creates a NavigationFilterDemo. + * + * @return a DemoFactory that creates a NavigationFilterDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new NavigationFilterDemo(); + } + }; + } + + class WordFilter extends NavigationFilter + { + public int getNextVisualPositionFrom(JTextComponent text, + int pos, + Position.Bias bias, + int direction, + Position.Bias[] biasRet) + throws BadLocationException + { + Point pt; + + int newpos = pos; + switch (direction) + { + case SwingConstants.NORTH: + // Find out where the caret want to be positioned ideally. + pt = text.getCaret().getMagicCaretPosition(); + + // Calculate its position above. + newpos = Utilities.getPositionAbove(text, pos, (pt != null) ? pt.x : 0); + + // If we have a valid position, then calculate the next word start + // from there. + if (newpos != -1) + return Utilities.getWordStart(text, newpos); + else + return pos; + case SwingConstants.SOUTH: + // Find out where the caret want to be positioned ideally. + pt = text.getCaret().getMagicCaretPosition(); + + // Calculate its position below. + newpos = Utilities.getPositionBelow(text, pos, (pt != null) ? pt.x : 0); + + // If we have a valid position, then calculate the next word start + // from there. + if (newpos != -1) + return Utilities.getWordStart(text, newpos); + else + return pos; + case SwingConstants.WEST: + // Calculate the next word start. + newpos = Utilities.getWordStart(text, newpos); + + // If that means that the caret will not move, return + // the start of the previous word. + if (newpos != pos) + return newpos; + else + return Utilities.getPreviousWord(text, newpos); + case SwingConstants.EAST: + return Utilities.getNextWord(text, newpos); + default: + // Do whatever the super implementation did. + return super.getNextVisualPositionFrom(text, pos, bias, + direction, biasRet); + } + } + + } + +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/ProgressBarDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/ProgressBarDemo.java new file mode 100644 index 000000000..1391a00ba --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/ProgressBarDemo.java @@ -0,0 +1,239 @@ +/* ProgressBarDemo.java -- A demonstration of JProgressBars + Copyright (C) 2005 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.swing; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JProgressBar; +import javax.swing.JSlider; +import javax.swing.SwingUtilities; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +public class ProgressBarDemo + extends JPanel + implements ActionListener +{ + + /** + * Creates a new ProgressBarDemo window with the specified title. + */ + ProgressBarDemo() + { + super(); + createContent(); + } + + void initFrameContent() + { + JPanel closePanel = new JPanel(); + JButton closeButton = new JButton("Close"); + closeButton.setActionCommand("CLOSE"); + closeButton.addActionListener(this); + closePanel.add(closeButton); + add(closePanel); + } + + private void createContent() + { + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + JPanel horizontalProgressBar = createHorizontalProgressBar(); + add(horizontalProgressBar); + add(Box.createVerticalStrut(10)); + JPanel verticalProgressBar = createVerticalProgressBar(); + add(verticalProgressBar); + } + + private static JPanel createHorizontalProgressBar() + { + JPanel panel = new JPanel(); + panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); + + // Plain progress bar. + final JProgressBar hor1 = new JProgressBar(JProgressBar.HORIZONTAL, 0, 100); + panel.add(hor1); + final JSlider slider1 = new JSlider(JSlider.HORIZONTAL, 0, 100, 0); + slider1.addChangeListener(new ChangeListener() + { + public void stateChanged(ChangeEvent event) + { + hor1.setValue(slider1.getValue()); + } + }); + panel.add(slider1); + + panel.add(Box.createVerticalStrut(5)); + + // Plain progress bar with some text. + final JProgressBar hor2 = new JProgressBar(JProgressBar.HORIZONTAL, 0, 100); + hor2.setString("ProgressBar Demo"); + hor2.setStringPainted(true); + panel.add(hor2); + final JSlider slider2 = new JSlider(JSlider.HORIZONTAL, 0, 100, 0); + slider2.addChangeListener(new ChangeListener() + { + public void stateChanged(ChangeEvent event) + { + hor2.setValue(slider2.getValue()); + } + }); + panel.add(slider2); + + panel.add(Box.createVerticalStrut(5)); + + // Indeterminate progress bar. + final JProgressBar hor3 = new JProgressBar(JProgressBar.HORIZONTAL, 0, 100); + hor3.setIndeterminate(true); + panel.add(hor3); + + panel.add(Box.createVerticalStrut(5)); + + // Indeterminate progress bar with text. + final JProgressBar hor4 = new JProgressBar(JProgressBar.HORIZONTAL, 0, 100); + hor4.setIndeterminate(true); + hor4.setString("Indeterminate ProgressBar"); + hor4.setStringPainted(true); + panel.add(hor4); + + return panel; + } + + private static JPanel createVerticalProgressBar() + { + JPanel panel = new JPanel(); + panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); + final JProgressBar vert = new JProgressBar(JProgressBar.VERTICAL, 0, 100); + panel.add(vert); + final JSlider slider = new JSlider(JSlider.VERTICAL, 0, 100, 0); + slider.addChangeListener(new ChangeListener() + { + public void stateChanged(ChangeEvent event) + { + vert.setValue(slider.getValue()); + } + }); + panel.add(slider); + + panel.add(Box.createHorizontalStrut(5)); + + final JProgressBar vert2 = new JProgressBar(JProgressBar.VERTICAL, 0, 100); + vert2.setString("ProgressBar Demo"); + panel.add(vert2); + vert2.setStringPainted(true); + final JSlider slider2 = new JSlider(JSlider.VERTICAL, 0, 100, 0); + slider2.addChangeListener(new ChangeListener() + { + public void stateChanged(ChangeEvent event) + { + vert2.setValue(slider2.getValue()); + } + }); + panel.add(slider2); + + panel.add(Box.createHorizontalStrut(5)); + + // Indeterminate progress bar. + final JProgressBar vert3 = new JProgressBar(JProgressBar.VERTICAL, 0, 100); + vert3.setIndeterminate(true); + panel.add(vert3); + + panel.add(Box.createHorizontalStrut(5)); + + // Indeterminate progress bar with text. + final JProgressBar vert4 = new JProgressBar(JProgressBar.VERTICAL, 0, 100); + vert4.setIndeterminate(true); + vert4.setString("Indeterminate ProgressBar"); + vert4.setStringPainted(true); + panel.add(vert4); + return panel; + } + + public void actionPerformed(ActionEvent event) + { + if (event.getActionCommand().equals("CLOSE")) + { + System.exit(0); + } + } + + /** + * The entry point when running as a standalone program. + * + * @param args command line arguments + */ + public static void main(String[] args) + { + SwingUtilities.invokeLater( + new Runnable() + { + public void run() + { + ProgressBarDemo app = new ProgressBarDemo(); + app.initFrameContent(); + JFrame frame = new JFrame("ProgressBar Demo"); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + } + }); + } + + /** + * Returns a DemoFactory that creates a ProgressBarDemo. + * + * @return a DemoFactory that creates a ProgressBarDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new ProgressBarDemo(); + } + }; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/ScrollBarDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/ScrollBarDemo.java new file mode 100644 index 000000000..ac500d612 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/ScrollBarDemo.java @@ -0,0 +1,174 @@ +/* ScrollBarDemo.java -- An example showing scroll bars in Swing. + Copyright (C) 2005, 2006, Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. +*/ + + +package gnu.classpath.examples.swing; + +import java.awt.BorderLayout; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JScrollBar; +import javax.swing.SwingUtilities; + +/** + * A simple scroll bar demo showing various scroll bars in different states. + */ +public class ScrollBarDemo + extends JPanel + implements ActionListener +{ + + /** + * Creates a new demo instance. + */ + public ScrollBarDemo() + { + super(); + createContent(); + } + + /** + * When the demo is run independently, the frame is displayed, so we should + * initialise the content panel (including the demo content and a close + * button). But when the demo is run as part of the Swing activity board, + * only the demo content panel is used, the frame itself is never displayed, + * so we can avoid this step. + */ + void initFrameContent() + { + JPanel closePanel = new JPanel(); + JButton closeButton = new JButton("Close"); + closeButton.setActionCommand("CLOSE"); + closeButton.addActionListener(this); + closePanel.add(closeButton); + add(closePanel, BorderLayout.SOUTH); + } + + /** + * Returns a panel with the demo content. The panel + * uses a BorderLayout(), and the BorderLayout.SOUTH area + * is empty, to allow callers to add controls to the + * bottom of the panel if they want to (a close button is + * added if this demo is being run as a standalone demo). + */ + private void createContent() + { + setLayout(new BorderLayout()); + JPanel panel = createScrollBarPanel(); + add(panel); + } + + private JPanel createScrollBarPanel() + { + JPanel panel = new JPanel(new BorderLayout()); + + JPanel horizontalPanel = new JPanel(); + + JScrollBar scroll1a = new JScrollBar(JScrollBar.HORIZONTAL); + JScrollBar scroll1b = new JScrollBar(JScrollBar.HORIZONTAL); + scroll1b.setEnabled(false); + JScrollBar scroll1c = new JScrollBar(JScrollBar.HORIZONTAL); + scroll1c.putClientProperty("JScrollBar.isFreeStanding", Boolean.FALSE); + JScrollBar scroll1d = new JScrollBar(JScrollBar.HORIZONTAL); + scroll1d.putClientProperty("JScrollBar.isFreeStanding", Boolean.FALSE); + scroll1d.setEnabled(false); + horizontalPanel.add(scroll1a); + horizontalPanel.add(scroll1b); + horizontalPanel.add(scroll1c); + horizontalPanel.add(scroll1d); + + panel.add(horizontalPanel, BorderLayout.NORTH); + + JPanel verticalPanel = new JPanel(); + verticalPanel.setLayout(new GridLayout(1, 7)); + + JScrollBar scroll2a = new JScrollBar(JScrollBar.VERTICAL); + JScrollBar scroll2b = new JScrollBar(JScrollBar.VERTICAL); + scroll2b.setEnabled(false); + JScrollBar scroll2c = new JScrollBar(JScrollBar.VERTICAL); + scroll2c.putClientProperty("JScrollBar.isFreeStanding", Boolean.FALSE); + JScrollBar scroll2d = new JScrollBar(JScrollBar.VERTICAL); + scroll2d.setEnabled(false); + scroll2d.putClientProperty("JScrollBar.isFreeStanding", Boolean.FALSE); + + verticalPanel.add(scroll2a); + verticalPanel.add(new JPanel()); + verticalPanel.add(scroll2b); + verticalPanel.add(new JPanel()); + verticalPanel.add(scroll2c); + verticalPanel.add(new JPanel()); + verticalPanel.add(scroll2d); + + panel.add(verticalPanel, BorderLayout.EAST); + + JPanel centerPanel = new JPanel(new GridLayout(1, 2)); + centerPanel.add(new JScrollBar(JScrollBar.HORIZONTAL)); + centerPanel.add(new JScrollBar(JScrollBar.VERTICAL)); + panel.add(centerPanel); + return panel; + } + + public void actionPerformed(ActionEvent e) + { + if (e.getActionCommand().equals("CLOSE")) + { + System.exit(0); + } + } + + public static void main(String[] args) + { + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + ScrollBarDemo app = new ScrollBarDemo(); + app.initFrameContent(); + JFrame frame = new JFrame("ScrollBar Demo"); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + }}); + } + + /** + * Returns a DemoFactory that creates a ScrollBarDemo. + * + * @return a DemoFactory that creates a ScrollBarDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new ScrollBarDemo(); + } + }; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/SliderDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/SliderDemo.java new file mode 100644 index 000000000..76d68c984 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/SliderDemo.java @@ -0,0 +1,287 @@ +/* SliderDemo.java -- An example showing JSlider in various configurations. + Copyright (C) 2005, 2006, Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. +*/ + + +package gnu.classpath.examples.swing; + +import java.awt.BorderLayout; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JSlider; +import javax.swing.SwingUtilities; + +public class SliderDemo + extends JPanel + implements ActionListener +{ + + JSlider hslider1; + JSlider hslider2; + JSlider hslider3; + JSlider hslider4; + JSlider hslider5; + JSlider hslider6; + JSlider hslider7; + JSlider hslider8; + + JSlider vslider1; + JSlider vslider2; + JSlider vslider3; + JSlider vslider4; + JSlider vslider5; + JSlider vslider6; + JSlider vslider7; + JSlider vslider8; + + JCheckBox enabledCheckBox; + + public SliderDemo() + { + createContent(); + } + + /** + * When the demo is run independently, the frame is displayed, so we should + * initialise the content panel (including the demo content and a close + * button). But when the demo is run as part of the Swing activity board, + * only the demo content panel is used, the frame itself is never displayed, + * so we can avoid this step. + */ + void initFrameContent() + { + JPanel closePanel = new JPanel(); + JButton closeButton = new JButton("Close"); + closeButton.setActionCommand("CLOSE"); + closeButton.addActionListener(this); + closePanel.add(closeButton); + add(closePanel, BorderLayout.SOUTH); + } + + /** + * Returns a panel with the demo content. The panel + * uses a BorderLayout(), and the BorderLayout.SOUTH area + * is empty, to allow callers to add controls to the + * bottom of the panel if they want to (a close button is + * added if this demo is being run as a standalone demo). + */ + private void createContent() + { + setLayout(new BorderLayout()); + JPanel panel = new JPanel(new GridLayout(1, 2)); + panel.add(createHorizontalPanel()); + panel.add(createVerticalPanel()); + enabledCheckBox = new JCheckBox("Enabled"); + enabledCheckBox.setSelected(true); + enabledCheckBox.setActionCommand("TOGGLE_ENABLED"); + enabledCheckBox.addActionListener(this); + JPanel checkBoxPanel = new JPanel(); + checkBoxPanel.add(enabledCheckBox); + JPanel panel2 = new JPanel(new BorderLayout()); + panel2.add(panel); + panel2.add(checkBoxPanel, BorderLayout.SOUTH); + add(panel2); + } + + private JPanel createHorizontalPanel() + { + JPanel panel = new JPanel(new GridLayout(8, 1)); + + hslider1 = new JSlider(JSlider.HORIZONTAL, 0, 100, 35); + panel.add(hslider1); + + hslider2 = new JSlider(JSlider.HORIZONTAL, 0, 100, 35); + hslider2.setMajorTickSpacing(20); + hslider2.setMinorTickSpacing(5); + hslider2.setPaintTicks(true); + panel.add(hslider2); + + hslider3 = new JSlider(JSlider.HORIZONTAL, 0, 100, 35); + hslider3.setMajorTickSpacing(20); + hslider3.setMinorTickSpacing(5); + hslider3.setPaintLabels(true); + hslider3.setPaintTicks(true); + panel.add(hslider3); + + hslider4 = new JSlider(JSlider.HORIZONTAL, 0, 100, 35); + hslider4.putClientProperty("JSlider.isFilled", Boolean.TRUE); + hslider4.setMajorTickSpacing(20); + hslider4.setMinorTickSpacing(5); + hslider4.setPaintLabels(true); + hslider4.setPaintTicks(true); + panel.add(hslider4); + + hslider5 = new JSlider(JSlider.HORIZONTAL, 0, 100, 35); + hslider5.setInverted(true); + panel.add(hslider5); + + hslider6 = new JSlider(JSlider.HORIZONTAL, 0, 100, 35); + hslider6.setInverted(true); + hslider6.setMajorTickSpacing(20); + hslider6.setMinorTickSpacing(5); + hslider6.setPaintTicks(true); + panel.add(hslider6); + + hslider7 = new JSlider(JSlider.HORIZONTAL, 0, 100, 35); + hslider7.setInverted(true); + hslider7.setMajorTickSpacing(20); + hslider7.setMinorTickSpacing(5); + hslider7.setPaintLabels(true); + hslider7.setPaintTicks(true); + panel.add(hslider7); + + hslider8 = new JSlider(JSlider.HORIZONTAL, 0, 100, 35); + hslider8.putClientProperty("JSlider.isFilled", Boolean.TRUE); + hslider8.setInverted(true); + hslider8.setMajorTickSpacing(20); + hslider8.setMinorTickSpacing(5); + hslider8.setPaintLabels(true); + hslider8.setPaintTicks(true); + panel.add(hslider8); + + return panel; + } + + private JPanel createVerticalPanel() + { + JPanel panel = new JPanel(new GridLayout(1, 8)); + + vslider1 = new JSlider(JSlider.VERTICAL, 0, 100, 35); + panel.add(vslider1); + + vslider2 = new JSlider(JSlider.VERTICAL, 0, 100, 35); + vslider2.setMajorTickSpacing(20); + vslider2.setMinorTickSpacing(5); + vslider2.setPaintTicks(true); + panel.add(vslider2); + + vslider3 = new JSlider(JSlider.VERTICAL, 0, 100, 35); + vslider3.setMajorTickSpacing(20); + vslider3.setMinorTickSpacing(5); + vslider3.setPaintLabels(true); + vslider3.setPaintTicks(true); + panel.add(vslider3); + + vslider4 = new JSlider(JSlider.VERTICAL, 0, 100, 35); + vslider4.putClientProperty("JSlider.isFilled", Boolean.TRUE); + vslider4.setMajorTickSpacing(20); + vslider4.setMinorTickSpacing(5); + vslider4.setPaintLabels(true); + vslider4.setPaintTicks(true); + panel.add(vslider4); + + vslider5 = new JSlider(JSlider.VERTICAL, 0, 100, 35); + vslider5.setInverted(true); + panel.add(vslider5); + + vslider6 = new JSlider(JSlider.VERTICAL, 0, 100, 35); + vslider6.setInverted(true); + vslider6.setMajorTickSpacing(20); + vslider6.setMinorTickSpacing(5); + vslider6.setPaintTicks(true); + panel.add(vslider6); + + vslider7 = new JSlider(JSlider.VERTICAL, 0, 100, 35); + vslider7.setInverted(true); + vslider7.setMajorTickSpacing(20); + vslider7.setMinorTickSpacing(5); + vslider7.setPaintLabels(true); + vslider7.setPaintTicks(true); + panel.add(vslider7); + + vslider8 = new JSlider(JSlider.VERTICAL, 0, 100, 35); + vslider8.putClientProperty("JSlider.isFilled", Boolean.TRUE); + vslider8.setInverted(true); + vslider8.setMajorTickSpacing(20); + vslider8.setMinorTickSpacing(5); + vslider8.setPaintLabels(true); + vslider8.setPaintTicks(true); + panel.add(vslider8); + return panel; + } + + public void actionPerformed(ActionEvent e) + { + if (e.getActionCommand().equals("CLOSE")) + { + System.exit(0); + } + else if (e.getActionCommand().equals("TOGGLE_ENABLED")) + { + boolean enabled = enabledCheckBox.isSelected(); + hslider1.setEnabled(enabled); + hslider2.setEnabled(enabled); + hslider3.setEnabled(enabled); + hslider4.setEnabled(enabled); + hslider5.setEnabled(enabled); + hslider6.setEnabled(enabled); + hslider7.setEnabled(enabled); + hslider8.setEnabled(enabled); + vslider1.setEnabled(enabled); + vslider2.setEnabled(enabled); + vslider3.setEnabled(enabled); + vslider4.setEnabled(enabled); + vslider5.setEnabled(enabled); + vslider6.setEnabled(enabled); + vslider7.setEnabled(enabled); + vslider8.setEnabled(enabled); + } + } + public static void main(String[] args) + { + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + SliderDemo app = new SliderDemo(); + app.initFrameContent(); + JFrame frame = new JFrame("Slider Demo"); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + } + }); + } + + + /** + * Returns a DemoFactory that creates a SliderDemo. + * + * @return a DemoFactory that creates a SliderDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new SliderDemo(); + } + }; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/SpinnerDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/SpinnerDemo.java new file mode 100644 index 000000000..abf72bce2 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/SpinnerDemo.java @@ -0,0 +1,235 @@ +/* SpinnerDemo.java -- An example showing various spinners in Swing. + Copyright (C) 2006, Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. +*/ + + +package gnu.classpath.examples.swing; + +import java.awt.BorderLayout; +import java.awt.Font; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.Calendar; +import java.util.Date; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JSpinner; +import javax.swing.SpinnerDateModel; +import javax.swing.SpinnerListModel; +import javax.swing.SpinnerNumberModel; +import javax.swing.SwingUtilities; + +/** + * A simple demo showing various spinners in different states. + */ +public class SpinnerDemo + extends JPanel + implements ActionListener +{ + private JCheckBox spinnerState1; + private JSpinner spinner1; + private JSpinner spinner2; + + private JCheckBox spinnerState2; + private JSpinner spinner3; + private JSpinner spinner4; + + private JCheckBox spinnerState3; + private JSpinner spinner5; + private JSpinner spinner6; + + /** + * Creates a new demo instance. + */ + public SpinnerDemo() + { + super(); + createContent(); + } + + /** + * When the demo is run independently, the frame is displayed, so we should + * initialise the content panel (including the demo content and a close + * button). But when the demo is run as part of the Swing activity board, + * only the demo content panel is used, the frame itself is never displayed, + * so we can avoid this step. + */ + void initFrameContent() + { + JPanel closePanel = new JPanel(); + JButton closeButton = new JButton("Close"); + closeButton.setActionCommand("CLOSE"); + closeButton.addActionListener(this); + closePanel.add(closeButton); + add(closePanel, BorderLayout.SOUTH); + } + + /** + * Returns a panel with the demo content. The panel + * uses a BorderLayout(), and the BorderLayout.SOUTH area + * is empty, to allow callers to add controls to the + * bottom of the panel if they want to (a close button is + * added if this demo is being run as a standalone demo). + */ + private void createContent() + { + setLayout(new BorderLayout()); + JPanel panel = new JPanel(new GridLayout(3, 1)); + panel.add(createPanel1()); + panel.add(createPanel2()); + panel.add(createPanel3()); + add(panel); + } + + private JPanel createPanel1() + { + JPanel panel = new JPanel(new BorderLayout()); + this.spinnerState1 = new JCheckBox("Enabled", true); + this.spinnerState1.setActionCommand("COMBO_STATE1"); + this.spinnerState1.addActionListener(this); + panel.add(this.spinnerState1, BorderLayout.EAST); + + JPanel controlPanel = new JPanel(); + controlPanel.setBorder(BorderFactory.createTitledBorder( + "Number Spinner: ")); + this.spinner1 = new JSpinner(new SpinnerNumberModel(5.0, 0.0, 10.0, 0.5)); + this.spinner2 = new JSpinner(new SpinnerNumberModel(50, 0, 100, 5)); + this.spinner2.setFont(new Font("Dialog", Font.PLAIN, 20)); + controlPanel.add(this.spinner1); + controlPanel.add(this.spinner2); + + panel.add(controlPanel); + + return panel; + } + + private JPanel createPanel2() + { + JPanel panel = new JPanel(new BorderLayout()); + this.spinnerState2 = new JCheckBox("Enabled", true); + this.spinnerState2.setActionCommand("COMBO_STATE2"); + this.spinnerState2.addActionListener(this); + panel.add(this.spinnerState2, BorderLayout.EAST); + + JPanel controlPanel = new JPanel(); + controlPanel.setBorder(BorderFactory.createTitledBorder("Date Spinner: ")); + this.spinner3 = new JSpinner(new SpinnerDateModel(new Date(), null, null, + Calendar.DATE)); + + this.spinner4 = new JSpinner(new SpinnerDateModel(new Date(), null, null, + Calendar.YEAR)); + this.spinner4.setFont(new Font("Dialog", Font.PLAIN, 20)); + + controlPanel.add(this.spinner3); + controlPanel.add(this.spinner4); + + panel.add(controlPanel); + + return panel; + } + + private JPanel createPanel3() + { + JPanel panel = new JPanel(new BorderLayout()); + this.spinnerState3 = new JCheckBox("Enabled", true); + this.spinnerState3.setActionCommand("COMBO_STATE3"); + this.spinnerState3.addActionListener(this); + panel.add(this.spinnerState3, BorderLayout.EAST); + + JPanel controlPanel = new JPanel(); + controlPanel.setBorder(BorderFactory.createTitledBorder("List Spinner: ")); + this.spinner5 = new JSpinner(new SpinnerListModel(new Object[] {"Red", + "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet"})); + + this.spinner6 = new JSpinner(new SpinnerListModel(new Object[] {"Red", + "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet"})); + this.spinner6.setValue("Yellow"); + this.spinner6.setFont(new Font("Dialog", Font.PLAIN, 20)); + + controlPanel.add(this.spinner5); + controlPanel.add(this.spinner6); + + panel.add(controlPanel); + + return panel; + } + + public void actionPerformed(ActionEvent e) + { + if (e.getActionCommand().equals("COMBO_STATE1")) + { + spinner1.setEnabled(spinnerState1.isSelected()); + spinner2.setEnabled(spinnerState1.isSelected()); + } + else if (e.getActionCommand().equals("COMBO_STATE2")) + { + spinner3.setEnabled(spinnerState2.isSelected()); + spinner4.setEnabled(spinnerState2.isSelected()); + } + else if (e.getActionCommand().equals("COMBO_STATE3")) + { + spinner5.setEnabled(spinnerState3.isSelected()); + spinner6.setEnabled(spinnerState3.isSelected()); + } + else if (e.getActionCommand().equals("CLOSE")) + { + System.exit(0); + } + } + + public static void main(String[] args) + { + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + SpinnerDemo app = new SpinnerDemo(); + app.initFrameContent(); + JFrame frame = new JFrame("Spinner Demo"); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + } + }); + } + + /** + * Returns a DemoFactory that creates a SpinnerDemo. + * + * @return a DemoFactory that creates a SpinnerDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new SpinnerDemo(); + } + }; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/TabbedPaneDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/TabbedPaneDemo.java new file mode 100644 index 000000000..7cf02ce29 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/TabbedPaneDemo.java @@ -0,0 +1,256 @@ +/* TabbedPaneDemo.java -- Demonstrates JTabbedPane + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.swing; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JMenu; +import javax.swing.JMenuItem; +import javax.swing.JPanel; +import javax.swing.JPopupMenu; +import javax.swing.JScrollPane; +import javax.swing.JTabbedPane; +import javax.swing.JTextArea; +import javax.swing.SwingConstants; +import javax.swing.SwingUtilities; + +public class TabbedPaneDemo + extends JPanel + implements ActionListener +{ + static Color[] colors = { Color.BLUE, Color.CYAN, Color.GRAY, Color.GREEN, + Color.MAGENTA, Color.ORANGE, Color.PINK, + Color.ORANGE, Color.RED, Color.BLUE, Color.YELLOW + }; + TabbedPaneDemo() + { + super(); + createContent(); + } + + private void createContent() + { + JPanel p = new JPanel(); + p.setLayout(new GridLayout(1, 1)); + + int COUNT = 25; + JTabbedPane tp = createTabbedPane(SwingConstants.TOP, "tab", COUNT); + p.add(tp); + + final JPopupMenu popup = new JPopupMenu(); + + JMenu menu = new JMenu("tab placement"); + menu.add(createPlacementChangingMenuItem("top", + SwingConstants.TOP, + tp)); + + menu.add(createPlacementChangingMenuItem("bottom", + SwingConstants.BOTTOM, + tp)); + + menu.add(createPlacementChangingMenuItem("left", + SwingConstants.LEFT, + tp)); + + menu.add(createPlacementChangingMenuItem("right", + SwingConstants.RIGHT, + tp)); + popup.add(menu); + + menu = new JMenu("tab layout"); + menu.add(createLayoutPolicyChangingMenuItem("wrapping tabs", + JTabbedPane.WRAP_TAB_LAYOUT, + tp)); + + menu.add(createLayoutPolicyChangingMenuItem("scrolling tabs", + JTabbedPane.SCROLL_TAB_LAYOUT, + tp)); + popup.add(menu); + + tp.addMouseListener(new MouseAdapter() + { + public void mousePressed(MouseEvent e) { + showPopup(e); + } + + public void mouseReleased(MouseEvent e) { + showPopup(e); + } + + void showPopup(MouseEvent e) { + if (e.isPopupTrigger()) { + popup.show(e.getComponent(), e.getX(), e.getY()); + } + } + }); + + setLayout(new BorderLayout()); + add(p, BorderLayout.CENTER); + + } + + private JMenuItem createPlacementChangingMenuItem(String t, + final int v, + final JTabbedPane dst) + { + JMenuItem item = new JMenuItem(t); + + item.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent ae) + { + dst.setTabPlacement(v); + } + }); + + return item; + } + + private JMenuItem createLayoutPolicyChangingMenuItem(String t, + final int v, + final JTabbedPane dst) + { + JMenuItem item = new JMenuItem(t); + + item.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent ae) + { + dst.setTabLayoutPolicy(v); + } + }); + + return item; + } + + private JTabbedPane createTabbedPane(int direction, String name, int count) + { + JTabbedPane pane = new JTabbedPane(direction); + + for(int i = 0; i< count; i++) + { + pane.addTab(name + " " + i, createTabContent(name + " " + i)); + if (Math.random() >= 0.75) + pane.setEnabledAt(i, false); + } + + return pane; + } + + private JPanel createTabContent(String name) + { + JTextArea ta; + JPanel panel = new JPanel(); + panel.add(new JLabel(name)); + panel.add(new JButton(name)); + panel.add(new JScrollPane(ta = new JTextArea(5, 5))); + + ta.setBackground(colors[(int) (Math.random() * colors.length)]); + + return panel; + } + + public void actionPerformed(ActionEvent e) + { + if (e.getActionCommand().equals("CLOSE")) + { + System.exit(0); + } + } + + /** + * When the demo is run independently, the frame is displayed, so we should + * initialise the content panel (including the demo content and a close + * button). But when the demo is run as part of the Swing activity board, + * only the demo content panel is used, the frame itself is never displayed, + * so we can avoid this step. + */ + void initFrameContent() + { + JPanel closePanel = new JPanel(); + JButton closeButton = new JButton("Close"); + closeButton.setActionCommand("CLOSE"); + closeButton.addActionListener(this); + closePanel.add(closeButton); + add(closePanel, BorderLayout.SOUTH); + } + + public static void main(String[] args) + { + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + TabbedPaneDemo app = new TabbedPaneDemo(); + app.initFrameContent(); + JFrame frame = new JFrame("TabbedPane Demo"); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + } + }); + } + + /** + * Returns a DemoFactory that creates a TabbedPaneDemo. + * + * @return a DemoFactory that creates a TabbedPaneDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new TabbedPaneDemo(); + } + }; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/TableDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/TableDemo.java new file mode 100644 index 000000000..6aa9ba558 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/TableDemo.java @@ -0,0 +1,410 @@ +/* TableDemo.java -- Demonstrates the use of JTable. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.swing; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import javax.swing.AbstractCellEditor; +import javax.swing.BorderFactory; +import javax.swing.DefaultCellEditor; +import javax.swing.Icon; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JScrollBar; +import javax.swing.JScrollPane; +import javax.swing.JSlider; +import javax.swing.JTable; +import javax.swing.SwingUtilities; +import javax.swing.border.Border; +import javax.swing.plaf.metal.MetalIconFactory; +import javax.swing.table.DefaultTableColumnModel; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.TableCellEditor; +import javax.swing.table.TableCellRenderer; +import javax.swing.table.TableColumn; +import javax.swing.table.TableColumnModel; + +/** + * Displays the editable table. The first column consists of check boxes. + * + * @author Audrius Meskauskas (audriusa@bioinformatics.org) + */ +public class TableDemo extends JPanel +{ + /** + * The initial row count for this table. + */ + static int rows = 32; + + /** + * The initial column count for this table. + */ + static int cols = 7; + + + /** + * The table model. + */ + class TModel extends DefaultTableModel + { + + /** + * All cells are editable in our table. + */ + public boolean isCellEditable(int row, int column) + { + return true; + } + + /** + * Get the number of the table rows. + */ + public int getRowCount() + { + return rows; + } + + /** + * Get the number of the table columns. + */ + public int getColumnCount() + { + return cols; + } + + /** + * Set the value at the given position + */ + public void setValueAt(Object aValue, int aRow, int aColumn) + { + values[aRow][aColumn] = aValue; + } + + /** + * Get the value at the given position. + */ + public Object getValueAt(int aRow, int aColumn) + { + return values[aRow][aColumn]; + } + + /** + * The column name, as suggested by model. This header should not be + * visible, as it is overridden by setting the header name with + * {@link TableColumn#setHeaderValue} in {@link TableDemo#createContent}. + */ + public String getColumnName(int column) + { + return "Error "+column; + } + + /** + * The first column contains booleans, the second - icons, + * others - default class. + */ + public Class getColumnClass(int column) + { + if (column == 0) + return Boolean.class; + else if (column == 1) + return Icon.class; + else + return super.getColumnClass(column); + } + } + + /** + * The scroll bar renderer. + */ + class SliderCell + extends AbstractCellEditor + implements TableCellEditor, TableCellRenderer + { + /** + * The editor bar. + */ + JSlider bar; + + /** + * The renderer bar. + */ + JSlider rendererBar; + + /** + * The border around the bar, if required. + */ + Border border = BorderFactory.createLineBorder(table.getGridColor()); + + SliderCell() + { + bar = new JSlider(); + bar.setOrientation(JScrollBar.HORIZONTAL); + bar.setMinimum(0); + bar.setMaximum(rows); + bar.setBorder(border); + + rendererBar = new JSlider(); + rendererBar.setMinimum(0); + rendererBar.setMaximum(rows); + rendererBar.setEnabled(false); + } + + /** + * Get the editor. + */ + public Component getTableCellEditorComponent(JTable table, Object value, + boolean isSelected, int row, + int column) + { + if (value instanceof Integer) + bar.setValue(((Integer) value).intValue()); + return bar; + } + + /** + * Get the renderer. + */ + public Component getTableCellRendererComponent(JTable table, Object value, + boolean isSelected, + boolean hasFocus, int row, + int column) + { + rendererBar.setValue(((Integer) value).intValue()); + if (hasFocus) + rendererBar.setBorder(border); + else + rendererBar.setBorder(null); + return rendererBar; + } + + public Object getCellEditorValue() + { + return new Integer(bar.getValue()); + } + + } + + /** + * The table being displayed. + */ + JTable table = new JTable(); + + /** + * The table model. + */ + TModel model = new TModel(); + + /** + * The table value array. + */ + Object[][] values; + + /** + * The icons that appear in the icon column. + */ + Icon[] icons = new Icon[] + { + MetalIconFactory.getTreeComputerIcon(), + MetalIconFactory.getTreeHardDriveIcon(), + MetalIconFactory.getTreeFolderIcon(), + }; + + /** + * The choices in the combo boxes + */ + String [] sides = new String[] + { + "north", "south", "east", "west" + }; + + + /** + * Create the table demo with the given titel. + */ + public TableDemo() + { + super(); + createContent(); + } + + /** + * Returns a panel with the demo content. The panel uses a BorderLayout(), and + * the BorderLayout.SOUTH area is empty, to allow callers to add controls to + * the bottom of the panel if they want to (a close button is added if this + * demo is being run as a standalone demo). + */ + private void createContent() + { + setLayout(new BorderLayout()); + values = new Object[rows][]; + + for (int i = 0; i < values.length; i++) + { + values[i] = new Object[cols]; + for (int j = 3; j < cols; j++) + { + values[i][j] = "" + ((char) ('a' + j)) + i; + } + values [i][0] = i % 2 == 0? Boolean.TRUE : Boolean.FALSE; + values [i][1] = icons [ i % icons.length ]; + values [i][2] = sides [ i % sides.length ]; + values [i][4] = new Integer(i); + } + + table.setModel(model); + + // Make the columns with gradually increasing width: + DefaultTableColumnModel cm = new DefaultTableColumnModel(); + table.setColumnModel(cm); + + for (int i = 0; i < cols; i++) + { + TableColumn column = new TableColumn(i); + + // Showing the variable width columns. + int width = 100+10*i; + column.setPreferredWidth(width); + + // If we do not set the header value here, the value, returned + // by model, is used. + column.setHeaderValue("Width +"+(20*i)); + + cm.addColumn(column); + } + + setCustomEditors(); + setInformativeHeaders(); + + // Create the table, place it into scroll pane and place + // the pane into this frame. + JScrollPane scroll = new JScrollPane(); + + // The horizontal scroll bar is never needed. + scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + scroll.getViewport().add(table); + add(scroll, BorderLayout.CENTER); + + // Increase the row height to make the icons and sliders look better. + table.setRowHeight(table.getRowHeight()+2); + } + + /** + * Set the more informative column headers for specific columns. + */ + void setInformativeHeaders() + { + TableColumnModel cm = table.getColumnModel(); + + cm.getColumn(0).setHeaderValue("check"); + cm.getColumn(1).setHeaderValue("icon"); + cm.getColumn(2).setHeaderValue("combo"); + cm.getColumn(3).setHeaderValue("edit combo"); + cm.getColumn(4).setHeaderValue("slider"); + } + + /** + * Set the custom editors for combo boxes. This method also sets one + * custom renderer. + */ + void setCustomEditors() + { + TableColumnModel cm = table.getColumnModel(); + + // Set combo-box based editor for icons (note that no custom + // renderer is needed for JComboBox to work with icons. + JComboBox combo0 = new JComboBox(icons); + cm.getColumn(1).setCellEditor(new DefaultCellEditor(combo0)); + + // Set the simple combo box editor for the third column: + JComboBox combo1 = new JComboBox(sides); + cm.getColumn(2).setCellEditor(new DefaultCellEditor(combo1)); + + // Set the editable combo box for the forth column: + JComboBox combo2 = new JComboBox(sides); + combo2.setEditable(true); + cm.getColumn(3).setCellEditor(new DefaultCellEditor(combo2)); + + SliderCell scrollView = new SliderCell(); + cm.getColumn(4).setCellEditor(scrollView); + cm.getColumn(4).setCellRenderer(scrollView); + + table.setColumnModel(cm); + } + + /** + * The executable method to display the editable table. + * + * @param args + * unused. + */ + public static void main(String[] args) + { + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + TableDemo demo = new TableDemo(); + JFrame frame = new JFrame(); + frame.getContentPane().add(demo); + frame.setSize(new Dimension(640, 100)); + frame.setVisible(true); + } + }); + } + + /** + * Returns a DemoFactory that creates a TableDemo. + * + * @return a DemoFactory that creates a TableDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new TableDemo(); + } + }; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/TextAreaDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/TextAreaDemo.java new file mode 100644 index 000000000..5381f7ead --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/TextAreaDemo.java @@ -0,0 +1,620 @@ +/* TextAreaDemo.java -- An example showing various textareas in Swing. + Copyright (C) 2005, 2006 Free Software Foundation, Inc. + + This file is part of GNU Classpath examples. + + GNU Classpath is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + GNU Classpath is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. + */ + + +package gnu.classpath.examples.swing; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.GridLayout; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Shape; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTabbedPane; +import javax.swing.JTextArea; +import javax.swing.SwingUtilities; +import javax.swing.text.BadLocationException; +import javax.swing.text.DefaultCaret; +import javax.swing.text.Highlighter; +import javax.swing.text.JTextComponent; +import javax.swing.text.View; +import javax.swing.text.LayeredHighlighter.LayerPainter; + +/** + * A simple textare demo showing various textareas in different states. + */ +public class TextAreaDemo + extends JPanel + implements ActionListener +{ + + /** + * A custom caret for demonstration purposes. This class is inspired by the + * CornerCaret from the OReilly Swing book. + * + * @author Roman Kennke (kennke@aicas.com) + */ + static class CornerCaret + extends DefaultCaret + { + public CornerCaret() + { + super(); + setBlinkRate(500); + } + + protected synchronized void damage(Rectangle r) + { + if (r == null) + return; + x = r.x; + y = r.y + (r.height * 4 / 5 - 3); + width = 5; + height = 5; + repaint(); + } + + public void paint(Graphics g) + { + JTextComponent comp = getComponent(); + if (comp == null) + return; + int dot = getDot(); + Rectangle r = null; + try + { + r = comp.modelToView(dot); + } + catch (BadLocationException e) + { + return; + } + if (r == null) + return; + int dist = r.height * 4 / 5 - 3; + if ((x != r.x) || (y != r.y + dist)) + { + repaint(); + x = r.x; + y = r.y + dist; + width = 5; + height = 5; + } + if (isVisible()) + { + g.drawLine(r.x, r.y + dist, r.x, r.y + dist + 4); + g.drawLine(r.x, r.y + dist + 4, r.x + 4, r.y + dist + 4); + } + } + } + + static class DemoHighlightPainter + extends LayerPainter + { + static DemoHighlightPainter INSTANCE = new DemoHighlightPainter(); + + static Color[] colors = { Color.BLUE, Color.CYAN, Color.GRAY, Color.GREEN, + Color.MAGENTA, Color.ORANGE, Color.PINK, + Color.ORANGE, Color.RED, Color.BLUE, Color.YELLOW }; + + public DemoHighlightPainter() + { + super(); + } + + private void paintHighlight(Graphics g, Rectangle rect) + { + g.fillRect(rect.x, rect.y, rect.width, rect.height); + } + + public void paint(Graphics g, int p0, int p1, Shape bounds, JTextComponent t) + { + try + { + + for (int i = p0; i < p1; i++) + { + Rectangle r = t.modelToView(i); + Point l1 = t.modelToView(i + 1).getLocation(); + + g.setColor(colors[(int) (Math.random() * colors.length)]); + g.fillOval(r.x, r.y, l1.x - r.x, r.height); + } + } + catch (BadLocationException ble) + { + } + + } + + public Shape paintLayer(Graphics g, int p0, int p1, Shape bounds, + JTextComponent c, View view) + { + paint(g, p0, p1, bounds, c); + + return bounds; + } + } + + /** + * The non wrapping text areas and state buttons. + */ + JTextArea textarea1; + + JTextArea textarea2; + + JTextArea textarea3; + + JCheckBox enabled1; + + JCheckBox editable1; + + JPanel panel1; + + /** + * The char wrapping textareas and state buttons. + */ + JTextArea textarea4; + + JTextArea textarea5; + + JTextArea textarea6; + + JCheckBox enabled2; + + JCheckBox editable2; + + /** + * The word wrapping textareas and state buttons. + */ + JTextArea textarea7; + + JTextArea textarea8; + + JTextArea textarea9; + + JCheckBox enabled3; + + JCheckBox editable3; + + /** + * The custom colored textareas and state buttons. + */ + JTextArea textarea10; + + JTextArea textarea11; + + JTextArea textarea12; + + JTextArea textarea13; + + JTextArea textarea14; + + JTextArea textarea14b; + + JCheckBox enabled4; + + JCheckBox editable4; + + /** + * Some miscellaneous textarea demos. + */ + JTextArea textarea15; + + JTextArea textarea16; + + JTextArea textarea17; + + JCheckBox enabled5; + + JCheckBox editable5; + + /** + * Creates a new demo instance. + */ + public TextAreaDemo() + { + super(); + createContent(); + } + + /** + * When the demo is run independently, the frame is displayed, so we should + * initialise the content panel (including the demo content and a close + * button). But when the demo is run as part of the Swing activity board, only + * the demo content panel is used, the frame itself is never displayed, so we + * can avoid this step. + */ + void initFrameContent() + { + JPanel closePanel = new JPanel(); + JButton closeButton = new JButton("Close"); + closeButton.setActionCommand("CLOSE"); + closeButton.addActionListener(this); + closePanel.add(closeButton); + add(closePanel, BorderLayout.SOUTH); + } + + /** + * Returns a panel with the demo content. The panel uses a BorderLayout(), and + * the BorderLayout.SOUTH area is empty, to allow callers to add controls to + * the bottom of the panel if they want to (a close button is added if this + * demo is being run as a standalone demo). + */ + private void createContent() + { + setLayout(new BorderLayout()); + JTabbedPane tabPane = new JTabbedPane(); + tabPane.addTab("Non-wrap", createNonWrapPanel()); + tabPane.addTab("Char-wrap", createCharWrapPanel()); + tabPane.addTab("Word-wrap", createWordWrapPanel()); + tabPane.addTab("Custom colors", createCustomColoredPanel()); + tabPane.addTab("Misc", createMiscPanel()); + add(tabPane); + } + + private JPanel createNonWrapPanel() + { + JPanel panel = new JPanel(new BorderLayout()); + panel.setBorder(BorderFactory.createTitledBorder("Not wrapping")); + + panel1 = new JPanel(new GridLayout(2, 2)); + + textarea1 = new JTextArea("Hello World!"); + textarea1.setFont(new Font("Dialog", Font.PLAIN, 8)); + panel1.add(new JScrollPane(textarea1)); + + textarea2 = new JTextArea("Hello World!"); + textarea2.setFont(new Font("Dialog", Font.ITALIC, 12)); + panel1.add(new JScrollPane(textarea2)); + + textarea3 = new JTextArea("Hello World!"); + textarea3.setFont(new Font("Dialog", Font.BOLD, 14)); + panel1.add(new JScrollPane(textarea3)); + + panel.add(panel1); + + JPanel statePanel = new JPanel(); + statePanel.setLayout(new BoxLayout(statePanel, BoxLayout.Y_AXIS)); + statePanel.add(Box.createVerticalGlue()); + enabled1 = new JCheckBox("enabled"); + enabled1.setSelected(true); + enabled1.addActionListener(this); + enabled1.setActionCommand("ENABLED1"); + statePanel.add(enabled1); + editable1 = new JCheckBox("editable"); + editable1.setSelected(true); + editable1.addActionListener(this); + editable1.setActionCommand("EDITABLE1"); + statePanel.add(editable1); + statePanel.add(Box.createVerticalGlue()); + panel.add(statePanel, BorderLayout.EAST); + + return panel; + } + + private JPanel createCharWrapPanel() + { + JPanel panel = new JPanel(new BorderLayout()); + panel.setBorder(BorderFactory.createTitledBorder("Wrap at char bounds")); + + JPanel innerPanel = new JPanel(new GridLayout(2, 2)); + + textarea4 = new JTextArea("Hello World!"); + textarea4.setLineWrap(true); + textarea4.setFont(new Font("Dialog", Font.PLAIN, 8)); + innerPanel.add(new JScrollPane(textarea4)); + + textarea5 = new JTextArea("Hello World!"); + textarea5.setLineWrap(true); + textarea5.setFont(new Font("Dialog", Font.ITALIC, 12)); + innerPanel.add(new JScrollPane(textarea5)); + + textarea6 = new JTextArea("Hello World!"); + textarea6.setLineWrap(true); + textarea6.setFont(new Font("Dialog", Font.BOLD, 14)); + innerPanel.add(new JScrollPane(textarea6)); + + panel.add(innerPanel); + + JPanel statePanel = new JPanel(); + statePanel.setLayout(new BoxLayout(statePanel, BoxLayout.Y_AXIS)); + statePanel.add(Box.createVerticalGlue()); + enabled2 = new JCheckBox("enabled"); + enabled2.setSelected(true); + enabled2.addActionListener(this); + enabled2.setActionCommand("ENABLED2"); + statePanel.add(enabled2); + editable2 = new JCheckBox("editable"); + editable2.setSelected(true); + editable2.addActionListener(this); + editable2.setActionCommand("EDITABLE2"); + statePanel.add(editable2); + statePanel.add(Box.createVerticalGlue()); + panel.add(statePanel, BorderLayout.EAST); + + return panel; + } + + private JPanel createWordWrapPanel() + { + JPanel panel = new JPanel(new BorderLayout()); + panel.setBorder(BorderFactory.createTitledBorder("Wrap at word bounds")); + + JPanel innerPanel = new JPanel(new GridLayout(2, 2)); + + textarea7 = new JTextArea("Hello World!"); + textarea7.setWrapStyleWord(true); + textarea7.setLineWrap(true); + textarea7.setFont(new Font("Dialog", Font.PLAIN, 8)); + innerPanel.add(new JScrollPane(textarea7)); + + textarea8 = new JTextArea("Hello World!"); + textarea8.setWrapStyleWord(true); + textarea8.setLineWrap(true); + textarea8.setFont(new Font("Dialog", Font.ITALIC, 12)); + innerPanel.add(new JScrollPane(textarea8)); + + textarea9 = new JTextArea("Hello World!"); + textarea9.setWrapStyleWord(true); + textarea9.setLineWrap(true); + textarea9.setFont(new Font("Dialog", Font.BOLD, 14)); + innerPanel.add(new JScrollPane(textarea9)); + + panel.add(innerPanel); + + JPanel statePanel = new JPanel(); + statePanel.setLayout(new BoxLayout(statePanel, BoxLayout.Y_AXIS)); + statePanel.add(Box.createVerticalGlue()); + enabled3 = new JCheckBox("enabled"); + enabled3.setSelected(true); + enabled3.addActionListener(this); + enabled3.setActionCommand("ENABLED3"); + statePanel.add(enabled3); + editable3 = new JCheckBox("editable"); + editable3.setSelected(true); + editable3.addActionListener(this); + editable3.setActionCommand("EDITABLE3"); + statePanel.add(editable3); + statePanel.add(Box.createVerticalGlue()); + panel.add(statePanel, BorderLayout.EAST); + + return panel; + } + + private JPanel createCustomColoredPanel() + { + JPanel panel = new JPanel(new BorderLayout()); + + JPanel innerPanel = new JPanel(new GridLayout(3, 2)); + panel.setBorder(BorderFactory.createTitledBorder("Custom colors")); + + textarea10 = new JTextArea("custom foreground", 10, 15); + textarea10.setForeground(Color.GREEN); + innerPanel.add(new JScrollPane(textarea10)); + + textarea11 = new JTextArea("custom background", 10, 15); + textarea11.setBackground(Color.YELLOW); + innerPanel.add(new JScrollPane(textarea11)); + + textarea12 = new JTextArea("custom disabled textcolor", 10, 15); + textarea12.setDisabledTextColor(Color.BLUE); + innerPanel.add(new JScrollPane(textarea12)); + + textarea13 = new JTextArea("custom selected text color", 10, 15); + textarea13.setSelectedTextColor(Color.RED); + innerPanel.add(new JScrollPane(textarea13)); + + textarea14 = new JTextArea("custom selection color", 10, 15); + textarea14.setSelectionColor(Color.RED); + innerPanel.add(new JScrollPane(textarea14)); + + textarea14b = new JTextArea("custom selection and selected text color", 10, 15); + textarea14b.setSelectedTextColor(Color.WHITE); + textarea14b.setSelectionColor(Color.BLACK); + innerPanel.add(new JScrollPane(textarea14b)); + + panel.add(innerPanel); + + JPanel statePanel = new JPanel(); + statePanel.setLayout(new BoxLayout(statePanel, BoxLayout.Y_AXIS)); + statePanel.add(Box.createVerticalGlue()); + enabled4 = new JCheckBox("enabled"); + enabled4.setSelected(true); + enabled4.addActionListener(this); + enabled4.setActionCommand("ENABLED4"); + statePanel.add(enabled4); + editable4 = new JCheckBox("editable"); + editable4.setSelected(true); + editable4.addActionListener(this); + editable4.setActionCommand("EDITABLE4"); + statePanel.add(editable4); + statePanel.add(Box.createVerticalGlue()); + panel.add(statePanel, BorderLayout.EAST); + + return panel; + } + + private JPanel createMiscPanel() + { + JPanel panel = new JPanel(new BorderLayout()); + panel.setBorder(BorderFactory.createTitledBorder("Miscellaneous")); + + JPanel innerPanel = new JPanel(new GridLayout(2, 2)); + + textarea15 = new JTextArea("Custom Caret"); + textarea15.setCaret(new CornerCaret()); + innerPanel.add(new JScrollPane(textarea15)); + + textarea16 = new JTextArea("Custom Caret color"); + textarea16.setCaretColor(Color.MAGENTA); + innerPanel.add(new JScrollPane(textarea16)); + + textarea16 = new JTextArea("Custom Selection painter"); + textarea16.setFont(new Font("Dialog", Font.PLAIN, 24)); + textarea16.setCaret(new DefaultCaret() + { + public Highlighter.HighlightPainter getSelectionPainter() + { + return DemoHighlightPainter.INSTANCE; + } + }); + + innerPanel.add(new JScrollPane(textarea16)); + + panel.add(innerPanel); + + JPanel statePanel = new JPanel(); + statePanel.setLayout(new BoxLayout(statePanel, BoxLayout.Y_AXIS)); + statePanel.add(Box.createVerticalGlue()); + enabled5 = new JCheckBox("enabled"); + enabled5.setSelected(true); + enabled5.addActionListener(this); + enabled5.setActionCommand("ENABLED5"); + statePanel.add(enabled5); + editable5 = new JCheckBox("editable"); + editable5.setSelected(true); + editable5.addActionListener(this); + editable5.setActionCommand("EDITABLE5"); + statePanel.add(editable5); + statePanel.add(Box.createVerticalGlue()); + panel.add(statePanel, BorderLayout.EAST); + + return panel; + } + + public void actionPerformed(ActionEvent e) + { + if (e.getActionCommand().equals("CLOSE")) + { + System.exit(0); + } + else if (e.getActionCommand().equals("ENABLED1")) + { + boolean enabled = enabled1.isSelected(); + textarea1.setEnabled(enabled); + textarea2.setEnabled(enabled); + textarea3.setEnabled(enabled); + } + else if (e.getActionCommand().equals("EDITABLE1")) + { + boolean editable = editable1.isSelected(); + textarea1.setEditable(editable); + textarea2.setEditable(editable); + textarea3.setEditable(editable); + } + else if (e.getActionCommand().equals("ENABLED2")) + { + boolean enabled = enabled2.isSelected(); + textarea4.setEnabled(enabled); + textarea5.setEnabled(enabled); + textarea6.setEnabled(enabled); + } + else if (e.getActionCommand().equals("EDITABLE2")) + { + boolean editable = editable2.isSelected(); + textarea4.setEditable(editable); + textarea5.setEditable(editable); + textarea6.setEditable(editable); + } + else if (e.getActionCommand().equals("ENABLED3")) + { + boolean enabled = enabled3.isSelected(); + textarea7.setEnabled(enabled); + textarea8.setEnabled(enabled); + textarea9.setEnabled(enabled); + } + else if (e.getActionCommand().equals("EDITABLE3")) + { + boolean editable = editable3.isSelected(); + textarea7.setEditable(editable); + textarea8.setEditable(editable); + textarea9.setEditable(editable); + } + else if (e.getActionCommand().equals("ENABLED4")) + { + boolean enabled = enabled4.isSelected(); + textarea10.setEnabled(enabled); + textarea11.setEnabled(enabled); + textarea12.setEnabled(enabled); + textarea13.setEnabled(enabled); + textarea14.setEnabled(enabled); + textarea14b.setEnabled(enabled); + } + else if (e.getActionCommand().equals("EDITABLE4")) + { + boolean editable = editable4.isSelected(); + textarea10.setEditable(editable); + textarea11.setEditable(editable); + textarea12.setEditable(editable); + textarea13.setEditable(editable); + textarea14.setEditable(editable); + textarea14b.setEditable(editable); + } + } + + public static void main(String[] args) + { + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + TextAreaDemo app = new TextAreaDemo(); + app.initFrameContent(); + JFrame frame = new JFrame(); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + } + }); + } + + /** + * Returns a DemoFactory that creates a TextAreaDemo. + * + * @return a DemoFactory that creates a TextAreaDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new TextAreaDemo(); + } + }; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/TextFieldDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/TextFieldDemo.java new file mode 100644 index 000000000..e63022880 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/TextFieldDemo.java @@ -0,0 +1,594 @@ +/* TextFieldDemo.java -- An example showing various textfields in Swing. + Copyright (C) 2005, 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. +*/ + + +package gnu.classpath.examples.swing; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.GridLayout; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Shape; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextField; +import javax.swing.SwingUtilities; +import javax.swing.border.CompoundBorder; +import javax.swing.border.EmptyBorder; +import javax.swing.border.LineBorder; +import javax.swing.border.TitledBorder; +import javax.swing.text.BadLocationException; +import javax.swing.text.DefaultCaret; +import javax.swing.text.Highlighter; +import javax.swing.text.JTextComponent; +import javax.swing.text.View; +import javax.swing.text.LayeredHighlighter.LayerPainter; + +/** + * A simple textfield demo showing various textfields in different states. + */ +public class TextFieldDemo + extends JPanel + implements ActionListener +{ + + /** + * A custom caret for demonstration purposes. This class is inspired by the + * CornerCaret from the OReilly Swing book. + * + * @author Roman Kennke (kennke@aicas.com) + */ + static class CornerCaret extends DefaultCaret + { + public CornerCaret() + { + super(); + setBlinkRate(500); + } + + protected synchronized void damage(Rectangle r) + { + if (r == null) return; + x = r.x; + y = r.y + (r.height * 4 / 5 - 3); + width = 5; + height = 5; + repaint(); + } + + public void paint(Graphics g) + { + JTextComponent comp = getComponent(); + if (comp == null) return; + int dot = getDot(); + Rectangle r = null; + try + { + r = comp.modelToView(dot); + } + catch (BadLocationException e) + { + return; + } + if (r == null) return; + int dist = r.height * 4 / 5 - 3; + if ((x != r.x) || (y != r.y + dist)) + { + repaint(); + x = r.x; + y = r.y + dist; + width = 5; + height = 5; + } + if (isVisible()) + { + g.drawLine(r.x, r.y + dist, r.x, r.y + dist + 4); + g.drawLine(r.x, r.y + dist + 4, r.x + 4, r.y + dist + 4); + } + } + } + + static class DemoHighlightPainter + extends LayerPainter + { + + static DemoHighlightPainter INSTANCE = new DemoHighlightPainter(); + + + static Color[] colors = { Color.BLUE, Color.CYAN, Color.GRAY, Color.GREEN, + Color.MAGENTA, Color.ORANGE, Color.PINK, + Color.ORANGE, Color.RED, Color.BLUE, Color.YELLOW }; + + + public DemoHighlightPainter() + { + super(); + } + + private void paintHighlight(Graphics g, Rectangle rect) + { + g.fillRect(rect.x, rect.y, rect.width, rect.height); + } + + public void paint(Graphics g, int p0, int p1, Shape bounds, JTextComponent t) + { + try + { + + for (int i = p0; i < p1; i++) + { + Rectangle r = t.modelToView(i); + Point l1 = t.modelToView(i + 1).getLocation(); + + g.setColor(colors[(int) (Math.random() * colors.length)]); + g.fillOval(r.x, r.y, l1.x - r.x, r.height); + } + } + catch (BadLocationException ble) + { + } + } + + public Shape paintLayer(Graphics g, int p0, int p1, Shape bounds, + JTextComponent c, View view) + { + paint(g, p0, p1, bounds, c); + + return bounds; + } + + } + + /** + * The left aligned textfields and state buttons. + */ + Compound compound1; + + /** + * The right aligned textfields and state buttons. + */ + Compound compound2; + + /** + * The centered textfields and state buttons. + */ + Compound compound3; + + /** + * The custom colored textfields and state buttons. + */ + Compound compound4; + Compound compound5; + + /** + * Some miscellaneous textfield demos. + */ + Compound compound6; + + /** + * Some textfields with custom borders. + */ + Compound compound7; + + /** + * Creates a new demo instance. + */ + public TextFieldDemo() + { + super(); + createContent(); + } + + /** + * When the demo is run independently, the frame is displayed, so we should + * initialise the content panel (including the demo content and a close + * button). But when the demo is run as part of the Swing activity board, + * only the demo content panel is used, the frame itself is never displayed, + * so we can avoid this step. + */ + void initFrameContent() + { + JPanel closePanel = new JPanel(); + JButton closeButton = new JButton("Close"); + closeButton.setActionCommand("CLOSE"); + closeButton.addActionListener(this); + closePanel.add(closeButton); + add(closePanel, BorderLayout.SOUTH); + } + + /** + * Returns a panel with the demo content. The panel + * uses a BorderLayout(), and the BorderLayout.SOUTH area + * is empty, to allow callers to add controls to the + * bottom of the panel if they want to (a close button is + * added if this demo is being run as a standalone demo). + */ + private void createContent() + { + setLayout(new BorderLayout()); + JPanel panel = new JPanel(new GridLayout(7, 1)); + panel.add(createLeftAlignedPanel()); + panel.add(createRightAlignedPanel()); + panel.add(createCenteredPanel()); + panel.add(createCustomColorPanel1()); + panel.add(createCustomColorPanel2()); + panel.add(createCustomBordersPanel()); + panel.add(createMiscPanel()); + + // Put everything in a scroll pane to make it neccessary + // to reach the bottom inner panels if the screen is to small. + add(new JScrollPane(panel)); + } + + private JPanel createLeftAlignedPanel() + { + compound1 = createTextFieldCompound("Left aligned", 1); + + compound1.setupTextfields("Hello World!", + JTextField.LEFT, + new Font[] { new Font("Dialog", Font.PLAIN, 8), + new Font("Dialog", Font.ITALIC, 12), + new Font("Dialog", Font.BOLD, 14) + }); + + return compound1.panel; + } + + private Compound createTextFieldCompound(String title, int actionCommandNo) + { + Compound compound = new Compound(); + compound.panel = new JPanel(new BorderLayout()); + compound.panel.setBorder(BorderFactory.createTitledBorder(title)); + + compound.textFieldPanel = new JPanel(); + compound.textFieldPanel.setLayout(new BoxLayout(compound.textFieldPanel, BoxLayout.X_AXIS)); + + compound.panel.add(compound.textFieldPanel); + + JPanel statePanel = new JPanel(); + statePanel.setLayout(new BoxLayout(statePanel, BoxLayout.Y_AXIS)); + statePanel.add(Box.createVerticalGlue()); + compound.enabled = new JCheckBox("enabled"); + compound.enabled.setSelected(true); + compound.enabled.addActionListener(this); + compound.enabled.setActionCommand("ENABLED" + actionCommandNo); + statePanel.add(compound.enabled); + compound.editable = new JCheckBox("editable"); + compound.editable.setSelected(true); + compound.editable.addActionListener(this); + compound.editable.setActionCommand("EDITABLE" + actionCommandNo); + statePanel.add(compound.editable); + statePanel.add(Box.createVerticalGlue()); + compound.panel.add(statePanel, BorderLayout.EAST); + + return compound; + } + + private JPanel createRightAlignedPanel() + { + compound2 = createTextFieldCompound("Right aligned", 2); + + compound2.setupTextfields("Hello World!", + JTextField.RIGHT, + new Font[] { new Font("Dialog", Font.PLAIN, 8), + new Font("Dialog", Font.ITALIC, 12), + new Font("Dialog", Font.BOLD, 14) + }); + + return compound2.panel; + } + + private JPanel createCenteredPanel() + { + compound3 = createTextFieldCompound("Centered", 3); + + compound3.setupTextfields("Hello World!", + JTextField.CENTER, + new Font[] { new Font("Dialog", Font.PLAIN, 8), + new Font("Dialog", Font.ITALIC, 12), + new Font("Dialog", Font.BOLD, 14) + }); + + return compound3.panel; + } + + private JPanel createCustomColorPanel1() + { + compound4 = createTextFieldCompound("Custom colors I", 4); + + compound4.textfield1 = new JTextField("custom foreground"); + compound4.textfield1.setForeground(Color.RED); + compound4.textFieldPanel.add(compound4.textfield1); + + compound4.textfield2 = new JTextField("custom background"); + compound4.textfield2.setBackground(Color.YELLOW); + compound4.textFieldPanel.add(compound4.textfield2); + + compound4.textfield3 = new JTextField("custom foreground and background"); + compound4.textfield3.setForeground(Color.RED); + compound4.textfield3.setBackground(Color.YELLOW); + compound4.textFieldPanel.add(compound4.textfield3); + + return compound4.panel; + + } + + private JPanel createCustomColorPanel2() + { + compound5 = createTextFieldCompound("Custom colors II", 5); + + compound5.textfield1 = new JTextField("custom disabled textcolor"); + compound5.textfield1.setDisabledTextColor(Color.BLUE); + compound5.textFieldPanel.add(compound5.textfield1); + + compound5.textfield2 = new JTextField("custom selected text color"); + compound5.textfield2.setSelectedTextColor(Color.RED); + compound5.textFieldPanel.add(compound5.textfield2); + + compound5.textfield3 = new JTextField("custom selection color"); + compound5.textfield3.setSelectionColor(Color.BLACK); + compound5.textFieldPanel.add(compound5.textfield3); + + return compound5.panel; + + } + + private JPanel createMiscPanel() + { + compound6 = createTextFieldCompound("Miscellaneous", 6); + + compound6.textfield1 = new JTextField("Custom Caret"); + compound6.textfield1.setCaret(new CornerCaret()); + compound6.textFieldPanel.add(compound6.textfield1); + + compound6.textfield2 = new JTextField("Custom Caret color"); + compound6.textfield2.setForeground(Color.LIGHT_GRAY); + compound6.textfield2.setBackground(Color.BLACK); + compound6.textfield2.setSelectedTextColor(Color.BLACK); + compound6.textfield2.setCaretColor(Color.WHITE); + compound6.textfield2.setSelectionColor(Color.DARK_GRAY); + compound6.textFieldPanel.add(compound6.textfield2); + + compound6.textfield3 = new JTextField("Custom highlighter"); + compound6.textfield3.setCaret(new DefaultCaret() + { + public Highlighter.HighlightPainter getSelectionPainter() + { + return DemoHighlightPainter.INSTANCE; + } + }); + compound6.textFieldPanel.add(compound6.textfield3); + + return compound6.panel; + } + + private JPanel createCustomBordersPanel() + { + compound7 = createTextFieldCompound("Custom borders", 7); + + compound7.textfield1 = new JTextField("red 5 pixel lineborder"); + compound7.textfield1.setBorder(new LineBorder(Color.RED, 5)); + compound7.textFieldPanel.add(compound7.textfield1); + + compound7.textfield2 = new JTextField("complex irregular border"); + + CompoundBorder innerCompound = new CompoundBorder(new EmptyBorder(5, 40, 15, 10), new LineBorder(Color.BLACK)); + CompoundBorder outerCompound = new CompoundBorder(new LineBorder(Color.BLACK), innerCompound); + compound7.textfield2.setBorder(outerCompound); + compound7.textFieldPanel.add(compound7.textfield2); + + compound7.textfield3 = new JTextField("a titled border", 10); + compound7.textfield3.setBorder(new TitledBorder(null, "Freak Out Border", TitledBorder.CENTER, TitledBorder.LEFT)); + compound7.textFieldPanel.add(compound7.textfield3); + + return compound7.panel; + } + + public void actionPerformed(ActionEvent e) + { + if (e.getActionCommand().equals("CLOSE")) + { + System.exit(0); + } + else if (e.getActionCommand().equals("ENABLED1")) + { + boolean enabled = compound1.enabled.isSelected(); + compound1.textfield1.setEnabled(enabled); + compound1.textfield2.setEnabled(enabled); + compound1.textfield3.setEnabled(enabled); + } + else if (e.getActionCommand().equals("EDITABLE1")) + { + boolean editable = compound1.editable.isSelected(); + compound1.textfield1.setEditable(editable); + compound1.textfield2.setEditable(editable); + compound1.textfield3.setEditable(editable); + } + else if (e.getActionCommand().equals("ENABLED2")) + { + boolean enabled = compound2.enabled.isSelected(); + compound2.textfield1.setEnabled(enabled); + compound2.textfield2.setEnabled(enabled); + compound2.textfield3.setEnabled(enabled); + } + else if (e.getActionCommand().equals("EDITABLE2")) + { + boolean editable = compound2.editable.isSelected(); + compound2.textfield1.setEditable(editable); + compound2.textfield2.setEditable(editable); + compound2.textfield3.setEditable(editable); + } + else if (e.getActionCommand().equals("ENABLED3")) + { + boolean enabled = compound3.enabled.isSelected(); + compound3.textfield1.setEnabled(enabled); + compound3.textfield2.setEnabled(enabled); + compound3.textfield3.setEnabled(enabled); + } + else if (e.getActionCommand().equals("EDITABLE3")) + { + boolean editable = compound3.editable.isSelected(); + compound3.textfield1.setEditable(editable); + compound3.textfield2.setEditable(editable); + compound3.textfield3.setEditable(editable); + } + else if (e.getActionCommand().equals("ENABLED4")) + { + boolean enabled = compound4.enabled.isSelected(); + compound4.textfield1.setEnabled(enabled); + compound4.textfield2.setEnabled(enabled); + compound4.textfield3.setEnabled(enabled); + } + else if (e.getActionCommand().equals("EDITABLE4")) + { + boolean editable = compound4.editable.isSelected(); + compound4.textfield1.setEditable(editable); + compound4.textfield2.setEditable(editable); + compound4.textfield3.setEditable(editable); + } + else if (e.getActionCommand().equals("ENABLED5")) + { + boolean enabled = compound5.enabled.isSelected(); + compound5.textfield1.setEnabled(enabled); + compound5.textfield2.setEnabled(enabled); + compound5.textfield3.setEnabled(enabled); + } + else if (e.getActionCommand().equals("EDITABLE5")) + { + boolean editable = compound5.editable.isSelected(); + compound5.textfield1.setEditable(editable); + compound5.textfield2.setEditable(editable); + compound5.textfield3.setEditable(editable); + } + else if (e.getActionCommand().equals("ENABLED6")) + { + boolean enabled = compound6.enabled.isSelected(); + compound6.textfield1.setEnabled(enabled); + compound6.textfield2.setEnabled(enabled); + compound6.textfield3.setEnabled(enabled); + } + else if (e.getActionCommand().equals("EDITABLE6")) + { + boolean editable = compound6.editable.isSelected(); + compound6.textfield1.setEditable(editable); + compound6.textfield2.setEditable(editable); + compound6.textfield3.setEditable(editable); + } + else if (e.getActionCommand().equals("ENABLED7")) + { + boolean enabled = compound7.enabled.isSelected(); + compound7.textfield1.setEnabled(enabled); + compound7.textfield2.setEnabled(enabled); + compound7.textfield3.setEnabled(enabled); + } + else if (e.getActionCommand().equals("EDITABLE7")) + { + boolean editable = compound7.editable.isSelected(); + compound7.textfield1.setEditable(editable); + compound7.textfield2.setEditable(editable); + compound7.textfield3.setEditable(editable); + } + } + + public static void main(String[] args) + { + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + TextFieldDemo app = new TextFieldDemo(); + app.initFrameContent(); + JFrame frame = new JFrame("TextField demo"); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + } + }); + } + + /** + * Returns a DemoFactory that creates a TextFieldDemo. + * + * @return a DemoFactory that creates a TextFieldDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new TextFieldDemo(); + } + }; + } + + static class Compound + { + JTextField textfield1; + JTextField textfield2; + JTextField textfield3; + JCheckBox enabled; + JCheckBox editable; + JPanel textFieldPanel; + JPanel panel; + + /** Creates and initializes the textfields with the same text and + * alignment but with a different font. + * + * @param title The text for the textfields. + * @param align The alignment for the textfields. + * @param fonts The fonts to be used for the textfields. + */ + void setupTextfields(String title, int align, Font[] fonts) + { + textfield1 = new JTextField(title); + textfield1.setHorizontalAlignment(align); + textfield1.setFont(fonts[0]); + textFieldPanel.add(textfield1); + + textfield2 = new JTextField(title); + textfield2.setHorizontalAlignment(align); + textfield2.setFont(fonts[1]); + textFieldPanel.add(textfield2); + + textfield3 = new JTextField(title); + textfield3.setHorizontalAlignment(align); + textfield3.setFont(fonts[2]); + textFieldPanel.add(textfield3); + } + + } + +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/TreeDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/TreeDemo.java new file mode 100644 index 000000000..f8f7ae6b4 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/TreeDemo.java @@ -0,0 +1,318 @@ +/* TreeDemo.java -- Demostrates JTree + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.swing; + +import java.awt.BorderLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JScrollPane; +import javax.swing.JTree; +import javax.swing.SwingUtilities; +import javax.swing.event.TreeSelectionEvent; +import javax.swing.event.TreeSelectionListener; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeModel; +import javax.swing.tree.DefaultTreeSelectionModel; +import javax.swing.tree.TreePath; + +public class TreeDemo + extends JPanel + implements ActionListener +{ + + TreeDemo() + { + super(); + createContent(); + } + + private void createContent() + { + // non-leafs + DefaultMutableTreeNode root = new DefaultMutableTreeNode("Exotic Subsistence"); + DefaultMutableTreeNode fruit = new DefaultMutableTreeNode("Interesting Fruit"); + DefaultMutableTreeNode veg = new DefaultMutableTreeNode("Extraordinary Vegetables"); + DefaultMutableTreeNode liq = new DefaultMutableTreeNode("Peculiar Liquids"); + + // leafs + DefaultMutableTreeNode f1 = new DefaultMutableTreeNode("Abiu"); + DefaultMutableTreeNode f2 = new DefaultMutableTreeNode("Bamboo Shoots"); + DefaultMutableTreeNode f3 = new DefaultMutableTreeNode("Breadfruit"); + DefaultMutableTreeNode f4 = new DefaultMutableTreeNode("Canistel"); + DefaultMutableTreeNode f5 = new DefaultMutableTreeNode("Duku"); + DefaultMutableTreeNode f6 = new DefaultMutableTreeNode("Guava"); + DefaultMutableTreeNode f7 = new DefaultMutableTreeNode("Jakfruit"); + DefaultMutableTreeNode f8 = new DefaultMutableTreeNode("Quaribea"); + + DefaultMutableTreeNode v1 = new DefaultMutableTreeNode("Amaranth"); + DefaultMutableTreeNode v2 = new DefaultMutableTreeNode("Kiwano"); + DefaultMutableTreeNode v3 = new DefaultMutableTreeNode("Leeks"); + DefaultMutableTreeNode v4 = new DefaultMutableTreeNode("Luffa"); + DefaultMutableTreeNode v5 = new DefaultMutableTreeNode("Chayote"); + DefaultMutableTreeNode v6 = new DefaultMutableTreeNode("Jicama"); + DefaultMutableTreeNode v7 = new DefaultMutableTreeNode("Okra"); + + DefaultMutableTreeNode l1 = new DefaultMutableTreeNode("Alcoholic"); + DefaultMutableTreeNode l11 = new DefaultMutableTreeNode("Caipirinha"); + DefaultMutableTreeNode l21 = new DefaultMutableTreeNode("Mojito"); + DefaultMutableTreeNode l31 = new DefaultMutableTreeNode("Margarita"); + DefaultMutableTreeNode l41 = new DefaultMutableTreeNode("Martini"); + DefaultMutableTreeNode l5 = new DefaultMutableTreeNode("Non Alcoholic"); + DefaultMutableTreeNode l55 = new DefaultMutableTreeNode("Babaji"); + DefaultMutableTreeNode l65 = new DefaultMutableTreeNode("Chikita"); + + root.add(fruit); + root.add(veg); + root.add(liq); + fruit.add(f1); + fruit.add(f2); + fruit.add(f3); + fruit.add(f4); + fruit.add(f5); + fruit.add(f6); + fruit.add(f7); + fruit.add(f8); + veg.add(v1); + veg.add(v2); + veg.add(v3); + veg.add(v4); + veg.add(v5); + veg.add(v6); + veg.add(v7); + liq.add(l1); + l1.add(l11); + l1.add(l21); + l1.add(l31); + l1.add(l41); + liq.add(l5); + l5.add(l55); + l5.add(l65); + + final JTree tree = new JTree(root); + tree.setLargeModel(true); + tree.setEditable(true); + final DefaultTreeSelectionModel selModel = new DefaultTreeSelectionModel(); + selModel.setSelectionMode( + DefaultTreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); + tree.setSelectionModel(selModel); + + // buttons to add and delete + JButton add = new JButton("add element"); + add.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + for (int i = 0; i < tree.getRowCount(); i++) + { + if (tree.isRowSelected(i)) + { + TreePath p = tree.getPathForRow(i); + DefaultMutableTreeNode n = (DefaultMutableTreeNode) p. + getLastPathComponent(); + n.add(new DefaultMutableTreeNode("New Element")); + + // The expansion state of the parent node does not change + // by default. We will expand it manually, to ensure that the + // added node is immediately visible. + tree.expandPath(p); + + // Refresh the tree (.repaint would be not enough both in + // Classpath and Sun implementations). + DefaultTreeModel model = (DefaultTreeModel) tree.getModel(); + model.reload(n); + break; + } + } + } + }); + + // Demonstration of the various selection modes + final JCheckBox cbSingle = new JCheckBox("single selection"); + cbSingle.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + if (cbSingle.isSelected()) + selModel.setSelectionMode( + DefaultTreeSelectionModel.SINGLE_TREE_SELECTION); + else + selModel.setSelectionMode( + DefaultTreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); + } + }); + + // Demonstration of the root visibility changes + final JCheckBox cbRoot = new JCheckBox("root"); + cbRoot.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + tree.setRootVisible(cbRoot.isSelected()); + } + }); + cbRoot.setSelected(true); + + // Demonstration of the tree selection listener. + final JLabel choice = new JLabel("Make a choice"); + tree.getSelectionModel().addTreeSelectionListener( + new TreeSelectionListener() + { + public void valueChanged(TreeSelectionEvent event) + { + TreePath was = event.getOldLeadSelectionPath(); + TreePath now = event.getNewLeadSelectionPath(); + String swas = + was == null ? "none":was.getLastPathComponent().toString(); + String snow = + now == null ? "none":now.getLastPathComponent().toString(); + choice.setText("From "+swas+" to "+snow); + } + } + ); + + setLayout(new BorderLayout()); + + JPanel p2 = new JPanel(); + p2.add(add); + p2.add(cbSingle); + p2.add(cbRoot); + + tree.getSelectionModel(). + setSelectionMode(DefaultTreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); + + // Panel for selecting line style. + ActionListener l = new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + JRadioButton b = (JRadioButton) e.getSource(); + tree.putClientProperty("JTree.lineStyle", b.getText()); + tree.repaint(); + } + }; + JPanel lineStylePanel = new JPanel(); + ButtonGroup buttons = new ButtonGroup(); + lineStylePanel.add(new JLabel("Line style: ")); + JRadioButton none = new JRadioButton("None"); + lineStylePanel.add(none); + buttons.add(none); + none.addActionListener(l); + JRadioButton angled = new JRadioButton("Angled"); + lineStylePanel.add(angled); + buttons.add(angled); + angled.addActionListener(l); + JRadioButton horizontal = new JRadioButton("Horizontal"); + lineStylePanel.add(horizontal); + buttons.add(horizontal); + horizontal.addActionListener(l); + p2.add(lineStylePanel); + + add(p2, BorderLayout.NORTH); + + add(new JScrollPane(tree), BorderLayout.CENTER); + add(choice, BorderLayout.SOUTH); + } + + public void actionPerformed(ActionEvent e) + { + if (e.getActionCommand().equals("CLOSE")) + { + System.exit(0); + } + } + + /** + * When the demo is run independently, the frame is displayed, so we should + * initialise the content panel (including the demo content and a close + * button). But when the demo is run as part of the Swing activity board, + * only the demo content panel is used, the frame itself is never displayed, + * so we can avoid this step. + */ + void initFrameContent() + { + JPanel closePanel = new JPanel(); + JButton closeButton = new JButton("Close"); + closeButton.setActionCommand("CLOSE"); + closeButton.addActionListener(this); + closePanel.add(closeButton); + add(closePanel, BorderLayout.SOUTH); + } + + public static void main(String[] args) + { + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + TreeDemo app = new TreeDemo(); + app.initFrameContent(); + JFrame frame = new JFrame("Tree Demo"); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + } + }); + } + + /** + * Returns a DemoFactory that creates a TreeDemo. + * + * @return a DemoFactory that creates a TreeDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new TreeDemo(); + } + }; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/forms.html b/libjava/classpath/examples/gnu/classpath/examples/swing/forms.html new file mode 100644 index 000000000..010a94c93 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/forms.html @@ -0,0 +1,98 @@ + + + + + + HTML text styles + + +
+ Back to start page +

Some form elements

+

Textarea

+ + +

Input fields

+

+ + +

+ +

Buttons

+

+ + + +

+ +

Checkboxes and Radiobuttons

+

+ Check this! + Or this +

+

+ A radio button + Another radio +

+

Select lists and combo boxes

+

+ +

+

+ +

+
+ + \ No newline at end of file diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/frame1.html b/libjava/classpath/examples/gnu/classpath/examples/swing/frame1.html new file mode 100644 index 000000000..b9150592f --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/frame1.html @@ -0,0 +1,41 @@ + + + +

Top Left Frame

+ + diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/frame2.html b/libjava/classpath/examples/gnu/classpath/examples/swing/frame2.html new file mode 100644 index 000000000..9dbf33c5a --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/frame2.html @@ -0,0 +1,42 @@ + + + +

Top Right + Frame

+ + diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/frame3.html b/libjava/classpath/examples/gnu/classpath/examples/swing/frame3.html new file mode 100644 index 000000000..e677bd6a1 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/frame3.html @@ -0,0 +1,42 @@ + + + +

Bottom Left Frame

+ + + diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/frame4.html b/libjava/classpath/examples/gnu/classpath/examples/swing/frame4.html new file mode 100644 index 000000000..1da53b101 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/frame4.html @@ -0,0 +1,41 @@ + + + +

Bottom Left Frame

+ + diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/frames.html b/libjava/classpath/examples/gnu/classpath/examples/swing/frames.html new file mode 100644 index 000000000..e7e2bf87c --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/frames.html @@ -0,0 +1,44 @@ + + + + + + + + + \ No newline at end of file diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/tables.html b/libjava/classpath/examples/gnu/classpath/examples/swing/tables.html new file mode 100644 index 000000000..af908e1ab --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/tables.html @@ -0,0 +1,66 @@ + + + + + + HTML text styles + + +

Table examples

+

Table with grid and mixed rowspan/colspan

+ + + + + + + + + + + + + + + + + + + +
Spans two columnsSpans three rows
Spans two rowsThis is the center
This should be in the middle of row number 3
A small one cell boxSpans two x two cells
Another small one cell box
+ diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/textstyles.html b/libjava/classpath/examples/gnu/classpath/examples/swing/textstyles.html new file mode 100644 index 000000000..786e18b77 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/textstyles.html @@ -0,0 +1,78 @@ + + + + + + HTML text styles + + + Back to start page +

Colors

+

The following are the 16 named colors in HTML. Of course you can also + use all RGB colors by specifying a value in the #RRGGBB + notation.

+

+ Black, Gray, + Maroon, Red, + Green, Lime, + Olive, Yellow, + Navy, Blue, + Purple, Fuchsia, + Teal, Aqua, + Silver, White

+

Font styles

+

The following lists the logical and physical font styles that can be set + by certain HTML tags

+

+ +

Address
, Bold, Big, + Citation, Code, Deleted, + Emphasized, Italic, Inserted, Quote, + Stroke-Through, Example, Small, + Strike, Strong, Subscript, + Superscript, Underlined, Variable +

+

Header Level 1

+

Header Level 2

+

Header Level 3

+

Header Level 4

+
Header Level 5
+
Header Level 6
+
Some centered Text
+ + \ No newline at end of file diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/welcome.html b/libjava/classpath/examples/gnu/classpath/examples/swing/welcome.html new file mode 100644 index 000000000..8bc987494 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/welcome.html @@ -0,0 +1,63 @@ + + + + + GNU Classpath HTML Browser + + + +

Welcome to GNU Classpath

+

A couple of websites that you might want to try out

+ + +

Testpages

+

These few pages are here to demonstrate and test the HTML rendering + capabilities of GNU Classpath's Swing.

+ + + \ No newline at end of file -- cgit v1.2.3