summaryrefslogtreecommitdiff
path: root/libjava/classpath/examples
diff options
context:
space:
mode:
authorupstream source tree <ports@midipix.org>2015-03-15 20:14:05 -0400
committerupstream source tree <ports@midipix.org>2015-03-15 20:14:05 -0400
commit554fd8c5195424bdbcabf5de30fdc183aba391bd (patch)
tree976dc5ab7fddf506dadce60ae936f43f58787092 /libjava/classpath/examples
downloadcbb-gcc-4.6.4-554fd8c5195424bdbcabf5de30fdc183aba391bd.tar.bz2
cbb-gcc-4.6.4-554fd8c5195424bdbcabf5de30fdc183aba391bd.tar.xz
obtained gcc-4.6.4.tar.bz2 from upstream website;upstream
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.
Diffstat (limited to 'libjava/classpath/examples')
-rw-r--r--libjava/classpath/examples/.cvsignore6
-rw-r--r--libjava/classpath/examples/Makefile.am111
-rw-r--r--libjava/classpath/examples/Makefile.in597
-rw-r--r--libjava/classpath/examples/Makefile.java2d.in17
-rw-r--r--libjava/classpath/examples/Makefile.jawt.in29
-rw-r--r--libjava/classpath/examples/README89
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/NamingService/Demo.java200
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/Demo.java102
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/DemoServer.java118
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/DemoServant.java230
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/DemoTester.java111
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/DirectTest.java344
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/RequestTest.java284
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToPass.java66
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToPassHelper.java103
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToPassHolder.java37
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToReturn.java71
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToReturnHelper.java116
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToReturnHolder.java60
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/TreeNode.java60
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/TreeNodeHelper.java162
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/TreeNodeHolder.java100
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/WeThrowThisException.java75
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/WeThrowThisExceptionHelper.java117
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/_DemoTesterImplBase.java209
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/_DemoTesterStub.java429
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/README.html493
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/CanvasWorld.java307
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/ChatConstants.java80
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/ClientFrame.java417
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/Demo.java99
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/GameManager.java68
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/GameManagerImpl.java135
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/IorReader.java124
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/OrbStarter.java236
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/Player.java96
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/PlayerImpl.java275
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/PlayingDesk.java512
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/State.java82
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/X5Server.java175
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/_GameManagerImpl_Tie.java209
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/_GameManager_Stub.java207
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/_PlayerImpl_Tie.java209
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/CORBA/swing/x5/_Player_Stub.java397
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/awt/AicasGraphicsBenchmark.java1018
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/awt/AnimationApplet.java232
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/awt/Demo.java1189
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/awt/HintingDemo.java420
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/datatransfer/Demo.java652
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/html/Demo.java131
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/icons/aicas.pngbin0 -> 2320 bytes
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/icons/back.pngbin0 -> 828 bytes
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/icons/badge.pngbin0 -> 45862 bytes
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/icons/big-fullscreen.pngbin0 -> 3768 bytes
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/icons/big-home.pngbin0 -> 4135 bytes
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/icons/big-warning.pngbin0 -> 2250 bytes
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/icons/palme.gifbin0 -> 502 bytes
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/icons/reload.pngbin0 -> 1324 bytes
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/icons/stock-copy.pngbin0 -> 285 bytes
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/icons/stock-cut.pngbin0 -> 328 bytes
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/icons/stock-go-back.pngbin0 -> 523 bytes
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/icons/stock-go-down.pngbin0 -> 536 bytes
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/icons/stock-go-forward.pngbin0 -> 522 bytes
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/icons/stock-mic.pngbin0 -> 590 bytes
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/icons/stock-new.pngbin0 -> 349 bytes
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/icons/stock-open.pngbin0 -> 448 bytes
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/icons/stock-paste.pngbin0 -> 563 bytes
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/icons/stock-quit.pngbin0 -> 507 bytes
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/icons/stock-save-as.pngbin0 -> 751 bytes
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/icons/stock-save.pngbin0 -> 539 bytes
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/icons/stock-spell-check.pngbin0 -> 374 bytes
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/java2d/J2dBenchmark.java1571
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/java2d/J2dBenchmarkGUI.java891
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/java2d/JNIOverhead.java390
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/java2d/bench.c606
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/java2d/bench.h64
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/jawt/DemoJAWT.c150
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/jawt/DemoJAWT.java77
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/management/TestBeans.java40
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/management/TestClassLoading.java77
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/management/TestCompilation.java48
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/management/TestGarbageCollector.java50
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/management/TestMemory.java52
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/management/TestMemoryManager.java46
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/management/TestMemoryPool.java91
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/management/TestOS.java38
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/management/TestRuntime.java54
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/management/TestThread.java118
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/midi/Demo.java137
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/print/Demo.java391
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/sound/AudioPlayerSample.java222
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/BrowserEditorKit.java56
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/ButtonDemo.java319
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/ComboBoxDemo.java386
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/Demo.java629
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/DemoDesktop.java82
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/DemoFactory.java57
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/DocumentFilterDemo.java288
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/FileChooserDemo.java264
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/HtmlDemo.java379
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/ListDemo.java231
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/MetalThemeEditor.java585
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/MiniDemo.java233
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/NavigationFilterDemo.java205
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/ProgressBarDemo.java239
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/ScrollBarDemo.java174
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/SliderDemo.java287
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/SpinnerDemo.java235
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/TabbedPaneDemo.java256
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/TableDemo.java410
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/TextAreaDemo.java620
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/TextFieldDemo.java594
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/TreeDemo.java318
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/forms.html98
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/frame1.html41
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/frame2.html42
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/frame3.html42
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/frame4.html41
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/frames.html44
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/tables.html66
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/textstyles.html78
-rw-r--r--libjava/classpath/examples/gnu/classpath/examples/swing/welcome.html63
122 files changed, 24081 insertions, 0 deletions
diff --git a/libjava/classpath/examples/.cvsignore b/libjava/classpath/examples/.cvsignore
new file mode 100644
index 000000000..d79d635e8
--- /dev/null
+++ b/libjava/classpath/examples/.cvsignore
@@ -0,0 +1,6 @@
+Makefile
+Makefile.in
+examples.zip
+Makefile.jawt
+Makefile.java2d
+
diff --git a/libjava/classpath/examples/Makefile.am b/libjava/classpath/examples/Makefile.am
new file mode 100644
index 000000000..ff4780124
--- /dev/null
+++ b/libjava/classpath/examples/Makefile.am
@@ -0,0 +1,111 @@
+## Input file for automake to generate the Makefile.in used by configure
+GLIBJ_CLASSPATH='$(top_builddir)/lib/glibj.zip:$(top_builddir)/lib'
+
+if GCJ_JAVAC
+JCOMPILER = $(JAVAC) $(JAVACFLAGS) -fsource=1.5 -ftarget=1.5 --encoding=UTF-8 --bootclasspath=$(GLIBJ_CLASSPATH) --classpath='$(top_builddir)/tools/tools.zip'
+else
+JCOMPILER = $(JAVAC) $(JAVACFLAGS) -source 1.5 -target 1.5 -encoding UTF-8 -bootclasspath $(GLIBJ_CLASSPATH) -classpath '$(top_builddir)/tools/tools.zip'
+endif
+
+# All our example java source files
+EXAMPLE_JAVA_FILES = $(srcdir)/gnu/classpath/examples/*/*.java $(srcdir)/gnu/classpath/examples/*/*/*.java $(srcdir)/gnu/classpath/examples/*/*/*/*.java
+
+# The example C source & header files
+EXAMPLE_C_FILES = $(srcdir)/gnu/classpath/examples/*/*.c
+EXAMPLE_CH_FILES = $(srcdir)/gnu/classpath/examples/*/*.h
+
+# The zip files with classes we want to produce.
+EXAMPLE_ZIP = examples.zip
+
+# Extra objects that will not exist until configure-time
+BUILT_SOURCES = $(EXAMPLE_ZIP)
+
+# the png icons we use in some of the examples.
+EXAMPLE_ICONS = $(srcdir)/gnu/classpath/examples/icons/*.png
+EXAMPLE_ICONS += $(srcdir)/gnu/classpath/examples/icons/*.gif
+
+# the html pages we use in the swing demo example.
+EXAMPLE_HTML = $(srcdir)/gnu/classpath/examples/swing/*.html
+
+# The example specific README files.
+READMES = $(srcdir)/gnu/classpath/examples/CORBA/swing/README.html
+
+# All the files we find "interesting"
+ALL_EXAMPLE_FILES = $(EXAMPLE_JAVA_FILES) $(EXAMPLE_C_FILES) $(EXAMPLE_CH_FILES) $(EXAMPLE_ICONS) $(EXAMPLE_HTML) $(READMES)
+
+# Some architecture independent data to be installed.
+example_DATA = $(EXAMPLE_ZIP) README
+
+# Where we want these data files installed.
+exampledir = $(pkgdatadir)/examples
+
+# Make sure all sources and icons are also installed so users can use them.
+# (Be careful to strip off the srcdir part of the path when installing.)
+install-data-local:
+ srcdir_cnt=`echo $(srcdir) | wc -c`; \
+ for file in $(ALL_EXAMPLE_FILES); do \
+ f=`echo $$file | cut -c$$srcdir_cnt-`; \
+ fdir=`dirname $$f`; \
+ if test ! -d $(DESTDIR)$(pkgdatadir)/examples/$$fdir; then \
+ echo "$(mkinstalldirs) $(DESTDIR)$(pkgdatadir)/examples/$$fdir"; \
+ $(mkinstalldirs) $(DESTDIR)$(pkgdatadir)/examples/$$fdir; \
+ fi; \
+ echo "$(INSTALL_DATA) $$file $(DESTDIR)$(pkgdatadir)/examples/$$f"; \
+ $(INSTALL_DATA) $$file $(DESTDIR)$(pkgdatadir)/examples/$$f; \
+ done
+ echo "$(INSTALL_DATA) Makefile.jawt $(DESTDIR)$(pkgdatadir)/examples/"
+ echo "$(INSTALL_DATA) Makefile.java2d $(DESTDIR)$(pkgdatadir)/examples/"
+ $(INSTALL_DATA) Makefile.jawt $(DESTDIR)$(pkgdatadir)/examples/
+ $(INSTALL_DATA) Makefile.java2d $(DESTDIR)$(pkgdatadir)/examples/
+
+uninstall-local:
+ srcdir_cnt=`echo $(srcdir) | wc -c`; \
+ for file in $(ALL_EXAMPLE_FILES); do \
+ f=`echo $$file | cut -c$$srcdir_cnt-`; \
+ echo "rm -f $(DESTDIR)$(pkgdatadir)/examples/$$f"; \
+ rm -f $(DESTDIR)$(pkgdatadir)/examples/$$f; \
+ done
+ echo "rm -f $(DESTDIR)$(pkgdatadir)/examples/Makefile.jawt"
+ echo "rm -f $(DESTDIR)$(pkgdatadir)/examples/Makefile.java2d"
+ rm -f $(DESTDIR)$(pkgdatadir)/examples/Makefile.jawt
+ rm -f $(DESTDIR)$(pkgdatadir)/examples/Makefile.java2d
+
+# Make sure everything is included in the distribution.
+EXTRA_DIST = README Makefile.jawt.in Makefile.java2d.in
+dist-hook:
+ srcdir_cnt=`echo $(srcdir) | wc -c`; \
+ for file in $(ALL_EXAMPLE_FILES); do \
+ f=`echo $$file | cut -c$$srcdir_cnt-`; \
+ fdir=`dirname $$f`; \
+ if test ! -d $(distdir)/$$fdir; then \
+ echo "$(makeinstalldirs) $(distdir)/$$fdir"; \
+ $(mkinstalldirs) $(distdir)/$$fdir; \
+ fi; \
+ echo "cp -p $$file $(distdir)/$$f"; \
+ cp -p $$file $(distdir)/$$f; \
+ done
+
+# To generate the example zip just depend on the sources and ignore the
+# class files. Always regenerate all .class files and remove them immediatly.
+# And copy the png icons we use to the classes dir so they get also included.
+
+if WITH_JAR
+CREATE_EXAMPLE_ZIP=$(JAR) cf ../$(EXAMPLE_ZIP) .
+else
+CREATE_EXAMPLE_ZIP=$(ZIP) -r ../$(EXAMPLE_ZIP) .
+endif
+
+$(EXAMPLE_ZIP): $(EXAMPLE_JAVA_FILES)
+ @mkdir_p@ classes/gnu/classpath/examples/icons
+ cp $(EXAMPLE_ICONS) classes/gnu/classpath/examples/icons
+ @mkdir_p@ classes/gnu/classpath/examples/swing
+ cp $(EXAMPLE_HTML) classes/gnu/classpath/examples/swing
+ $(JCOMPILER) -d classes $(EXAMPLE_JAVA_FILES)
+ (cd classes; \
+ $(CREATE_EXAMPLE_ZIP); \
+ cd ..)
+ rm -rf classes
+
+# Zip file be gone! (and make sure the classes are gone too)
+clean-local:
+ rm -rf $(EXAMPLE_ZIP) classes
diff --git a/libjava/classpath/examples/Makefile.in b/libjava/classpath/examples/Makefile.in
new file mode 100644
index 000000000..be2e2ce57
--- /dev/null
+++ b/libjava/classpath/examples/Makefile.in
@@ -0,0 +1,597 @@
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
+# @configure_input@
+
+# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation,
+# Inc.
+# This Makefile.in is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
+# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE.
+
+@SET_MAKE@
+
+VPATH = @srcdir@
+pkgdatadir = $(datadir)/@PACKAGE@
+pkgincludedir = $(includedir)/@PACKAGE@
+pkglibdir = $(libdir)/@PACKAGE@
+pkglibexecdir = $(libexecdir)/@PACKAGE@
+am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
+install_sh_DATA = $(install_sh) -c -m 644
+install_sh_PROGRAM = $(install_sh) -c
+install_sh_SCRIPT = $(install_sh) -c
+INSTALL_HEADER = $(INSTALL_DATA)
+transform = $(program_transform_name)
+NORMAL_INSTALL = :
+PRE_INSTALL = :
+POST_INSTALL = :
+NORMAL_UNINSTALL = :
+PRE_UNINSTALL = :
+POST_UNINSTALL = :
+build_triplet = @build@
+host_triplet = @host@
+target_triplet = @target@
+subdir = examples
+DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \
+ $(srcdir)/Makefile.jawt.in $(srcdir)/Makefile.java2d.in
+ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
+am__aclocal_m4_deps = $(top_srcdir)/../../config/depstand.m4 \
+ $(top_srcdir)/../../config/lead-dot.m4 \
+ $(top_srcdir)/../../config/lib-ld.m4 \
+ $(top_srcdir)/../../config/lib-link.m4 \
+ $(top_srcdir)/../../config/lib-prefix.m4 \
+ $(top_srcdir)/../../config/multi.m4 \
+ $(top_srcdir)/../../config/no-executables.m4 \
+ $(top_srcdir)/../../config/override.m4 \
+ $(top_srcdir)/../../libtool.m4 \
+ $(top_srcdir)/../../ltoptions.m4 \
+ $(top_srcdir)/../../ltsugar.m4 \
+ $(top_srcdir)/../../ltversion.m4 \
+ $(top_srcdir)/../../lt~obsolete.m4 \
+ $(top_srcdir)/m4/ac_prog_antlr.m4 \
+ $(top_srcdir)/m4/ac_prog_java.m4 \
+ $(top_srcdir)/m4/ac_prog_java_works.m4 \
+ $(top_srcdir)/m4/ac_prog_javac.m4 \
+ $(top_srcdir)/m4/ac_prog_javac_works.m4 \
+ $(top_srcdir)/m4/acattribute.m4 $(top_srcdir)/m4/accross.m4 \
+ $(top_srcdir)/m4/acinclude.m4 \
+ $(top_srcdir)/m4/ax_create_stdint_h.m4 \
+ $(top_srcdir)/m4/ax_func_which_gethostbyname_r.m4 \
+ $(top_srcdir)/m4/gcc_attribute.m4 $(top_srcdir)/m4/iconv.m4 \
+ $(top_srcdir)/m4/pkg.m4 $(top_srcdir)/configure.ac
+am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
+ $(ACLOCAL_M4)
+mkinstalldirs = $(SHELL) $(top_srcdir)/../../mkinstalldirs
+CONFIG_HEADER = $(top_builddir)/include/config.h
+CONFIG_CLEAN_FILES = Makefile.jawt Makefile.java2d
+CONFIG_CLEAN_VPATH_FILES =
+SOURCES =
+am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
+am__vpath_adj = case $$p in \
+ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
+ *) f=$$p;; \
+ esac;
+am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
+am__install_max = 40
+am__nobase_strip_setup = \
+ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip = \
+ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list = $(am__nobase_strip_setup); \
+ for p in $$list; do echo "$$p $$p"; done | \
+ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
+ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
+ if (++n[$$2] == $(am__install_max)) \
+ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
+ END { for (dir in files) print dir, files[dir] }'
+am__base_list = \
+ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
+am__installdirs = "$(DESTDIR)$(exampledir)"
+DATA = $(example_DATA)
+ACLOCAL = @ACLOCAL@
+AMTAR = @AMTAR@
+ANTLR = @ANTLR@
+ANTLR_JAR = @ANTLR_JAR@
+AR = @AR@
+AUTOCONF = @AUTOCONF@
+AUTOHEADER = @AUTOHEADER@
+AUTOMAKE = @AUTOMAKE@
+AWK = @AWK@
+CAIRO_CFLAGS = @CAIRO_CFLAGS@
+CAIRO_LIBS = @CAIRO_LIBS@
+CC = @CC@
+CCDEPMODE = @CCDEPMODE@
+CFLAGS = @CFLAGS@
+CLASSPATH_CONVENIENCE = @CLASSPATH_CONVENIENCE@
+CLASSPATH_INCLUDES = @CLASSPATH_INCLUDES@
+CLASSPATH_MODULE = @CLASSPATH_MODULE@
+COLLECTIONS_PREFIX = @COLLECTIONS_PREFIX@
+CP = @CP@
+CPP = @CPP@
+CPPFLAGS = @CPPFLAGS@
+CXX = @CXX@
+CXXCPP = @CXXCPP@
+CXXDEPMODE = @CXXDEPMODE@
+CXXFLAGS = @CXXFLAGS@
+CYGPATH_W = @CYGPATH_W@
+DATE = @DATE@
+DEFAULT_PREFS_PEER = @DEFAULT_PREFS_PEER@
+DEFS = @DEFS@
+DEPDIR = @DEPDIR@
+DSYMUTIL = @DSYMUTIL@
+DUMPBIN = @DUMPBIN@
+ECHO_C = @ECHO_C@
+ECHO_N = @ECHO_N@
+ECHO_T = @ECHO_T@
+ECJ_JAR = @ECJ_JAR@
+EGREP = @EGREP@
+ERROR_CFLAGS = @ERROR_CFLAGS@
+EXAMPLESDIR = @EXAMPLESDIR@
+EXEEXT = @EXEEXT@
+EXTRA_CFLAGS = @EXTRA_CFLAGS@
+FGREP = @FGREP@
+FIND = @FIND@
+FREETYPE2_CFLAGS = @FREETYPE2_CFLAGS@
+FREETYPE2_LIBS = @FREETYPE2_LIBS@
+GCONF_CFLAGS = @GCONF_CFLAGS@
+GCONF_LIBS = @GCONF_LIBS@
+GDK_CFLAGS = @GDK_CFLAGS@
+GDK_LIBS = @GDK_LIBS@
+GJDOC = @GJDOC@
+GLIB_CFLAGS = @GLIB_CFLAGS@
+GLIB_LIBS = @GLIB_LIBS@
+GMP_CFLAGS = @GMP_CFLAGS@
+GMP_LIBS = @GMP_LIBS@
+GREP = @GREP@
+GSTREAMER_BASE_CFLAGS = @GSTREAMER_BASE_CFLAGS@
+GSTREAMER_BASE_LIBS = @GSTREAMER_BASE_LIBS@
+GSTREAMER_CFLAGS = @GSTREAMER_CFLAGS@
+GSTREAMER_FILE_READER = @GSTREAMER_FILE_READER@
+GSTREAMER_LIBS = @GSTREAMER_LIBS@
+GSTREAMER_MIXER_PROVIDER = @GSTREAMER_MIXER_PROVIDER@
+GSTREAMER_PLUGINS_BASE_CFLAGS = @GSTREAMER_PLUGINS_BASE_CFLAGS@
+GSTREAMER_PLUGINS_BASE_LIBS = @GSTREAMER_PLUGINS_BASE_LIBS@
+GST_PLUGIN_LDFLAGS = @GST_PLUGIN_LDFLAGS@
+GTK_CFLAGS = @GTK_CFLAGS@
+GTK_LIBS = @GTK_LIBS@
+INIT_LOAD_LIBRARY = @INIT_LOAD_LIBRARY@
+INSTALL = @INSTALL@
+INSTALL_DATA = @INSTALL_DATA@
+INSTALL_PROGRAM = @INSTALL_PROGRAM@
+INSTALL_SCRIPT = @INSTALL_SCRIPT@
+INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
+JAR = @JAR@
+JAVA = @JAVA@
+JAVAC = @JAVAC@
+JAVAC_IS_GCJ = @JAVAC_IS_GCJ@
+JAVAC_MEM_OPT = @JAVAC_MEM_OPT@
+JAVA_LANG_SYSTEM_EXPLICIT_INITIALIZATION = @JAVA_LANG_SYSTEM_EXPLICIT_INITIALIZATION@
+JAY = @JAY@
+JAY_SKELETON = @JAY_SKELETON@
+LD = @LD@
+LDFLAGS = @LDFLAGS@
+LIBDEBUG = @LIBDEBUG@
+LIBICONV = @LIBICONV@
+LIBMAGIC = @LIBMAGIC@
+LIBOBJS = @LIBOBJS@
+LIBS = @LIBS@
+LIBTOOL = @LIBTOOL@
+LIBVERSION = @LIBVERSION@
+LIPO = @LIPO@
+LN_S = @LN_S@
+LTLIBICONV = @LTLIBICONV@
+LTLIBOBJS = @LTLIBOBJS@
+MAINT = @MAINT@
+MAKEINFO = @MAKEINFO@
+MKDIR = @MKDIR@
+MKDIR_P = @MKDIR_P@
+MOC = @MOC@
+MOZILLA_CFLAGS = @MOZILLA_CFLAGS@
+MOZILLA_LIBS = @MOZILLA_LIBS@
+NM = @NM@
+NMEDIT = @NMEDIT@
+OBJDUMP = @OBJDUMP@
+OBJEXT = @OBJEXT@
+OTOOL = @OTOOL@
+OTOOL64 = @OTOOL64@
+PACKAGE = @PACKAGE@
+PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
+PACKAGE_NAME = @PACKAGE_NAME@
+PACKAGE_STRING = @PACKAGE_STRING@
+PACKAGE_TARNAME = @PACKAGE_TARNAME@
+PACKAGE_URL = @PACKAGE_URL@
+PACKAGE_VERSION = @PACKAGE_VERSION@
+PANGOFT2_CFLAGS = @PANGOFT2_CFLAGS@
+PANGOFT2_LIBS = @PANGOFT2_LIBS@
+PATH_SEPARATOR = @PATH_SEPARATOR@
+PATH_TO_ESCHER = @PATH_TO_ESCHER@
+PATH_TO_GLIBJ_ZIP = @PATH_TO_GLIBJ_ZIP@
+PERL = @PERL@
+PKG_CONFIG = @PKG_CONFIG@
+PLUGIN_DIR = @PLUGIN_DIR@
+QT_CFLAGS = @QT_CFLAGS@
+QT_LIBS = @QT_LIBS@
+RANLIB = @RANLIB@
+REMOVE = @REMOVE@
+SED = @SED@
+SET_MAKE = @SET_MAKE@
+SHELL = @SHELL@
+STRICT_WARNING_CFLAGS = @STRICT_WARNING_CFLAGS@
+STRIP = @STRIP@
+TOOLSDIR = @TOOLSDIR@
+USER_JAVAH = @USER_JAVAH@
+VERSION = @VERSION@
+WANT_NATIVE_BIG_INTEGER = @WANT_NATIVE_BIG_INTEGER@
+WARNING_CFLAGS = @WARNING_CFLAGS@
+XMKMF = @XMKMF@
+XML_CFLAGS = @XML_CFLAGS@
+XML_LIBS = @XML_LIBS@
+XSLT_CFLAGS = @XSLT_CFLAGS@
+XSLT_LIBS = @XSLT_LIBS@
+XTEST_LIBS = @XTEST_LIBS@
+X_CFLAGS = @X_CFLAGS@
+X_EXTRA_LIBS = @X_EXTRA_LIBS@
+X_LIBS = @X_LIBS@
+X_PRE_LIBS = @X_PRE_LIBS@
+ZIP = @ZIP@
+abs_builddir = @abs_builddir@
+abs_srcdir = @abs_srcdir@
+abs_top_builddir = @abs_top_builddir@
+abs_top_srcdir = @abs_top_srcdir@
+ac_ct_ANTLR = @ac_ct_ANTLR@
+ac_ct_CC = @ac_ct_CC@
+ac_ct_CXX = @ac_ct_CXX@
+ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
+am__include = @am__include@
+am__leading_dot = @am__leading_dot@
+am__quote = @am__quote@
+am__tar = @am__tar@
+am__untar = @am__untar@
+bindir = @bindir@
+build = @build@
+build_alias = @build_alias@
+build_cpu = @build_cpu@
+build_os = @build_os@
+build_vendor = @build_vendor@
+builddir = @builddir@
+datadir = @datadir@
+datarootdir = @datarootdir@
+default_toolkit = @default_toolkit@
+docdir = @docdir@
+dvidir = @dvidir@
+exec_prefix = @exec_prefix@
+glibjdir = @glibjdir@
+host = @host@
+host_alias = @host_alias@
+host_cpu = @host_cpu@
+host_os = @host_os@
+host_vendor = @host_vendor@
+htmldir = @htmldir@
+includedir = @includedir@
+infodir = @infodir@
+install_sh = @install_sh@
+libdir = @libdir@
+libexecdir = @libexecdir@
+localedir = @localedir@
+localstatedir = @localstatedir@
+mandir = @mandir@
+mkdir_p = @mkdir_p@
+multi_basedir = @multi_basedir@
+nativeexeclibdir = @nativeexeclibdir@
+oldincludedir = @oldincludedir@
+pdfdir = @pdfdir@
+prefix = @prefix@
+program_transform_name = @program_transform_name@
+psdir = @psdir@
+sbindir = @sbindir@
+sharedstatedir = @sharedstatedir@
+srcdir = @srcdir@
+sysconfdir = @sysconfdir@
+target = @target@
+target_alias = @target_alias@
+target_cpu = @target_cpu@
+target_os = @target_os@
+target_vendor = @target_vendor@
+toolexeclibdir = @toolexeclibdir@
+top_build_prefix = @top_build_prefix@
+top_builddir = @top_builddir@
+top_srcdir = @top_srcdir@
+uudecode = @uudecode@
+vm_classes = @vm_classes@
+GLIBJ_CLASSPATH = '$(top_builddir)/lib/glibj.zip:$(top_builddir)/lib'
+@GCJ_JAVAC_FALSE@JCOMPILER = $(JAVAC) $(JAVACFLAGS) -source 1.5 -target 1.5 -encoding UTF-8 -bootclasspath $(GLIBJ_CLASSPATH) -classpath '$(top_builddir)/tools/tools.zip'
+@GCJ_JAVAC_TRUE@JCOMPILER = $(JAVAC) $(JAVACFLAGS) -fsource=1.5 -ftarget=1.5 --encoding=UTF-8 --bootclasspath=$(GLIBJ_CLASSPATH) --classpath='$(top_builddir)/tools/tools.zip'
+
+# All our example java source files
+EXAMPLE_JAVA_FILES = $(srcdir)/gnu/classpath/examples/*/*.java $(srcdir)/gnu/classpath/examples/*/*/*.java $(srcdir)/gnu/classpath/examples/*/*/*/*.java
+
+# The example C source & header files
+EXAMPLE_C_FILES = $(srcdir)/gnu/classpath/examples/*/*.c
+EXAMPLE_CH_FILES = $(srcdir)/gnu/classpath/examples/*/*.h
+
+# The zip files with classes we want to produce.
+EXAMPLE_ZIP = examples.zip
+
+# Extra objects that will not exist until configure-time
+BUILT_SOURCES = $(EXAMPLE_ZIP)
+
+# the png icons we use in some of the examples.
+EXAMPLE_ICONS = $(srcdir)/gnu/classpath/examples/icons/*.png \
+ $(srcdir)/gnu/classpath/examples/icons/*.gif
+
+# the html pages we use in the swing demo example.
+EXAMPLE_HTML = $(srcdir)/gnu/classpath/examples/swing/*.html
+
+# The example specific README files.
+READMES = $(srcdir)/gnu/classpath/examples/CORBA/swing/README.html
+
+# All the files we find "interesting"
+ALL_EXAMPLE_FILES = $(EXAMPLE_JAVA_FILES) $(EXAMPLE_C_FILES) $(EXAMPLE_CH_FILES) $(EXAMPLE_ICONS) $(EXAMPLE_HTML) $(READMES)
+
+# Some architecture independent data to be installed.
+example_DATA = $(EXAMPLE_ZIP) README
+
+# Where we want these data files installed.
+exampledir = $(pkgdatadir)/examples
+
+# Make sure everything is included in the distribution.
+EXTRA_DIST = README Makefile.jawt.in Makefile.java2d.in
+@WITH_JAR_FALSE@CREATE_EXAMPLE_ZIP = $(ZIP) -r ../$(EXAMPLE_ZIP) .
+
+# To generate the example zip just depend on the sources and ignore the
+# class files. Always regenerate all .class files and remove them immediatly.
+# And copy the png icons we use to the classes dir so they get also included.
+@WITH_JAR_TRUE@CREATE_EXAMPLE_ZIP = $(JAR) cf ../$(EXAMPLE_ZIP) .
+all: $(BUILT_SOURCES)
+ $(MAKE) $(AM_MAKEFLAGS) all-am
+
+.SUFFIXES:
+$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps)
+ @for dep in $?; do \
+ case '$(am__configure_deps)' in \
+ *$$dep*) \
+ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+ && { if test -f $@; then exit 0; else break; fi; }; \
+ exit 1;; \
+ esac; \
+ done; \
+ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu examples/Makefile'; \
+ $(am__cd) $(top_srcdir) && \
+ $(AUTOMAKE) --gnu examples/Makefile
+.PRECIOUS: Makefile
+Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
+ @case '$?' in \
+ *config.status*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
+ *) \
+ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
+ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
+ esac;
+
+$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
+Makefile.jawt: $(top_builddir)/config.status $(srcdir)/Makefile.jawt.in
+ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@
+Makefile.java2d: $(top_builddir)/config.status $(srcdir)/Makefile.java2d.in
+ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@
+
+mostlyclean-libtool:
+ -rm -f *.lo
+
+clean-libtool:
+ -rm -rf .libs _libs
+install-exampleDATA: $(example_DATA)
+ @$(NORMAL_INSTALL)
+ test -z "$(exampledir)" || $(MKDIR_P) "$(DESTDIR)$(exampledir)"
+ @list='$(example_DATA)'; test -n "$(exampledir)" || list=; \
+ for p in $$list; do \
+ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
+ echo "$$d$$p"; \
+ done | $(am__base_list) | \
+ while read files; do \
+ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(exampledir)'"; \
+ $(INSTALL_DATA) $$files "$(DESTDIR)$(exampledir)" || exit $$?; \
+ done
+
+uninstall-exampleDATA:
+ @$(NORMAL_UNINSTALL)
+ @list='$(example_DATA)'; test -n "$(exampledir)" || list=; \
+ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+ test -n "$$files" || exit 0; \
+ echo " ( cd '$(DESTDIR)$(exampledir)' && rm -f" $$files ")"; \
+ cd "$(DESTDIR)$(exampledir)" && rm -f $$files
+tags: TAGS
+TAGS:
+
+ctags: CTAGS
+CTAGS:
+
+check-am: all-am
+check: $(BUILT_SOURCES)
+ $(MAKE) $(AM_MAKEFLAGS) check-am
+all-am: Makefile $(DATA)
+installdirs:
+ for dir in "$(DESTDIR)$(exampledir)"; do \
+ test -z "$$dir" || $(MKDIR_P) "$$dir"; \
+ done
+install: $(BUILT_SOURCES)
+ $(MAKE) $(AM_MAKEFLAGS) install-am
+install-exec: install-exec-am
+install-data: install-data-am
+uninstall: uninstall-am
+
+install-am: all-am
+ @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
+
+installcheck: installcheck-am
+install-strip:
+ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
+ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
+ `test -z '$(STRIP)' || \
+ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
+mostlyclean-generic:
+
+clean-generic:
+
+distclean-generic:
+ -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+ -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
+
+maintainer-clean-generic:
+ @echo "This command is intended for maintainers to use"
+ @echo "it deletes files that may require special tools to rebuild."
+ -test -z "$(BUILT_SOURCES)" || rm -f $(BUILT_SOURCES)
+clean: clean-am
+
+clean-am: clean-generic clean-libtool clean-local mostlyclean-am
+
+distclean: distclean-am
+ -rm -f Makefile
+distclean-am: clean-am distclean-generic
+
+dvi: dvi-am
+
+dvi-am:
+
+html: html-am
+
+html-am:
+
+info: info-am
+
+info-am:
+
+install-data-am: install-data-local install-exampleDATA
+
+install-dvi: install-dvi-am
+
+install-dvi-am:
+
+install-exec-am:
+
+install-html: install-html-am
+
+install-html-am:
+
+install-info: install-info-am
+
+install-info-am:
+
+install-man:
+
+install-pdf: install-pdf-am
+
+install-pdf-am:
+
+install-ps: install-ps-am
+
+install-ps-am:
+
+installcheck-am:
+
+maintainer-clean: maintainer-clean-am
+ -rm -f Makefile
+maintainer-clean-am: distclean-am maintainer-clean-generic
+
+mostlyclean: mostlyclean-am
+
+mostlyclean-am: mostlyclean-generic mostlyclean-libtool
+
+pdf: pdf-am
+
+pdf-am:
+
+ps: ps-am
+
+ps-am:
+
+uninstall-am: uninstall-exampleDATA uninstall-local
+
+.MAKE: all check install install-am install-strip
+
+.PHONY: all all-am check check-am clean clean-generic clean-libtool \
+ clean-local distclean distclean-generic distclean-libtool dvi \
+ dvi-am html html-am info info-am install install-am \
+ install-data install-data-am install-data-local install-dvi \
+ install-dvi-am install-exampleDATA install-exec \
+ install-exec-am install-html install-html-am install-info \
+ install-info-am install-man install-pdf install-pdf-am \
+ install-ps install-ps-am install-strip installcheck \
+ installcheck-am installdirs maintainer-clean \
+ maintainer-clean-generic mostlyclean mostlyclean-generic \
+ mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am \
+ uninstall-exampleDATA uninstall-local
+
+
+# Make sure all sources and icons are also installed so users can use them.
+# (Be careful to strip off the srcdir part of the path when installing.)
+install-data-local:
+ srcdir_cnt=`echo $(srcdir) | wc -c`; \
+ for file in $(ALL_EXAMPLE_FILES); do \
+ f=`echo $$file | cut -c$$srcdir_cnt-`; \
+ fdir=`dirname $$f`; \
+ if test ! -d $(DESTDIR)$(pkgdatadir)/examples/$$fdir; then \
+ echo "$(mkinstalldirs) $(DESTDIR)$(pkgdatadir)/examples/$$fdir"; \
+ $(mkinstalldirs) $(DESTDIR)$(pkgdatadir)/examples/$$fdir; \
+ fi; \
+ echo "$(INSTALL_DATA) $$file $(DESTDIR)$(pkgdatadir)/examples/$$f"; \
+ $(INSTALL_DATA) $$file $(DESTDIR)$(pkgdatadir)/examples/$$f; \
+ done
+ echo "$(INSTALL_DATA) Makefile.jawt $(DESTDIR)$(pkgdatadir)/examples/"
+ echo "$(INSTALL_DATA) Makefile.java2d $(DESTDIR)$(pkgdatadir)/examples/"
+ $(INSTALL_DATA) Makefile.jawt $(DESTDIR)$(pkgdatadir)/examples/
+ $(INSTALL_DATA) Makefile.java2d $(DESTDIR)$(pkgdatadir)/examples/
+
+uninstall-local:
+ srcdir_cnt=`echo $(srcdir) | wc -c`; \
+ for file in $(ALL_EXAMPLE_FILES); do \
+ f=`echo $$file | cut -c$$srcdir_cnt-`; \
+ echo "rm -f $(DESTDIR)$(pkgdatadir)/examples/$$f"; \
+ rm -f $(DESTDIR)$(pkgdatadir)/examples/$$f; \
+ done
+ echo "rm -f $(DESTDIR)$(pkgdatadir)/examples/Makefile.jawt"
+ echo "rm -f $(DESTDIR)$(pkgdatadir)/examples/Makefile.java2d"
+ rm -f $(DESTDIR)$(pkgdatadir)/examples/Makefile.jawt
+ rm -f $(DESTDIR)$(pkgdatadir)/examples/Makefile.java2d
+dist-hook:
+ srcdir_cnt=`echo $(srcdir) | wc -c`; \
+ for file in $(ALL_EXAMPLE_FILES); do \
+ f=`echo $$file | cut -c$$srcdir_cnt-`; \
+ fdir=`dirname $$f`; \
+ if test ! -d $(distdir)/$$fdir; then \
+ echo "$(makeinstalldirs) $(distdir)/$$fdir"; \
+ $(mkinstalldirs) $(distdir)/$$fdir; \
+ fi; \
+ echo "cp -p $$file $(distdir)/$$f"; \
+ cp -p $$file $(distdir)/$$f; \
+ done
+
+$(EXAMPLE_ZIP): $(EXAMPLE_JAVA_FILES)
+ @mkdir_p@ classes/gnu/classpath/examples/icons
+ cp $(EXAMPLE_ICONS) classes/gnu/classpath/examples/icons
+ @mkdir_p@ classes/gnu/classpath/examples/swing
+ cp $(EXAMPLE_HTML) classes/gnu/classpath/examples/swing
+ $(JCOMPILER) -d classes $(EXAMPLE_JAVA_FILES)
+ (cd classes; \
+ $(CREATE_EXAMPLE_ZIP); \
+ cd ..)
+ rm -rf classes
+
+# Zip file be gone! (and make sure the classes are gone too)
+clean-local:
+ rm -rf $(EXAMPLE_ZIP) classes
+
+# Tell versions [3.59,3.63) of GNU make to not export all variables.
+# Otherwise a system limit (for SysV at least) may be exceeded.
+.NOEXPORT:
diff --git a/libjava/classpath/examples/Makefile.java2d.in b/libjava/classpath/examples/Makefile.java2d.in
new file mode 100644
index 000000000..dac22068c
--- /dev/null
+++ b/libjava/classpath/examples/Makefile.java2d.in
@@ -0,0 +1,17 @@
+# @configure_input@
+
+srcdir = @srcdir@
+prefix = @prefix@
+exec_prefix = @exec_prefix@
+includedir = @includedir@
+libdir = @libdir@
+pkglibdir = $(libdir)/@PACKAGE@
+GTK_CFLAGS = @GTK_CFLAGS@
+GTK_LIBS = @GTK_LIBS@
+
+all: $(srcdir)/gnu/classpath/examples/java2d/bench.c $(srcdir)/gnu/classpath/examples/java2d/bench.h
+ gcc -g -O0 -Wall -I$(srcdir)/gnu/classpath/examples/java2d $(GTK_CFLAGS) -L$(GTK_LIBS) \
+ -o cairobench $(srcdir)/gnu/classpath/examples/java2d/bench.c
+
+clean:
+ rm -f gnu/classpath/examples/java2d/bench
diff --git a/libjava/classpath/examples/Makefile.jawt.in b/libjava/classpath/examples/Makefile.jawt.in
new file mode 100644
index 000000000..aea41d4cb
--- /dev/null
+++ b/libjava/classpath/examples/Makefile.jawt.in
@@ -0,0 +1,29 @@
+# @configure_input@
+
+prefix = @prefix@
+exec_prefix = @exec_prefix@
+includedir = @includedir@
+libdir = @libdir@
+pkglibdir = $(libdir)/@PACKAGE@
+
+all: gnu/classpath/examples/jawt/DemoJAWT.class libDemoJAWT.so
+ @echo "RUN with:"
+ @echo " LD_LIBRARY_PATH=$$LD_LIBRARY_PATH:.:$(pkglibdir) jamvm \\"
+ @echo " gnu.classpath.examples.jawt.DemoJAWT"
+
+gnu/classpath/examples/jawt/DemoJAWT.class: gnu/classpath/examples/jawt/DemoJAWT.java
+ gcj -C gnu/classpath/examples/jawt/DemoJAWT.java
+
+DemoJAWT.h: gnu/classpath/examples/jawt/DemoJAWT.class
+ gcjh -jni gnu.classpath.examples.jawt.DemoJAWT -o DemoJAWT.h
+
+libDemoJAWT.so: gnu/classpath/examples/jawt/DemoJAWT.c DemoJAWT.h
+ gcc -g -O0 -Wall -I. -I/usr/X11R6/include -L. -L/usr/X11R6/lib \
+ -I$(includedir) -L$(pkglibdir) \
+ -lX11 -ljawtgnu -shared -o libDemoJAWT.so \
+ gnu/classpath/examples/jawt/DemoJAWT.c
+
+clean:
+ rm -f DemoJAWT.h
+ rm -f gnu/classpath/examples/jawt/DemoJAWT*.class
+ rm -f libDemoJAWT.so
diff --git a/libjava/classpath/examples/README b/libjava/classpath/examples/README
new file mode 100644
index 000000000..f7bf59962
--- /dev/null
+++ b/libjava/classpath/examples/README
@@ -0,0 +1,89 @@
+This directory contains example programs that show how the GNU Classpath
+library can be used.
+
+Each example has its own package under gnu.classpath.examples and has a
+class Demo which contains a main() method to run that particular example.
+
+The examples can be compiled and run with gcj as follows:
+
+ gcj -o swingdemo --main=gnu.classpath.examples.swing.Demo \
+ gnu/classpath/examples/swing/Demo.java \
+ gnu/classpath/examples/swing/GNULookAndFeel.java
+ ./swingdemo
+
+Or with a traditional byte code interpreter like:
+
+ gcj -C gnu/classpath/examples/awt/Demo.java
+ gij gnu.classpath.examples.awt.Demo
+
+The installation also comes with an examples.zip archive that contains
+all needed resources and compiled byte code class files that can be
+run as follows:
+
+ kaffe -classpath examples.zip gnu.classpath.examples.awt.Demo
+ kaffe -classpath examples.zip gnu.classpath.examples.swing.Demo
+
+The jawt Demo needs some extra support library that currently needs to be
+build by hand. The following assumes GNU Classpath was installed in
+/usr/local/classpath, if you installed it somewhere else then adjust the
+-I and -L paths accordingly. The included Makefile.jawt is setup this way.
+
+You can invoke it with:
+
+ make -f Makefile.jawt
+
+Or you can compile by hand as follows:
+
+ gcj -C gnu/classpath/examples/jawt/DemoJAWT.java
+ gcjh -jni gnu.classpath.examples.jawt.DemoJAWT -o DemoJAWT.h
+ gcc -g -O0 -Wall -I. -I/usr/X11R6/include -L. -L/usr/X11R6/lib \
+ -I/usr/local/classpath/include -L/usr/local/classpath/lib/classpath \
+ -lX11 -ljawtgnu -shared -o libDemoJAWT.so \
+ gnu/classpath/examples/jawt/DemoJAWT.c
+
+You can then run the example as follows:
+
+ export LD_LIBRARY_PATH=.:/usr/local/classpath/lib/classpath
+ jamvm gnu.classpath.examples.jawt.DemoJAWT
+
+The java2d benchmarking demos include a GTK widget to measure the native
+speed of some basic java2d options, without the JNI overhead.
+
+You can invoke it with:
+
+ make -f Makefile.java2d
+
+Or you can compile by hand as follows:
+
+ gcc -g -O0 -Wall -I./gnu/classpath/examples/java2d \
+ -o cairobench gnu/classpath/examples/java2d/bench.c \
+ `pkg-config --libs --cflags gtk+-2.0`
+
+You can then run the example as follows:
+
+ ./cairobench
+
+All example code is distributed under the GNU General Public License (GPL).
+
+The example icons used in some of the examples come from gnome-icon-theme
+version 1.2.3 and are also distributed under the GPL.
+All these images are stored in the directory gnu/classpath/examples/icons/.
+
+More free icons can be found in the gnome-icon-theme package:
+http://ftp.gnome.org/pub/GNOME/sources/gnome-icon-theme/
+
+
+GNU Classpath examples are 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 examples are distributed in the hope that they 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 examples; see the file COPYING. If not,
+write to the Free Software Foundation, 51 Franklin Street, Fifth Floor,
+Boston, MA 02110-1301, USA.
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:
+ // <ROOT CONTEXT>
+ // |
+ // +--- <c.d context>
+ // | |
+ // | +--- 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 @@
+<html>
+ <head>
+ <title>Five-in-a-row v 0.0</title>
+ </head>
+ <body LANG="en-US">
+ <h1>
+ <i>Five-in-a-row
+ </i> 0.0 supplementary documentation
+ </h1>
+ <h3>Introduction and rules
+ </h3>
+ <p>
+ <i>Five-in-a-row
+ </i> 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.
+ </p>
+ <p>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.
+ </p>
+ <p>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.
+ </p>
+ <p>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.
+ </p>
+ <p>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.
+ </p>
+ <p>
+ 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.
+ </p>
+ <h3>Configuration and run
+ </h3>
+ <p>The game manager server executable class is
+ <i>gnu.classpath.examples.CORBA.swing.x5.X5Server
+ </i>. After start,
+ it will print to console the Internet address that must be entered to
+ the client to reach the manager.
+ </p>
+ <p>The client executable class it
+ <i>gnu.classpath.examples.CORBA.swing.x5.Demo
+ </i>.
+ </p>
+ <p>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.
+ </p>
+ <p>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.
+ </p>
+ <h3>The game server
+ </h3>
+ <p>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
+ <i>Five-in-a-row&nbsp;
+ </i>client uses
+ this reference to find and access the remote game server object.
+ </p>
+ <p>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 &ldquo;meeting point&rdquo; where the players can
+ find each other. The game server is a console-only application.
+ </p>
+ <p>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.
+ </p>
+ <h3>The game client
+ </h3>
+ <p>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
+ <i>State
+ </i> interface. They are displayed in the bottom left
+ corner of the window and are summarized in the following table:
+ </p>
+ <table BORDER=1 CELLPADDING=4 CELLSPACING=0 WIDTH="100%">
+ <thead>
+ <tr BGCOLOR="#ccccff">
+ <th BGCOLOR="#e6e6ff">
+ Our state
+ </th>
+ <th BGCOLOR="#e6e6ff">
+ Partner state
+ </th>
+ <th BGCOLOR="#e6e6ff">
+ Possible actions
+ </th>
+ <th BGCOLOR="#e6e6ff">
+ Comment
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>
+ Disconnected
+ </td>
+ <td>
+ Partner not accessible
+ </td>
+ <td>
+ Connect
+ </td>
+ <td>
+ Initial state.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ Queued
+ </td>
+ <td>
+ Partner not accessible
+ </td>
+ <td>
+ Leave
+ </td>
+ <td>
+ Queued by the game manager.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ I think.
+ </td>
+ <td>
+ I wait for your move
+ </td>
+ <td>
+ Make move, reset game, leave, chat.
+ </td>
+ <td>
+ The person who waited for another player to come starts
+ the game first.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ I wait for your move
+ </td>
+ <td>
+ I think
+ </td>
+ <td>
+ Chat, reset game, leave.
+ </td>
+ <td>
+ After the partner makes the move, the state changes to
+ <i>I think
+ </i>, unless the end of game situation is detected by
+ the desk analyzer.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ I have lost
+ </td>
+ <td>
+ I have won
+ </td>
+ <td>
+ Chat, reset game, leave.
+ </td>
+ <td>
+ Can be entered with the help of the desk analyzer only.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ I have won
+ </td>
+ <td>
+ I have lost
+ </td>
+ <td>
+ Chat, reset game, leave
+ </td>
+ <td>
+ Can be entered with the help of the desk analyzer only.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ Error
+ </td>
+ <td>
+ Any
+ </td>
+ <td>
+ Chat, leave
+ </td>
+ <td>
+ This should never happen under normal work, but the demo
+ program may be modified by the user.
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ <br>
+ <br>
+ 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.
+ <h3>The used RMI-IIOP architecture
+ </h3>
+ Both player and game manager servants are derived from the
+ <i>org.omg.PortableServer.Servant
+ </i> and, being servants, are simply
+ connected to the
+ <i>POA
+ </i>with
+ <i>POA.servant_to_reference
+ </i>. The
+ first remote object (game manager) is found using the stringified
+ object reference. No naming service is involved.
+</p>
+Where required, the CORBA objects are narrowed into required
+player and game manager interfaces using method
+<i>PortableRemoteObject.narrow(org.omg.CORBA.Object object, Class
+ interface_class)
+</i>, 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
+<i>Player.start_game.
+</i>
+<h3>Class and interface summary
+</h3>
+<table BORDER=1 CELLPADDING=3 CELLSPACING=0 WIDTH="100%">
+ <col>
+ <col>
+ <tr>
+ <th COLSPAN=2 BGCOLOR="#e6e6ff">
+ Executables classes
+ </th>
+ </tr>
+ <tr>
+ <td>
+ Demo
+ </td>
+ <td>
+ The main executable class of the game client.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ X5Server
+ </td>
+ <td>
+ The main executable class of the game manager server.
+ </td>
+ </tr>
+</table>
+<p></p>
+<table BORDER=1 CELLPADDING=3 CELLSPACING=0 WIDTH="100%">
+ <tr BGCOLOR="#ccccff">
+ <th COLSPAN=2 BGCOLOR="#e6e6ff">
+ Interface Summary
+ </th>
+ </tr>
+ <tr>
+ <td>
+ GameManager
+ </td>
+ <td>
+ The game manager interface.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ Player
+ </td>
+ <td>
+ Defines remote methods that are invoked by another player or by
+ the challenge server.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ State
+ </td>
+ <td>
+ Defines the states in that the player can be.
+ </td>
+ </tr>
+</table>
+&nbsp;
+<table BORDER=1 CELLPADDING=3 CELLSPACING=0 WIDTH="100%">
+ <col>
+ <col>
+ <tr BGCOLOR="#ccccff">
+ <th COLSPAN=2 BGCOLOR="#e6e6ff">
+ Class Summary
+ </th>
+ </tr>
+ <tr>
+ <td>
+ _GameManager_Stub
+ </td>
+ <td>
+ Normally generated with rmic compiler, this class represents
+ the GameManager Stub on the client side.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ _GameManagerImpl_Tie
+ </td>
+ <td>
+ Normally generated with rmic compiler, this class represents
+ the GameManager Tie on the client side.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ _Player_Stub
+ </td>
+ <td>
+ 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).
+ </td>
+ </tr>
+ <tr>
+ <td>
+ _PlayerImpl_Tie
+ </td>
+ <td>
+ 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).
+ </td>
+ </tr>
+ <tr>
+ <td>
+ ChatConstants
+ </td>
+ <td>
+ The chat color code constants, used to indicate who is talking.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ ClientFrame
+ </td>
+ <td>
+ The JFrame of the GUI client.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ GameManagerImpl
+ </td>
+ <td>
+ The manager connects two players into the game.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ IorReader
+ </td>
+ <td>
+ Reads the remote URL.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ OrbStarter
+ </td>
+ <td>
+ Starts the ORBs, involved into this application.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ PlayerImpl
+ </td>
+ <td>
+ The implementation of the PlayerCommunicator, providing the
+ local functionality.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ PlayingDesk
+ </td>
+ <td>
+ Manages actions, related to the game rules and also does all
+ painting.
+ </td>
+ </tr>
+</table>
+<h3>See also
+</h3>
+<p>
+ <a HREF="http://www.javascripter.net/games/xo/xo.htm">http://www.javascripter.net/games/xo/xo.htm
+ </a>
+</p>
+<p>
+ <a HREF="http://www.leepoint.net/notes-java/45examples/55games/five/five.html">http://www.leepoint.net/notes-java/45examples/55games/five/five.html
+ </a>
+</p>
+<p>Copyright
+</p>
+<p>
+ <font COLOR="#b3b3b3">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.
+ </font>
+</p>
+<p>
+ <br>
+ <br>
+</p>
+<p>
+First version written by <a href="http://savannah.gnu.org/users/audriusa">
+Audrius Me&scaron;kauskas</a>
+</p>
+</body>
+</html>
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}:
+ * <pre>
+ * rmic -iiop -poa -keep gnu.classpath.examples.CORBA.swing.x5.GameManagerImpl
+ * </pre>
+ * (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}:
+ * <pre>
+ * rmic -iiop -poa -keep gnu.classpath.examples.CORBA.swing.x5.GameManagerImpl
+ * </pre>
+ * (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 [<options>] [<test> ...]");
+ System.out.println("");
+ System.out.println("Options: -i|--iterations=<n|-1> - number of iterations (-1 is infinite)");
+ System.out.println(" -w|--width=<n> - screen width; default "+DEFAULT_SCREEN_WIDTH);
+ System.out.println(" -h|--height=<n> - 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<modes.length;i++ )
+ list.add(modes[i].getWidth() + "x"
+ + modes[i].getHeight()
+ + ((modes[i].getBitDepth() != DisplayMode.BIT_DEPTH_MULTI)
+ ? "x" + modes[i].getBitDepth() + "bpp"
+ : "")
+ + ((modes[i].getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN)
+ ? "@" + modes[i].getRefreshRate() + "Hz"
+ : ""));
+
+ ActionListener al = new ActionListener()
+ {
+ public void actionPerformed(ActionEvent ae)
+ {
+ int i = list.getSelectedIndex();
+ gd.setDisplayMode(gd.getDisplayModes()[i]);
+ }
+ };
+
+ Button b = new Button("Switch");
+ Button c = new Button("Close");
+
+ list.addActionListener(al);
+ b.addActionListener(al);
+
+ c.addActionListener(new ActionListener () {
+ public void actionPerformed (ActionEvent e) {
+ dispose();
+ }
+ });
+
+ setLayout(new GridLayout(3, 1, 5, 5));
+ add(list);
+ add(b);
+ add(c);
+
+ pack();
+ }
+ }
+
+ static class DragDropWindow
+ extends SubFrame
+ implements ActionListener, DropTargetListener
+ {
+ DragLabel source = new DragLabel("Drag and drop me to the following Button",
+ Label.CENTER);
+
+ Button target = new Button();
+
+ public void init()
+ {
+ source.setForeground(Color.red);
+ add(source, BorderLayout.NORTH);
+
+ target.addActionListener(this);
+ add(target, BorderLayout.SOUTH);
+
+ new DropTarget(target, DnDConstants.ACTION_COPY_OR_MOVE, this);
+
+ setSize(205, 100);
+
+ pack();
+ }
+
+ public void actionPerformed(ActionEvent e)
+ {
+ Button b = (Button) e.getSource();
+ b.setLabel("");
+ }
+
+ public void dragEnter(DropTargetDragEvent e)
+ {
+ }
+
+ public void dragExit(DropTargetEvent e)
+ {
+ }
+
+ public void dragOver(DropTargetDragEvent e)
+ {
+ }
+
+ public void drop(DropTargetDropEvent e)
+ {
+ try
+ {
+ Transferable t = e.getTransferable();
+
+ if (e.isDataFlavorSupported(DataFlavor.stringFlavor))
+ {
+ e.acceptDrop(e.getDropAction());
+
+ String s;
+ s = (String) t.getTransferData(DataFlavor.stringFlavor);
+
+ target.setLabel(s);
+
+ e.dropComplete(true);
+ }
+ else
+ e.rejectDrop();
+ }
+ catch (java.io.IOException e2)
+ {
+ }
+ catch (UnsupportedFlavorException e2)
+ {
+ }
+ }
+
+ public void dropActionChanged(DropTargetDragEvent e)
+ {
+ }
+
+ class DragLabel
+ extends Label
+ implements DragGestureListener, DragSourceListener
+ {
+ private DragSource ds = DragSource.getDefaultDragSource();
+
+ public DragLabel(String s, int alignment)
+ {
+ super(s, alignment);
+ int action = DnDConstants.ACTION_COPY_OR_MOVE;
+ ds.createDefaultDragGestureRecognizer(this, action, this);
+ }
+
+ public void dragGestureRecognized(DragGestureEvent e)
+ {
+ try
+ {
+ Transferable t = new StringSelection(getText());
+ e.startDrag(DragSource.DefaultCopyNoDrop, t, this);
+ }
+ catch (InvalidDnDOperationException e2)
+ {
+ System.out.println(e2);
+ }
+ }
+
+ public void dragDropEnd(DragSourceDropEvent e)
+ {
+ if (e.getDropSuccess() == false)
+ return;
+
+ int action = e.getDropAction();
+ if ((action & DnDConstants.ACTION_MOVE) != 0)
+ setText("");
+ }
+
+ public void dragEnter(DragSourceDragEvent e)
+ {
+ DragSourceContext ctx = e.getDragSourceContext();
+
+ int action = e.getDropAction();
+ if ((action & DnDConstants.ACTION_COPY) != 0)
+ ctx.setCursor(DragSource.DefaultCopyDrop);
+ else
+ ctx.setCursor(DragSource.DefaultCopyNoDrop);
+ }
+
+ public void dragExit(DragSourceEvent e)
+ {
+ }
+
+ public void dragOver(DragSourceDragEvent e)
+ {
+ }
+
+ public void dropActionChanged(DragSourceDragEvent e)
+ {
+ }
+ }
+ }
+
+ static class FullscreenWindow extends SubFrame
+ {
+ GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
+
+ public void init ()
+ {
+ initted = true;
+
+ setTitle("Fullscreen Exclusive Mode");
+
+ ActionListener al = new ActionListener()
+ {
+ public void actionPerformed(ActionEvent ae)
+ {
+ if (gd.getFullScreenWindow() == FullscreenWindow.this)
+ gd.setFullScreenWindow(null);
+ else
+ gd.setFullScreenWindow(FullscreenWindow.this);
+ }
+ };
+
+ Button b = new Button("Toggle Fullscreen");
+ Button c = new Button("Close");
+
+ b.addActionListener(al);
+
+ c.addActionListener(new ActionListener () {
+ public void actionPerformed (ActionEvent e) {
+ gd.setFullScreenWindow(null);
+ dispose();
+ }
+ });
+
+ setLayout(new GridLayout(3, 1, 5, 5));
+ add(b);
+ add(c);
+
+ pack();
+ }
+ }
+
+ static class RoundRectWindow extends SubFrame
+ {
+ public void init ()
+ {
+ initted = true;
+ setTitle("RoundRect");
+ setLayout(new BorderLayout());
+ add(new DrawRoundRect(), "West");
+ Button cb = new Button ("Close");
+ cb.addActionListener(new ActionListener () {
+ public void actionPerformed (ActionEvent e) {
+ dispose();
+ }
+ });
+ add(cb, "Center");
+ add(new FillRoundRect(), "East");
+ pack();
+ }
+
+ static class DrawRoundRect extends Panel
+ {
+
+ public Dimension getPreferredSize()
+ {
+ return new Dimension(500, 500);
+ }
+
+ public void paint( Graphics g )
+ {
+ // left side
+
+ // rectangles should be identical
+ g.setColor(Color.red);
+ g.drawRect(50, 50, 300, 100);
+ g.setColor(Color.black);
+ g.drawRoundRect(50, 50, 300, 100, 0, 0);
+
+ // small round corners
+ g.setColor(Color.red);
+ g.drawRect(50, 200, 300, 100);
+ g.setColor(Color.black);
+ g.drawRoundRect(50, 200, 300, 100, 25, 25);
+
+ // round ends
+ g.setColor(Color.red);
+ g.drawRect(50, 350, 300, 100);
+ g.setColor(Color.black);
+ g.drawRoundRect(50, 350, 300, 100, 25, 100);
+
+ // right side
+
+ // circle only
+ g.setColor(Color.blue);
+ g.drawOval(375, 50, 100, 100);
+
+ // round rectangle should exactly cover circle
+ g.setColor(Color.blue);
+ g.drawOval(375, 200, 100, 100);
+ g.setColor(Color.black);
+ g.drawRoundRect(375, 200, 100, 100, 100, 100);
+
+ // round rectangle should look like a circle
+ g.setColor(Color.red);
+ g.drawRect(375, 350, 100, 100);
+ g.setColor(Color.black);
+ g.drawRoundRect(375, 350, 100, 100, 100, 100);
+ }
+ }
+
+ static class FillRoundRect extends Panel
+ {
+
+ public Dimension getPreferredSize()
+ {
+ return new Dimension(500, 500);
+ }
+
+ public void paint( Graphics g )
+ {
+ // left side
+
+ // rectangles should be identical
+ g.setColor(Color.red);
+ g.fillRect(50, 50, 300, 100);
+ g.setColor(Color.black);
+ g.fillRoundRect(50, 50, 300, 100, 0, 0);
+
+ // small round corners
+ g.setColor(Color.red);
+ g.fillRect(50, 200, 300, 100);
+ g.setColor(Color.black);
+ g.fillRoundRect(50, 200, 300, 100, 25, 25);
+
+ // round ends
+ g.setColor(Color.red);
+ g.fillRect(50, 350, 300, 100);
+ g.setColor(Color.black);
+ g.fillRoundRect(50, 350, 300, 100, 25, 100);
+
+ // right side
+
+ // circle only
+ g.setColor(Color.blue);
+ g.fillOval(375, 50, 100, 100);
+
+ // round rectangle should exactly cover circle
+ g.setColor(Color.blue);
+ g.fillOval(375, 200, 100, 100);
+ g.setColor(Color.black);
+ g.fillRoundRect(375, 200, 100, 100, 100, 100);
+
+ // round rectangle should look like a circle
+ g.setColor(Color.red);
+ g.fillRect(375, 350, 100, 100);
+ g.setColor(Color.black);
+ g.fillRoundRect(375, 350, 100, 100, 100, 100);
+ }
+ }
+ }
+
+ static class AnimationWindow extends SubFrame
+ {
+ AnimationApplet a;
+ public void init ()
+ {
+ initted = true;
+ setTitle("Animation");
+ Button cb = new Button ("Close");
+ cb.addActionListener(new ActionListener () {
+ public void actionPerformed (ActionEvent e)
+ {
+ if (a != null)
+ {
+ a.destroy();
+ dispose();
+ }
+ }
+ });
+ a = new AnimationApplet();
+ add(a, "Center");
+ add(cb, "South");
+ pack();
+ }
+
+ public void show()
+ {
+ super.show();
+ a.init();
+ a.run();
+ }
+ }
+}
diff --git a/libjava/classpath/examples/gnu/classpath/examples/awt/HintingDemo.java b/libjava/classpath/examples/gnu/classpath/examples/awt/HintingDemo.java
new file mode 100644
index 000000000..5ba44f6d9
--- /dev/null
+++ b/libjava/classpath/examples/gnu/classpath/examples/awt/HintingDemo.java
@@ -0,0 +1,420 @@
+/* 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 gnu.java.awt.font.FontDelegate;
+import gnu.java.awt.font.GNUGlyphVector;
+import gnu.java.awt.font.opentype.OpenTypeFontFactory;
+
+import java.awt.BasicStroke;
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Font;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.GridLayout;
+import java.awt.Insets;
+import java.awt.RenderingHints;
+import java.awt.Shape;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.font.FontRenderContext;
+import java.io.File;
+import java.io.RandomAccessFile;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.text.StringCharacterIterator;
+
+import javax.swing.BoxLayout;
+import javax.swing.JCheckBox;
+import javax.swing.JFileChooser;
+import javax.swing.JFrame;
+import javax.swing.JMenu;
+import javax.swing.JMenuBar;
+import javax.swing.JMenuItem;
+import javax.swing.JPanel;
+import javax.swing.JSpinner;
+import javax.swing.JTextField;
+import javax.swing.border.TitledBorder;
+import javax.swing.event.ChangeEvent;
+import javax.swing.event.ChangeListener;
+
+public class HintingDemo extends JFrame {
+
+ FontDelegate font;
+ GNUGlyphVector glyph;
+ GlyphPreview glyphPreview;
+ HintPanel hintPanel;
+ StringViewer stringViewer;
+ Chooser chooser;
+ char character;
+ Options options;
+ boolean antiAlias;
+ boolean showGrid;
+ boolean showOriginal;
+ boolean showHinted;
+ int flags;
+
+ class StringViewer extends JPanel
+ implements ActionListener
+ {
+ JTextField input;
+ GNUGlyphVector gv;
+ Viewer viewer;
+ StringViewer()
+ {
+ setLayout(new GridLayout(0, 1));
+ setBorder(new TitledBorder("Use this field to render complete strings"));
+ input = new JTextField();
+ input.addActionListener(this);
+ add(input);
+ viewer = new Viewer();
+ add(viewer);
+ }
+
+ public void actionPerformed(ActionEvent event)
+ {
+ refresh();
+ }
+
+ void refresh()
+ {
+ gv = (GNUGlyphVector)
+ font.createGlyphVector(new Font("Dialog", 0, 12),
+ new FontRenderContext(null, false, false),
+ new StringCharacterIterator(input.getText()));
+ viewer.repaint();
+ }
+
+ class Viewer extends JPanel
+ {
+ protected void paintComponent(Graphics g)
+ {
+ if (gv != null && g instanceof Graphics2D)
+ {
+ Graphics2D g2d = (Graphics2D) g;
+ if (antiAlias)
+ {
+ g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+ RenderingHints.VALUE_ANTIALIAS_ON);
+ }
+ else
+ {
+ g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+ RenderingHints.VALUE_ANTIALIAS_OFF);
+ }
+ g2d.clearRect(0, 0, getWidth(), getHeight());
+ g2d.setColor(Color.BLACK);
+ Shape outline = gv.getOutline(0, 0,
+ flags | FontDelegate.FLAG_FITTED);
+ g2d.translate(20, Math.floor(outline.getBounds2D().getHeight()) + 2);
+ g2d.fill(outline);
+ }
+ }
+ }
+ }
+
+ class HintPanel extends JPanel
+ {
+
+ HintPanel()
+ {
+ setBorder(new TitledBorder("Detailed glyph view"));
+ }
+ protected void paintComponent(Graphics g)
+ {
+ if (glyph != null && g instanceof Graphics2D)
+ {
+ Graphics2D g2d = (Graphics2D) g.create();
+ Insets i = getInsets();
+ g2d.clearRect(i.left, i.top, getWidth() - i.left - i.right,
+ getHeight() - i.top - i.bottom);
+ if (showGrid)
+ {
+ g2d.setColor(Color.GRAY);
+ for (int x = 20; x < getWidth(); x += 20)
+ {
+ g2d.drawLine(x, i.top, x, getHeight() - i.top - i.bottom);
+ }
+ for (int y = 20; y < getHeight(); y += 20)
+ {
+ g2d.drawLine(i.left, y, getWidth() - i.left - i.right, y);
+ }
+ }
+// g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+// RenderingHints.VALUE_ANTIALIAS_ON);
+ g2d.translate(40, 300);
+ g2d.scale(20., 20.);
+ g2d.setStroke(new BasicStroke((float) (1/10.)));
+ if (showOriginal)
+ {
+ g2d.setColor(Color.RED);
+ g2d.draw(glyph.getOutline(0, 0,
+ flags & ~FontDelegate.FLAG_FITTED));
+ }
+ if (showHinted)
+ {
+ g2d.setColor(Color.RED);
+ g2d.draw(glyph.getOutline(0, 0,
+ flags | FontDelegate.FLAG_FITTED));
+ }
+ }
+ }
+
+ }
+
+ class GlyphPreview extends JPanel
+ {
+ protected void paintComponent(Graphics g)
+ {
+ if (glyph != null && g instanceof Graphics2D)
+ {
+ Graphics2D g2d = (Graphics2D) g;
+ if (antiAlias)
+ {
+ g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+ RenderingHints.VALUE_ANTIALIAS_ON);
+ }
+ else
+ {
+ g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+ RenderingHints.VALUE_ANTIALIAS_OFF);
+ }
+ g2d.clearRect(0, 0, getWidth(), getHeight());
+ g2d.setColor(Color.BLACK);
+ Shape outline = glyph.getOutline(0, 0,
+ flags | FontDelegate.FLAG_FITTED);
+ g2d.translate(20, outline.getBounds2D().getHeight() + 2);
+ g2d.fill(outline);
+ }
+ }
+
+ }
+
+ HintingDemo()
+ {
+ File file = new File("/usr/share/fonts/truetype/freefont/FreeSans.ttf");
+ loadFont(file);
+ setLayout(new BorderLayout());
+ chooser = new Chooser();
+ add(chooser, BorderLayout.NORTH);
+ hintPanel = new HintPanel();
+ character = 'A';
+ add(hintPanel);
+
+ options = new Options();
+ add(options, BorderLayout.EAST);
+
+ stringViewer = new StringViewer();
+ add(stringViewer, BorderLayout.SOUTH);
+ refresh();
+
+ JMenuBar mb = new JMenuBar();
+ setJMenuBar(mb);
+ JMenu fileMenu = new JMenu("File");
+ mb.add(fileMenu);
+ JMenuItem loadFont = new JMenuItem("Load font");
+ loadFont.addActionListener(new ActionListener(){
+ public void actionPerformed(ActionEvent ev)
+ {
+ JFileChooser fc = new JFileChooser()
+ {
+ public boolean accept(File f)
+ {
+ return f.isDirectory() || f.getName().endsWith(".ttf");
+ }
+ };
+ int status = fc.showOpenDialog(HintingDemo.this);
+ if (status == JFileChooser.APPROVE_OPTION)
+ {
+ File file = fc.getSelectedFile();
+ loadFont(file);
+ }
+ }
+ });
+ fileMenu.add(loadFont);
+ }
+
+ void refresh()
+ {
+ if (chooser != null)
+ chooser.refresh();
+ if (glyphPreview != null)
+ glyphPreview.repaint();
+ if (hintPanel != null)
+ hintPanel.repaint();
+ if (stringViewer != null)
+ stringViewer.refresh();
+ }
+
+ class Options extends JPanel
+ implements ActionListener
+ {
+ JCheckBox antiAliasOpt;
+ JCheckBox showGridOpt;
+ JCheckBox showOriginalOpt;
+ JCheckBox showHintedOpt;
+ JCheckBox hintHorizontalOpt;
+ JCheckBox hintVerticalOpt;
+ JCheckBox hintEdgeOpt;
+ JCheckBox hintStrongOpt;
+ JCheckBox hintWeakOpt;
+ Options()
+ {
+ setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
+ setBorder(new TitledBorder("Hinting options"));
+ antiAliasOpt = new JCheckBox("Antialias");
+ antiAliasOpt.setSelected(true);
+ antiAliasOpt.addActionListener(this);
+ add(antiAliasOpt);
+ showGridOpt = new JCheckBox("Show grid");
+ showGridOpt.setSelected(true);
+ showGridOpt.addActionListener(this);
+ add(showGridOpt);
+ showOriginalOpt = new JCheckBox("Show original");
+ showOriginalOpt.setSelected(true);
+ showOriginalOpt.addActionListener(this);
+ add(showOriginalOpt);
+ showHintedOpt = new JCheckBox("Show hinted");
+ showHintedOpt.setSelected(true);
+ showHintedOpt.addActionListener(this);
+ add(showHintedOpt);
+ hintHorizontalOpt = new JCheckBox("Hint horizontal");
+ hintHorizontalOpt.setSelected(true);
+ hintHorizontalOpt.addActionListener(this);
+ add(hintHorizontalOpt);
+ hintVerticalOpt = new JCheckBox("Hint vertical");
+ hintVerticalOpt.setSelected(true);
+ hintVerticalOpt.addActionListener(this);
+ add(hintVerticalOpt);
+ hintEdgeOpt = new JCheckBox("Hint edge points");
+ hintEdgeOpt.setSelected(true);
+ hintEdgeOpt.addActionListener(this);
+ add(hintEdgeOpt);
+ hintStrongOpt = new JCheckBox("Hint strong points");
+ hintStrongOpt.setSelected(true);
+ hintStrongOpt.addActionListener(this);
+ add(hintStrongOpt);
+ hintWeakOpt = new JCheckBox("Hint weak points");
+ hintWeakOpt.setSelected(true);
+ hintWeakOpt.addActionListener(this);
+ add(hintWeakOpt);
+ sync();
+ }
+
+ void sync()
+ {
+ antiAlias = antiAliasOpt.isSelected();
+ showGrid = showGridOpt.isSelected();
+ showOriginal = showOriginalOpt.isSelected();
+ showHinted = showHintedOpt.isSelected();
+ if (hintHorizontalOpt.isSelected())
+ flags &= ~FontDelegate.FLAG_NO_HINT_HORIZONTAL;
+ else
+ flags |= FontDelegate.FLAG_NO_HINT_HORIZONTAL;
+ if (hintVerticalOpt.isSelected())
+ flags &= ~FontDelegate.FLAG_NO_HINT_VERTICAL;
+ else
+ flags |= FontDelegate.FLAG_NO_HINT_VERTICAL;
+ if (hintEdgeOpt.isSelected())
+ flags &= ~FontDelegate.FLAG_NO_HINT_EDGE_POINTS;
+ else
+ flags |= FontDelegate.FLAG_NO_HINT_EDGE_POINTS;
+ if (hintStrongOpt.isSelected())
+ flags &= ~FontDelegate.FLAG_NO_HINT_STRONG_POINTS;
+ else
+ flags |= FontDelegate.FLAG_NO_HINT_STRONG_POINTS;
+ if (hintWeakOpt.isSelected())
+ flags &= ~FontDelegate.FLAG_NO_HINT_WEAK_POINTS;
+ else
+ flags |= FontDelegate.FLAG_NO_HINT_WEAK_POINTS;
+
+ refresh();
+ }
+
+ public void actionPerformed(ActionEvent event)
+ {
+ sync();
+ }
+ }
+
+ class Chooser extends JPanel
+ {
+ JSpinner spin;
+ Chooser()
+ {
+ setLayout(new GridLayout(1, 0));
+ setBorder(new TitledBorder("Choose and preview the character to render"));
+ spin = new JSpinner();
+ spin.addChangeListener(new ChangeListener()
+ {
+
+ public void stateChanged(ChangeEvent event)
+ {
+ int val = ((Integer) spin.getValue()).intValue();
+ setGlyph((char) val);
+ }
+ });
+ add(spin);
+ glyphPreview = new GlyphPreview();
+ add(glyphPreview);
+ }
+ void refresh()
+ {
+ spin.setValue(new Integer(character));
+ repaint();
+ }
+ }
+
+ private void loadFont(File file)
+ {
+ try
+ {
+ RandomAccessFile raf = new RandomAccessFile(file, "r");
+ FileChannel chan = raf.getChannel();
+ ByteBuffer buf = chan.map(FileChannel.MapMode.READ_ONLY, 0, raf.length());
+ FontDelegate[] fonts = OpenTypeFontFactory.createFonts(buf);
+ font = fonts[0];
+ setGlyph(character);
+ refresh();
+ }
+ catch (Exception ex)
+ {
+ ex.printStackTrace();
+ }
+ }
+
+ void setGlyph(char ch)
+ {
+ character = ch;
+ glyph = (GNUGlyphVector)
+ font.createGlyphVector(new Font("Dialog", 0, 12),
+ new FontRenderContext(null, false, false),
+ new StringCharacterIterator(new String(new char[]{ch})));
+ refresh();
+ }
+
+ public static void main(String[] args) {
+ HintingDemo f = new HintingDemo();
+ f.setSize(500, 500);
+ f.setVisible(true);
+ }
+}
diff --git a/libjava/classpath/examples/gnu/classpath/examples/datatransfer/Demo.java b/libjava/classpath/examples/gnu/classpath/examples/datatransfer/Demo.java
new file mode 100644
index 000000000..3bf9431a1
--- /dev/null
+++ b/libjava/classpath/examples/gnu/classpath/examples/datatransfer/Demo.java
@@ -0,0 +1,652 @@
+/* Demo.java -- And example of copy/paste datatransfer
+ 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.datatransfer;
+
+import java.awt.*;
+import java.awt.event.*;
+import java.awt.datatransfer.*;
+
+import java.io.*;
+import java.net.URL;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.Random;
+
+/**
+ * An example how datatransfer works for copying and pasting data to
+ * and from other programs.
+ */
+class Demo
+ extends Frame
+ implements ActionListener, ItemListener, FlavorListener
+{
+ public static void main(String args[])
+ {
+ new Demo();
+ }
+
+ private TextArea text;
+ private Button copyText;
+ private Button pasteText;
+
+ private ImageComponent image;
+ private Button copyImage;
+ private Button pasteImage;
+
+ private ObjectComponent object;
+ private Button copyObject;
+ private Button pasteObject;
+
+ private FilesComponent files;
+ private Button copyFiles;
+ private Button pasteFiles;
+
+ private FlavorsComponent flavors;
+ private FlavorDetailsComponent details;
+
+ private Demo()
+ {
+ super("GNU Classpath datatransfer");
+
+ /* Add all the different panel to the main window in one row. */
+ setLayout(new GridLayout(5, 1, 10, 10));
+ add(createTextPanel());
+ add(createImagePanel());
+ add(createObjectPanel());
+ add(createFilesPanel());
+ add(createFlavorsPanel());
+
+ /* Add listeners for the various buttons and events we are
+ interested in. */
+ addWindowListener(new WindowAdapter ()
+ {
+ public void windowClosing (WindowEvent e)
+ {
+ dispose();
+ }
+ });
+ flavors.addItemListener(this);
+ Toolkit t = Toolkit.getDefaultToolkit();
+ Clipboard c = t.getSystemClipboard();
+ c.addFlavorListener(this);
+
+ /* Show time! */
+ pack();
+ show();
+ }
+
+ /**
+ * The Text Panel will show simple text that can be copied and pasted.
+ */
+ private Panel createTextPanel()
+ {
+ Panel textPanel = new Panel();
+ textPanel.setLayout(new BorderLayout());
+ text = new TextArea("GNU Everywhere!",
+ 2, 80,
+ TextArea.SCROLLBARS_VERTICAL_ONLY);
+ text.setEditable(false);
+ text.setEnabled(true);
+ Panel textButtons = new Panel();
+ textButtons.setLayout(new FlowLayout());
+ copyText = new Button("Copy text");
+ copyText.addActionListener(this);
+ pasteText = new Button("Paste text");
+ pasteText.addActionListener(this);
+ textButtons.add(copyText);
+ textButtons.add(pasteText);
+ textPanel.add(text, BorderLayout.CENTER);
+ textPanel.add(textButtons, BorderLayout.SOUTH);
+ return textPanel;
+ }
+
+ /**
+ * The Image Panel shows an image that can be copied to another
+ * program or be replaced by pasting in an image from another
+ * application.
+ */
+ private Panel createImagePanel()
+ {
+ Panel imagePanel = new Panel();
+ imagePanel.setLayout(new BorderLayout());
+ URL imageurl = this.getClass()
+ .getResource("/gnu/classpath/examples/icons/big-fullscreen.png");
+ Image img = Toolkit.getDefaultToolkit().createImage(imageurl);
+ image = new ImageComponent(img);
+ Panel imageButtons = new Panel();
+ copyImage = new Button("Copy image");
+ copyImage.addActionListener(this);
+ pasteImage = new Button("Paste image");
+ pasteImage.addActionListener(this);
+ imageButtons.add(copyImage);
+ imageButtons.add(pasteImage);
+ imagePanel.add(image, BorderLayout.CENTER);
+ imagePanel.add(imageButtons, BorderLayout.SOUTH);
+ return imagePanel;
+ }
+
+ /**
+ * The Object Panel holds a simple (Point) object that can be copied
+ * and pasted to another program that supports exchanging serialized
+ * objects.
+ */
+ private Panel createObjectPanel()
+ {
+ Panel objectPanel = new Panel();
+ objectPanel.setLayout(new BorderLayout());
+ Random random = new Random();
+ int x = (byte) random.nextInt();
+ int y = (byte) random.nextInt();
+ object = new ObjectComponent(new Point(x, y));
+ Panel objectButtons = new Panel();
+ copyObject = new Button("Copy object");
+ copyObject.addActionListener(this);
+ pasteObject = new Button("Paste object");
+ pasteObject.addActionListener(this);
+ objectButtons.add(copyObject);
+ objectButtons.add(pasteObject);
+ objectPanel.add(object, BorderLayout.CENTER);
+ objectPanel.add(objectButtons, BorderLayout.SOUTH);
+ return objectPanel;
+ }
+
+ /**
+ * The Files Panel shows the files from the current working
+ * directory. They can be copied and pasted between other
+ * applications that support the exchange of file lists.
+ */
+ private Panel createFilesPanel()
+ {
+ Panel filesPanel = new Panel();
+ filesPanel.setLayout(new BorderLayout());
+ files = new FilesComponent(new File(".").listFiles());
+ Panel filesButtons = new Panel();
+ copyFiles = new Button("Copy files");
+ copyFiles.addActionListener(this);
+ pasteFiles = new Button("Paste files");
+ pasteFiles.addActionListener(this);
+ filesButtons.add(copyFiles);
+ filesButtons.add(pasteFiles);
+ filesPanel.add(files, BorderLayout.CENTER);
+ filesPanel.add(filesButtons, BorderLayout.SOUTH);
+ return filesPanel;
+ }
+
+ /**
+ * The Flavors Panel shows the different formats (mime-types) that
+ * data on the clipboard is available in. By clicking on a flavor
+ * details about the representation class and object is given.
+ */
+ private Panel createFlavorsPanel()
+ {
+ Panel flavorsPanel = new Panel();
+ flavorsPanel.setLayout(new BorderLayout());
+ Label flavorsHeader = new Label("Flavors on clipboard:");
+ Toolkit t = Toolkit.getDefaultToolkit();
+ Clipboard c = t.getSystemClipboard();
+ DataFlavor[] dataflavors = c.getAvailableDataFlavors();
+ flavors = new FlavorsComponent(dataflavors);
+ details = new FlavorDetailsComponent(null);
+ flavorsPanel.add(flavorsHeader, BorderLayout.NORTH);
+ flavorsPanel.add(flavors, BorderLayout.CENTER);
+ flavorsPanel.add(details, BorderLayout.SOUTH);
+ return flavorsPanel;
+ }
+
+ /**
+ * FlavorListener implementation that updates the Flavors Panel
+ * whenever a change in the mime-types available has been detected.
+ */
+ public void flavorsChanged(FlavorEvent event)
+ {
+ Toolkit t = Toolkit.getDefaultToolkit();
+ Clipboard c = t.getSystemClipboard();
+ DataFlavor[] dataflavors = c.getAvailableDataFlavors();
+ flavors.setFlavors(dataflavors);
+ details.setDataFlavor(null);
+ }
+
+ /**
+ * ItemChangeListener implementation that updates the flavor details
+ * whenever the user selects a different representation of the data
+ * available on the clipboard.
+ */
+ public void itemStateChanged(ItemEvent evt)
+ {
+ DataFlavor df = null;
+ String s = flavors.getSelectedItem();
+ if (s != null)
+ {
+ try
+ {
+ df = new DataFlavor(s);
+ }
+ catch (ClassNotFoundException cnfe)
+ {
+ cnfe.printStackTrace();
+ }
+ }
+ details.setDataFlavor(df);
+ }
+
+ /**
+ * ActionListener implementations that will copy or past data
+ * to/from the clipboard when the user requests that for the text,
+ * image, object of file component.
+ */
+ public void actionPerformed (ActionEvent evt)
+ {
+ Button b = (Button) evt.getSource();
+ Toolkit t = Toolkit.getDefaultToolkit();
+ Clipboard c = t.getSystemClipboard();
+ if (b == copyText)
+ c.setContents(new StringSelection(text.getText()), null);
+
+ if (b == pasteText)
+ {
+ String s = null;
+ try
+ {
+ s = (String) c.getData(DataFlavor.stringFlavor);
+ }
+ catch (UnsupportedFlavorException dfnse)
+ {
+ }
+ catch (IOException ioe)
+ {
+ }
+ catch (ClassCastException cce)
+ {
+ }
+ if (s == null)
+ t.beep();
+ else
+ text.setText(s);
+ }
+
+ if (b == copyImage)
+ c.setContents(new ImageSelection(image.getImage()), null);
+
+ if (b == pasteImage)
+ {
+ Image i = null;
+ try
+ {
+ i = (Image) c.getData(DataFlavor.imageFlavor);
+ }
+ catch (UnsupportedFlavorException dfnse)
+ {
+ }
+ catch (IOException ioe)
+ {
+ }
+ catch (ClassCastException cce)
+ {
+ }
+ if (i == null)
+ t.beep();
+ else
+ image.setImage(i);
+ }
+
+ if (b == copyObject)
+ c.setContents(new ObjectSelection(object.getObject()), null);
+
+ if (b == pasteObject)
+ {
+ Serializable o = null;
+ try
+ {
+ o = (Serializable) c.getData(ObjectSelection.objFlavor);
+ }
+ catch (UnsupportedFlavorException dfnse)
+ {
+ }
+ catch (IOException ioe)
+ {
+ }
+ catch (ClassCastException cce)
+ {
+ }
+ if (o == null)
+ t.beep();
+ else
+ object.setObject(o);
+ }
+
+ if (b == copyFiles)
+ c.setContents(new FilesSelection(files.getFiles()), null);
+
+ if (b == pasteFiles)
+ {
+ java.util.List fs = null;
+ try
+ {
+ fs = (java.util.List) c.getData(DataFlavor.javaFileListFlavor);
+ }
+ catch (UnsupportedFlavorException dfnse)
+ {
+ }
+ catch (IOException ioe)
+ {
+ }
+ catch (ClassCastException cce)
+ {
+ }
+ if (fs == null)
+ t.beep();
+ else
+ files.setFiles(fs);
+ }
+ }
+
+ /**
+ * Simple awt component that shows an settable image.
+ */
+ static class ImageComponent extends Component
+ {
+ private Image image;
+
+ ImageComponent(Image image)
+ {
+ setSize(20, 20);
+ setImage(image);
+ }
+
+ Image getImage()
+ {
+ return image;
+ }
+
+ void setImage(Image image)
+ {
+ this.image = image;
+ repaint();
+ }
+
+ public void paint(Graphics g)
+ {
+ g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
+ }
+ }
+
+ /**
+ * Simple awt component that shows a settable Serializable object.
+ */
+ static class ObjectComponent extends TextArea
+ {
+ private Serializable object;
+
+ ObjectComponent(Serializable object)
+ {
+ super("", 2, 80, TextArea.SCROLLBARS_NONE);
+ setEditable(false);
+ setEnabled(false);
+ setObject(object);
+ }
+
+ Serializable getObject()
+ {
+ return object;
+ }
+
+ void setObject(Serializable object)
+ {
+ this.object = object;
+ setText("Class: " + object.getClass().getName()
+ + "\n"
+ + "toString(): " + object.toString());
+ repaint();
+ }
+ }
+
+ /**
+ * Simple awt component that shows a settable list of Files.
+ */
+ static class FilesComponent extends List
+ {
+ private File[] files;
+
+ FilesComponent(File[] files)
+ {
+ super(4, true);
+ setFiles(files);
+ }
+
+ File[] getFiles()
+ {
+ String[] strings = getSelectedItems();
+ if (strings == null || strings.length == 0)
+ return (File[]) files.clone();
+
+ File[] fs = new File[strings.length];
+ for (int i = 0; i < strings.length; i++)
+ fs[i] = new File(strings[i]);
+ return fs;
+ }
+
+ void setFiles(File[] files)
+ {
+ this.files = files;
+ removeAll();
+ for (int i = 0; i < files.length; i++)
+ {
+ addItem(files[i].toString());
+ select(i);
+ }
+ }
+
+ void setFiles(java.util.List list)
+ {
+ File[] fs = new File[list.size()];
+ int i = 0;
+ Iterator it = list.iterator();
+ while (it.hasNext())
+ fs[i++] = (File) it.next();
+
+ setFiles(fs);
+ }
+ }
+
+ /**
+ * Simple awt component that shows a settable list of DataFlavors.
+ */
+ static class FlavorsComponent extends List
+ {
+ FlavorsComponent(DataFlavor[] flavors)
+ {
+ super(4);
+ setFlavors(flavors);
+ }
+
+ void setFlavors(DataFlavor[] flavors)
+ {
+ removeAll();
+ for (int i = 0; i < flavors.length; i++)
+ {
+ addItem(flavors[i].getMimeType());
+ }
+ }
+ }
+
+ /**
+ * Simple awt component that shows the details for and an object as
+ * found on the system clipboard as represented by a given
+ * DataFlavor.
+ */
+ static class FlavorDetailsComponent extends TextArea
+ {
+ private DataFlavor df;
+
+ FlavorDetailsComponent(DataFlavor df)
+ {
+ super("", 2, 80, TextArea.SCROLLBARS_NONE);
+ setEditable(false);
+ setEnabled(false);
+ setDataFlavor(df);
+ }
+
+ void setDataFlavor(DataFlavor df)
+ {
+ if (df == this.df
+ || (df != null && df.equals(this.df)))
+ return;
+
+ this.df = df;
+
+ if (df == null)
+ setText("No flavor selected");
+ else
+ {
+ Object o = null;
+ Throwable exception = null;
+ try
+ {
+ Toolkit t = Toolkit.getDefaultToolkit();
+ Clipboard c = t.getSystemClipboard();
+ o = c.getData(df);
+ }
+ catch (Throwable t)
+ {
+ exception = t;
+ }
+ if (o != null)
+ {
+ setText("Data: " + o.getClass().getName()
+ + "\n"
+ + o);
+ }
+ else
+ {
+ setText("Error retrieving: " + df
+ + "\n"
+ + exception != null ? exception.toString() : "");
+ }
+ }
+ repaint();
+ }
+ }
+
+ /**
+ * Helper class to put an Image on a clipboard as
+ * DataFlavor.imageFlavor.
+ */
+ static class ImageSelection implements Transferable
+ {
+ private final Image img;
+
+ ImageSelection(Image img)
+ {
+ this.img = img;
+ }
+
+ static DataFlavor[] flavors = new DataFlavor[] { DataFlavor.imageFlavor };
+ public DataFlavor[] getTransferDataFlavors()
+ {
+ return (DataFlavor[]) flavors.clone();
+ }
+
+ public boolean isDataFlavorSupported(DataFlavor flavor)
+ {
+ return flavor.equals(DataFlavor.imageFlavor);
+ }
+
+ public Object getTransferData(DataFlavor flavor)
+ throws UnsupportedFlavorException
+ {
+ if (!isDataFlavorSupported(flavor))
+ throw new UnsupportedFlavorException(flavor);
+
+ return img;
+ }
+ }
+
+ /**
+ * Helper class to put an Object on a clipboard as Serializable
+ * object.
+ */
+ static class ObjectSelection implements Transferable
+ {
+ private final Serializable obj;
+
+ ObjectSelection(Serializable obj)
+ {
+ this.obj = obj;
+ }
+
+ static DataFlavor objFlavor = new DataFlavor(Serializable.class,
+ "Serialized Object");
+ static DataFlavor[] flavors = new DataFlavor[] { objFlavor };
+ public DataFlavor[] getTransferDataFlavors()
+ {
+ return (DataFlavor[]) flavors.clone();
+ }
+
+ public boolean isDataFlavorSupported(DataFlavor flavor)
+ {
+ return flavor.equals(objFlavor);
+ }
+
+ public Object getTransferData(DataFlavor flavor)
+ throws UnsupportedFlavorException
+ {
+ if (!isDataFlavorSupported(flavor))
+ throw new UnsupportedFlavorException(flavor);
+
+ return obj;
+ }
+ }
+
+ /**
+ * Helper class to put a List of Files on the clipboard as
+ * DataFlavor.javaFileListFlavor.
+ */
+ static class FilesSelection implements Transferable
+ {
+ private final File[] files;
+
+ FilesSelection(File[] files)
+ {
+ this.files = files;
+ }
+
+ static DataFlavor[] flavors = new DataFlavor[]
+ { DataFlavor.javaFileListFlavor };
+ public DataFlavor[] getTransferDataFlavors()
+ {
+ return (DataFlavor[]) flavors.clone();
+ }
+
+ public boolean isDataFlavorSupported(DataFlavor flavor)
+ {
+ return flavor.equals(DataFlavor.javaFileListFlavor);
+ }
+
+ public Object getTransferData(DataFlavor flavor)
+ throws UnsupportedFlavorException
+ {
+ if (!isDataFlavorSupported(flavor))
+ throw new UnsupportedFlavorException(flavor);
+
+ return Arrays.asList(files);
+ }
+ }
+}
diff --git a/libjava/classpath/examples/gnu/classpath/examples/html/Demo.java b/libjava/classpath/examples/gnu/classpath/examples/html/Demo.java
new file mode 100644
index 000000000..0a3c512bf
--- /dev/null
+++ b/libjava/classpath/examples/gnu/classpath/examples/html/Demo.java
@@ -0,0 +1,131 @@
+/* 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.html;
+
+import gnu.javax.swing.text.html.parser.HTML_401F;
+
+import gnu.xml.dom.html2.DomHTMLParser;
+
+import java.io.IOException;
+import java.io.PrintStream;
+import java.io.StringReader;
+
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.w3c.dom.html2.HTMLDocument;
+
+/**
+ * This example demonstrates how to parse HTML input into
+ * org.w3c.dom.html2 document model.
+ * @author Audrius Meskauskas (AudriusA@Bioinformatics.org)
+ */
+public class Demo
+{
+ /**
+ * The sample HTML to parse.
+ */
+ static String input = "<!--2-->a<b iD=1>x</b>y<b><i>c</b>d</i>e";
+
+ public static void main(String[] args)
+ {
+ try
+ {
+ // Create a parser, using our DTD.
+ DomHTMLParser p = new DomHTMLParser(HTML_401F.getInstance());
+ HTMLDocument d = p.parseDocument(new StringReader(input));
+
+ // Print the input HTML.
+ System.out.println(input);
+
+ // Print the parsed data structure.
+ print(System.out, d, 0);
+ }
+ catch (IOException ex)
+ {
+ ex.printStackTrace();
+ }
+ }
+
+ /**
+ * Print the parsed data structure.
+ *
+ * @param stream the output
+ * @param node the node
+ * @param ident the identation
+ */
+ static void print(PrintStream stream, Node node, int ident)
+ {
+ if (node == null)
+ return;
+
+ StringBuilder tab = new StringBuilder();
+ stream.println();
+ for (int i = 0; i < ident; i++)
+ {
+ tab.append(' ');
+ }
+
+ stream.print(tab + node.getNodeName());
+ if (node.getNodeValue() != null)
+ {
+ stream.println();
+ stream.print(tab + " '" + node.getNodeValue() + "'");
+ }
+
+ NamedNodeMap attributes = node.getAttributes();
+ if (attributes != null && attributes.getLength() != 0)
+ {
+ stream.print(' ');
+ for (int i = 0; i < attributes.getLength(); i++)
+ {
+ Node a = attributes.item(i);
+ stream.print(a.getNodeName() + "='" + a.getNodeValue() + "'");
+ }
+ }
+
+ ident += 2;
+
+ NodeList childs = node.getChildNodes();
+ if (childs != null)
+ for (int i = 0; i < childs.getLength(); i++)
+ {
+ print(stream, childs.item(i), ident);
+ }
+ }
+}
diff --git a/libjava/classpath/examples/gnu/classpath/examples/icons/aicas.png b/libjava/classpath/examples/gnu/classpath/examples/icons/aicas.png
new file mode 100644
index 000000000..dcf39654b
--- /dev/null
+++ b/libjava/classpath/examples/gnu/classpath/examples/icons/aicas.png
Binary files differ
diff --git a/libjava/classpath/examples/gnu/classpath/examples/icons/back.png b/libjava/classpath/examples/gnu/classpath/examples/icons/back.png
new file mode 100644
index 000000000..d320f26c6
--- /dev/null
+++ b/libjava/classpath/examples/gnu/classpath/examples/icons/back.png
Binary files differ
diff --git a/libjava/classpath/examples/gnu/classpath/examples/icons/badge.png b/libjava/classpath/examples/gnu/classpath/examples/icons/badge.png
new file mode 100644
index 000000000..2f80ad944
--- /dev/null
+++ b/libjava/classpath/examples/gnu/classpath/examples/icons/badge.png
Binary files differ
diff --git a/libjava/classpath/examples/gnu/classpath/examples/icons/big-fullscreen.png b/libjava/classpath/examples/gnu/classpath/examples/icons/big-fullscreen.png
new file mode 100644
index 000000000..12ca14678
--- /dev/null
+++ b/libjava/classpath/examples/gnu/classpath/examples/icons/big-fullscreen.png
Binary files differ
diff --git a/libjava/classpath/examples/gnu/classpath/examples/icons/big-home.png b/libjava/classpath/examples/gnu/classpath/examples/icons/big-home.png
new file mode 100644
index 000000000..3a8f055a0
--- /dev/null
+++ b/libjava/classpath/examples/gnu/classpath/examples/icons/big-home.png
Binary files differ
diff --git a/libjava/classpath/examples/gnu/classpath/examples/icons/big-warning.png b/libjava/classpath/examples/gnu/classpath/examples/icons/big-warning.png
new file mode 100644
index 000000000..dc8c8a457
--- /dev/null
+++ b/libjava/classpath/examples/gnu/classpath/examples/icons/big-warning.png
Binary files differ
diff --git a/libjava/classpath/examples/gnu/classpath/examples/icons/palme.gif b/libjava/classpath/examples/gnu/classpath/examples/icons/palme.gif
new file mode 100644
index 000000000..694794655
--- /dev/null
+++ b/libjava/classpath/examples/gnu/classpath/examples/icons/palme.gif
Binary files differ
diff --git a/libjava/classpath/examples/gnu/classpath/examples/icons/reload.png b/libjava/classpath/examples/gnu/classpath/examples/icons/reload.png
new file mode 100644
index 000000000..04c575002
--- /dev/null
+++ b/libjava/classpath/examples/gnu/classpath/examples/icons/reload.png
Binary files differ
diff --git a/libjava/classpath/examples/gnu/classpath/examples/icons/stock-copy.png b/libjava/classpath/examples/gnu/classpath/examples/icons/stock-copy.png
new file mode 100644
index 000000000..f2f83e34c
--- /dev/null
+++ b/libjava/classpath/examples/gnu/classpath/examples/icons/stock-copy.png
Binary files differ
diff --git a/libjava/classpath/examples/gnu/classpath/examples/icons/stock-cut.png b/libjava/classpath/examples/gnu/classpath/examples/icons/stock-cut.png
new file mode 100644
index 000000000..f887e1569
--- /dev/null
+++ b/libjava/classpath/examples/gnu/classpath/examples/icons/stock-cut.png
Binary files differ
diff --git a/libjava/classpath/examples/gnu/classpath/examples/icons/stock-go-back.png b/libjava/classpath/examples/gnu/classpath/examples/icons/stock-go-back.png
new file mode 100644
index 000000000..bd5607c6b
--- /dev/null
+++ b/libjava/classpath/examples/gnu/classpath/examples/icons/stock-go-back.png
Binary files differ
diff --git a/libjava/classpath/examples/gnu/classpath/examples/icons/stock-go-down.png b/libjava/classpath/examples/gnu/classpath/examples/icons/stock-go-down.png
new file mode 100644
index 000000000..c8f54fb91
--- /dev/null
+++ b/libjava/classpath/examples/gnu/classpath/examples/icons/stock-go-down.png
Binary files differ
diff --git a/libjava/classpath/examples/gnu/classpath/examples/icons/stock-go-forward.png b/libjava/classpath/examples/gnu/classpath/examples/icons/stock-go-forward.png
new file mode 100644
index 000000000..bc5bcc519
--- /dev/null
+++ b/libjava/classpath/examples/gnu/classpath/examples/icons/stock-go-forward.png
Binary files differ
diff --git a/libjava/classpath/examples/gnu/classpath/examples/icons/stock-mic.png b/libjava/classpath/examples/gnu/classpath/examples/icons/stock-mic.png
new file mode 100644
index 000000000..62fc914c6
--- /dev/null
+++ b/libjava/classpath/examples/gnu/classpath/examples/icons/stock-mic.png
Binary files differ
diff --git a/libjava/classpath/examples/gnu/classpath/examples/icons/stock-new.png b/libjava/classpath/examples/gnu/classpath/examples/icons/stock-new.png
new file mode 100644
index 000000000..db8b08748
--- /dev/null
+++ b/libjava/classpath/examples/gnu/classpath/examples/icons/stock-new.png
Binary files differ
diff --git a/libjava/classpath/examples/gnu/classpath/examples/icons/stock-open.png b/libjava/classpath/examples/gnu/classpath/examples/icons/stock-open.png
new file mode 100644
index 000000000..b1b22e5ed
--- /dev/null
+++ b/libjava/classpath/examples/gnu/classpath/examples/icons/stock-open.png
Binary files differ
diff --git a/libjava/classpath/examples/gnu/classpath/examples/icons/stock-paste.png b/libjava/classpath/examples/gnu/classpath/examples/icons/stock-paste.png
new file mode 100644
index 000000000..35f67d647
--- /dev/null
+++ b/libjava/classpath/examples/gnu/classpath/examples/icons/stock-paste.png
Binary files differ
diff --git a/libjava/classpath/examples/gnu/classpath/examples/icons/stock-quit.png b/libjava/classpath/examples/gnu/classpath/examples/icons/stock-quit.png
new file mode 100644
index 000000000..60a6e40e6
--- /dev/null
+++ b/libjava/classpath/examples/gnu/classpath/examples/icons/stock-quit.png
Binary files differ
diff --git a/libjava/classpath/examples/gnu/classpath/examples/icons/stock-save-as.png b/libjava/classpath/examples/gnu/classpath/examples/icons/stock-save-as.png
new file mode 100644
index 000000000..9d7f9a4cb
--- /dev/null
+++ b/libjava/classpath/examples/gnu/classpath/examples/icons/stock-save-as.png
Binary files differ
diff --git a/libjava/classpath/examples/gnu/classpath/examples/icons/stock-save.png b/libjava/classpath/examples/gnu/classpath/examples/icons/stock-save.png
new file mode 100644
index 000000000..0bc44aba4
--- /dev/null
+++ b/libjava/classpath/examples/gnu/classpath/examples/icons/stock-save.png
Binary files differ
diff --git a/libjava/classpath/examples/gnu/classpath/examples/icons/stock-spell-check.png b/libjava/classpath/examples/gnu/classpath/examples/icons/stock-spell-check.png
new file mode 100644
index 000000000..6f154fd9f
--- /dev/null
+++ b/libjava/classpath/examples/gnu/classpath/examples/icons/stock-spell-check.png
Binary files differ
diff --git a/libjava/classpath/examples/gnu/classpath/examples/java2d/J2dBenchmark.java b/libjava/classpath/examples/gnu/classpath/examples/java2d/J2dBenchmark.java
new file mode 100644
index 000000000..4f6b9f4bd
--- /dev/null
+++ b/libjava/classpath/examples/gnu/classpath/examples/java2d/J2dBenchmark.java
@@ -0,0 +1,1571 @@
+/* J2dBenchmark.java -- Benchmarking utility for java2d,
+ based on the Aicas AWT benchmarker
+ 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 java.awt.AlphaComposite;
+import java.awt.BasicStroke;
+import java.awt.BorderLayout;
+import java.awt.Canvas;
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Frame;
+import java.awt.GradientPaint;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.Image;
+import java.awt.Insets;
+import java.awt.Label;
+import java.awt.MediaTracker;
+import java.awt.Panel;
+import java.awt.Rectangle;
+import java.awt.RenderingHints;
+import java.awt.TexturePaint;
+import java.awt.Toolkit;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.awt.geom.AffineTransform;
+import java.awt.geom.Arc2D;
+import java.awt.geom.CubicCurve2D;
+import java.awt.geom.Ellipse2D;
+import java.awt.geom.GeneralPath;
+import java.awt.geom.Line2D;
+import java.awt.geom.QuadCurve2D;
+import java.awt.geom.Rectangle2D;
+import java.awt.geom.RoundRectangle2D;
+import java.awt.image.BufferedImage;
+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 J2dBenchmark
+ extends Panel
+{
+ /**
+ * Default number of test-iterations.
+ */
+ protected static final int DEFAULT_TEST_SIZE = 1000;
+
+ /**
+ * Default screen size.
+ */
+ protected static final int DEFAULT_SCREEN_WIDTH = 320;
+
+ protected static final int DEFAULT_SCREEN_HEIGHT = 240;
+
+ /**
+ * Java2D tests.
+ */
+ protected static final int J2DTEST_ARC = 1 << 0;
+
+ protected static final int J2DTEST_CUBICCURVE = 1 << 1;
+
+ protected static final int J2DTEST_ELLIPSE = 1 << 2;
+
+ protected static final int J2DTEST_GENERALPATH = 1 << 3;
+
+ protected static final int J2DTEST_LINE = 1 << 4;
+
+ protected static final int J2DTEST_QUADCURVE = 1 << 5;
+
+ protected static final int J2DTEST_RECTANGLE = 1 << 6;
+
+ protected static final int J2DTEST_ROUNDRECTANGLE = 1 << 7;
+
+ protected static final int J2DTEST_IMAGE = 1 << 8;
+
+ protected static final int J2DTEST_NONE = 0;
+
+ /*
+ private static final int J2DTEST_ALL = J2DTEST_ARC | J2DTEST_CUBICCURVE
+ | J2DTEST_ELLIPSE
+ | J2DTEST_GENERALPATH | J2DTEST_LINE
+ | J2DTEST_QUADCURVE
+ | J2DTEST_RECTANGLE
+ | J2DTEST_ROUNDRECTANGLE
+ | J2DTEST_IMAGE;
+ */
+ private static final int J2DTEST_ALL = J2DTEST_ARC | J2DTEST_CUBICCURVE
+ | J2DTEST_ELLIPSE
+ | J2DTEST_LINE
+ | J2DTEST_QUADCURVE
+ | J2DTEST_RECTANGLE
+ | J2DTEST_ROUNDRECTANGLE
+ | J2DTEST_IMAGE;
+
+ int iterations = 1;
+
+ protected int screenWidth = DEFAULT_SCREEN_WIDTH;
+
+ protected int screenHeight = DEFAULT_SCREEN_HEIGHT;
+
+ protected boolean noClippingFlag = true;
+
+ protected boolean withClippingFlag = true;
+
+ protected boolean zeroClippingFlag = true;
+
+ protected boolean singleBufferFlag = true;
+
+ protected boolean doubleBufferFlag = true;
+
+ protected boolean gradientFlag = false;
+
+ protected String texture = null;
+
+ protected boolean strokeFlag = false;
+
+ protected float composite = 1;
+
+ protected int xtranslate = 0;
+
+ protected int ytranslate = 0;
+
+ protected double xshear = 0;
+
+ protected double yshear = 0;
+
+ protected double rotate = 0;
+
+ protected boolean antialiasFlag = false;
+
+ protected AffineTransform affineTransform = null;
+
+ protected int awtTests = J2DTEST_ALL;
+
+ protected int testSize = DEFAULT_TEST_SIZE;
+
+ private Label testLabel;
+
+ private String testContext = "";
+
+ Logger logger = Logger.getLogger("J2dGraphicsBenchmark");
+
+ private Image pngTestImage;
+
+ private Image gifTestImage;
+
+ protected BufferedImage textureImage;
+
+ protected TestSet testSetMap = new TestSet();
+
+ public String init()
+ {
+ boolean loadError = false;
+ pngTestImage = loadImage("../icons/aicas.png");
+ gifTestImage = loadImage("../icons/palme.gif");
+
+ if (texture != null)
+ {
+ textureImage = loadBufferedImage(texture);
+
+ if (textureImage == null)
+ {
+ logger.logp(Level.WARNING, "J2dGraphicsBenchmark", "init",
+ "Unable to load texture - defaulting "
+ + "to solid colours");
+ texture = null;
+ loadError = true;
+ }
+ }
+
+ setLayout(new BorderLayout());
+ testLabel = new Label();
+ add(testLabel, BorderLayout.NORTH);
+ add(new GraphicsTest(), BorderLayout.CENTER);
+
+ if (loadError)
+ return "Unable to load image";
+ else
+ return null;
+ }
+
+ void setTestContext(String testName)
+ {
+ logger.logp(Level.INFO, "J2dGraphicsBenchmark", "recordTest",
+ "--- Starting new test context: " + testName);
+ testContext = testName;
+ testLabel.setText(testName);
+ }
+
+ private void recordTest(String testName, long time)
+ {
+ logger.logp(Level.INFO, "J2dGraphicsBenchmark", "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() + "]");
+ }
+ }
+
+ void testComplete()
+ {
+ System.exit(0);
+ }
+
+ public static void main(String[] args)
+ {
+ int awtTests;
+ int i;
+ boolean endOfOptionsFlag;
+ J2dBenchmark speed = new J2dBenchmark();
+
+ // Parse arguments.
+ i = 0;
+ endOfOptionsFlag = false;
+ awtTests = J2DTEST_NONE;
+ while (i < args.length)
+ {
+ if (! endOfOptionsFlag)
+ {
+ if (args[i].equals("--help") || args[i].equals("-help")
+ || args[i].equals("-h"))
+ {
+ System.out.println("Usage: J2dBenchmark [<options>] [<test> ...]");
+ System.out.println("");
+ System.out.println("Options: -i|--iterations=<n|-1> - number of iterations (-1 is infinite; default "
+ + speed.iterations + ")");
+ System.out.println(" -w|--width=<n> - screen width; default "
+ + DEFAULT_SCREEN_WIDTH);
+ System.out.println(" -h|--height=<n> - screen height; default "
+ + DEFAULT_SCREEN_HEIGHT);
+ System.out.println(" -d|--noDoubleBuffer - disable double-buffering test");
+ System.out.println(" -s|--testsize=<n> - 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=<file> - enable texturing with this file (not compatible with --with-gradients)");
+ System.out.println(" --composite=<n|-1> - set alpha composite level; -1 for random; default 1.0 (no transparency)");
+ System.out.println(" --anti-alias=<on|off> - set anti-aliasing hint (not all implementations respect this); default off");
+ System.out.println(" --x-translate=<n> - set x-axis translation; default 0");
+ System.out.println(" --y-translate=<n> - set y-axis translation; default 0");
+ System.out.println(" --x-shear=<n> - set x-axis shear; default 0");
+ System.out.println(" --y-shear=<n> - set y-axis shear; default 0");
+ System.out.println(" --rotate=<n|-1> - 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: <java> FillRect2 [-sleep <millis>] [-size <int>] [-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 <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <gtk/gtk.h>
+#include <sys/timeb.h>
+
+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 <gtk/gtk.h>
+
+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 <string.h>
+
+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<ObjectName> 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 <neugens@limasoftware.net>
+ */
+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<String, Object> 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 <code>javax.swing.text.DocumentFilter</code> class.
+ *
+ * <p>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.</p>
+ *
+ * @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 <code>javax.swing.text.NavigationFilter</code> class.
+ *
+ * <p>It shows a NavigationFilter which lets you walk word-wise
+ * through a text.</p>
+ *
+ * @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 @@
+<!-- welcome.html -- Some HTML stuff to show Swing HTML
+ 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. -->
+
+<html>
+
+ <head>
+ <title>HTML text styles</title>
+ </head>
+ <body>
+ <form>
+ <a href="welcome.html">Back to start page</a>
+ <h1>Some form elements</h1>
+ <h2>Textarea</h2>
+ <textarea cols="30" rows="5">
+ Hello GNU Classpath world. This text should show up in a text area
+ that has a size of 30 columns and 5 rows
+ </textarea>
+
+ <h2>Input fields</h2>
+ <p>
+ <input type="text" value="This is a normal textfield">
+ <input type="password" value="secret password">
+ </p>
+
+ <h2>Buttons</h2>
+ <p>
+ <input type="submit"></input>
+ <input type="reset"></input>
+ <input type="button" value="Some button"></input>
+ </p>
+
+ <h2>Checkboxes and Radiobuttons</h2>
+ <p>
+ <input type="checkbox" name="2">Check this!</input>
+ <input type="checkbox" name="2">Or this</input>
+ </p>
+ <p>
+ <input type="radio" name="1">A radio button</input>
+ <input type="radio" name="1">Another radio</input>
+ </p>
+ <h2>Select lists and combo boxes</h2>
+ <p>
+ <select>
+ <option>Value1</option>
+ <option>Value2</option>
+ <option>Value3</option>
+ <option label="Labeled value 4">Value4</option>
+ <option>Value5</option>
+ <option>Value6</option>
+ </select>
+ </p>
+ <p>
+ <select size="3">
+ <option>Value1</option>
+ <option>Value2</option>
+ <option>Value3</option>
+ <option label="Labeled value 4">Value4</option>
+ <option>Value5</option>
+ <option>Value6</option>
+ </select>
+ </p>
+ </form>
+ </body>
+</html> \ 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 @@
+<!-- frame1.html -- Some HTML stuff to show Swing HTML
+ 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. -->
+<html>
+<body>
+<h1>Top Left Frame</h1>
+</body>
+</html>
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 @@
+<!-- frame2.html -- Some HTML stuff to show Swing HTML
+ 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. -->
+<html>
+<body>
+<h1>Top Right
+ Frame</h1>
+</body>
+</html>
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 @@
+<!-- frame3.html -- Some HTML stuff to show Swing HTML
+ 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. -->
+<html>
+<body>
+<h1>Bottom Left Frame</h1>
+</body>
+</html>
+
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 @@
+<!-- frame4.html -- Some HTML stuff to show Swing HTML
+ 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. -->
+<html>
+<body>
+<h1>Bottom Left Frame</h1>
+</body>
+</html>
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 @@
+<!-- frames.html -- Some HTML stuff to show Swing HTML
+ 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. -->
+<html>
+<frameset cols="40%,60%" rows="20%,80%">
+ <frame src="frame1.html">
+ <frame src="frame2.html">
+ <frame src="frame3.html">
+ <frame src="frame4.html">
+</frameset>
+</html> \ 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 @@
+<!-- tables.html -- Some HTML stuff to show Swing HTML
+ 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. -->
+
+<html>
+
+<head>
+ <title>HTML text styles</title>
+ </head>
+ <body>
+<h1>Table examples</h1>
+<h2>Table with grid and mixed rowspan/colspan</h2>
+ <table border="1">
+ <tr>
+ <td width="30%" colspan="2">Spans two columns</td>
+ <td rowspan="3">Spans three rows</td>
+ </tr>
+ <tr>
+ <td rowspan="2">Spans two rows</td>
+ <td>This is the center</td>
+ </tr>
+ <tr>
+ <td>This should be in the middle of row number 3</td>
+ </tr>
+ <tr>
+ <td>A small one cell box</td>
+ <td colspan="2" rowspan="2">Spans two x two cells</td>
+ </tr>
+ <tr>
+ <td>Another small one cell box</td>
+ </tr>
+ </table>
+</body></html>
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 @@
+<!-- welcome.html -- Some HTML stuff to show Swing HTML
+ 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. -->
+
+<html>
+
+ <head>
+ <title>HTML text styles</title>
+ </head>
+ <body>
+ <a href="welcome.html">Back to start page</a>
+ <h1>Colors</h1>
+ <p>The following are the 16 named colors in HTML. Of course you can also
+ use all RGB colors by specifying a value in the <code>#RRGGBB</code>
+ notation.</p>
+ <p>
+ <font color="black">Black</font>, <font color="gray">Gray</font>,
+ <font color="maroon">Maroon</font>, <font color="red">Red</font>,
+ <font color="green">Green</font>, <font color="lime">Lime</font>,
+ <font color="olive">Olive</font>, <font color="yellow">Yellow</font>,
+ <font color="navy">Navy</font>, <font color="blue">Blue</font>,
+ <font color="purple">Purple</font>, <font color="fuchsia">Fuchsia</font>,
+ <font color="teal">Teal</font>, <font color="aque">Aqua</font>,
+ <font color="silver">Silver</font>, <font color="white">White</font></p>
+ <h1>Font styles</h1>
+ <p>The following lists the logical and physical font styles that can be set
+ by certain HTML tags</p>
+ <p>
+ <!--<abbr>Abbreviation</abbr>, <acronym>Acronym</acronym>,-->
+ <address>Address</address>, <b>Bold</b>, <big>Big</big>,
+ <cite>Citation</cite>, <code>Code</code>, <del>Deleted</del>,
+ <em>Emphasized<em>, <i>Italic</i>, <ins>Inserted</ins>, <q>Quote</q>,
+ <s>Stroke-Through</s>, <samp>Example</samp>, <small>Small</small>,
+ <strike>Strike</strike>, <strong>Strong</strong>, <sub>Subscript</sub>,
+ <sup>Superscript</sup>, <u>Underlined</u>, <var>Variable</var>
+ </p>
+ <h1>Header Level 1</h1>
+ <h2>Header Level 2</h2>
+ <h3>Header Level 3</h3>
+ <h4>Header Level 4</h4>
+ <h5>Header Level 5</h5>
+ <h6>Header Level 6</h6>
+ <center>Some centered Text</center>
+ </body>
+</html> \ 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 @@
+<!-- welcome.html -- Some HTML stuff to show Swing HTML
+ 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. -->
+
+<html>
+ <head>
+ <title>GNU Classpath HTML Browser</title>
+ </head>
+ <body>
+ <img src="../icons/badge.png" width="100" height="100">
+ <h1>Welcome to GNU Classpath</h1>
+ <h2>A couple of websites that you might want to try out</h2>
+ <ul>
+ <li><a href="http://www.gnu.org/software/classpath/">GNU Classpath homepage</a></li>
+ <li><a href="http://planet.classpath.org">Planet Classpath</a></li>
+ <li><a href="http://developer.classpath.org">GNU Classpath developer pages</a></li>
+ <li><a href="http://www.google.com">Google</a></li>
+ </ul>
+
+ <h2>Testpages</h2>
+ <p>These few pages are here to demonstrate and test the HTML rendering
+ capabilities of GNU Classpath's Swing.</p>
+ <ul>
+ <li><a href="textstyles.html">Text styles</li>
+ <li><a href="forms.html">Form elements</li>
+ <li><a href="tables.html">Tables</li>
+ <li><a href="frames.html">Frames</li>
+ </ul>
+ </body>
+</html> \ No newline at end of file