Realhowto Java
Realhowto Java
This is the PDF version of the Real's HowTo Web site ( http://www.rgagnon.com/howto.html ).
For uptodate content, please refer to the Web site.
There are 4 files : Real's Java , Real's Javascript, Real's Powerbuilder and Real's VBS and Misc
Prog HowTo.
Please don't make PDF versions available on the internet (it's ok in intranet)
From the PDF, you can't run the examples and the links to other Howto's are not working.
If you feel that effort has been useful to you, perhaps you will consider giving something back?
You can make a donation through PayPal at https://www.paypal.com , make you donation to
[email protected]
Contributions via PayPal are accepted in any amount using a credit card or checking account.
(Donations of any size gladly accepted)
Real's Howto copyright notice ( [email protected] )
Redistribution and use in source and binary forms,
with or without modification, are permitted provided
that the following conditions is met:
* the source code is used in a development project
Redistributions of source code or site content
(even partially) in any publications (electronic or paper)
is forbidden without permission.
DISCLAIMER
THIS SOFTWARE IS PROVIDED BY Real Gagnon "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
Real Gagnon BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Real's [email protected]
1 Applet...............................................................................................................................................1
1.1 javaapplet........................................................................................................................1
1.2 Goto to a new URL from an AppletTag(s): Applet.............................................................1
1.3 Determine the host from where the Applet is loadedTag(s): Applet..................................3
1.4 Have a scrolling status lineTag(s): Applet..........................................................................3
1.5 Use a search engineTag(s): Applet...................................................................................5
1.6 Have an onscreen clockTag(s): Applet............................................................................6
1.7 Have Applets on the same page communicate with each otherTag(s): Applet.................8
1.8 Have Applets on different frames communicates with each otherTag(s): Applet..............9
1.9 Send a message from an Applet to another Applet on a different pageTag(s): Applet....11
1.10 Have an applet launch an other appletTag(s): Applet....................................................13
1.11 Get the user nameTag(s): Applet Security.....................................................................14
1.12 Access parameters passed in the URLTag(s): Applet...................................................15
1.13 Convert an Applet to Application Tag(s): Applet............................................................17
1.14 Change the mouse cursor in AppletTag(s): Applet........................................................18
1.15 Use an Image as the Applet backgroundTag(s): Applet AWT.......................................19
1.16 Handle the new Control Activation mechanism in IETag(s): Applet...............................20
1.16.1 Solution #1............................................................................................................20
1.16.2 Solution #2............................................................................................................21
1.16.3 Solution #3............................................................................................................22
1.17 Pass parameters to the Applet JVM (WIN)Tag(s): Applet.............................................23
1.18 See the Java Console Window Log (Java plugin)Tag(s): Applet Environment..............24
1.19 Display debugging infos for an AppletTag(s): Applet.....................................................24
1.20 Have an invisible Applet Tag(s): Applet.........................................................................25
1.21 Keep the JVM loadedTag(s): Applet..............................................................................25
1.22 Detect browser type from an AppletTag(s): Applet Environment Javascript
interaction.............................................................................................................................25
1.23 Call a Javascript from the Applet...................................................................................26
1.24 Get the value from the serverside................................................................................27
2 Date and Time...............................................................................................................................28
2.1 javadate.........................................................................................................................28
2.2 Have year on 4 digits from a Date objectTag(s): Date and Time.....................................28
2.3 Get the current Date and TimeTag(s): Date and Time....................................................28
2.4 Compute days between 2 datesTag(s): Date and Time..................................................29
2.5 Get the number of days in a monthTag(s): Date and Time..............................................31
2.6 Validate a dateTag(s): Date and Time.............................................................................31
2.6.1 Using DateFormat...................................................................................................31
2.6.2 Using GregorianCalendar.......................................................................................33
2.7 Determine to day of the weekTag(s): Date and Time......................................................33
2.8 Add/Substract Day/Month/Year to a DateTag(s): Date and Time....................................34
2.9 Get the correct TimeZone on DateFormatTag(s): Date and Time...................................35
2.10 Simply format a date as "YYYYMMDD"Tag(s): Date and Time.....................................35
2.11 Compare 2 datesTag(s): Date and Time.......................................................................36
2.12 Parse a String to obtain a Date/GregorianCalendar objectTag(s): Date and Time........37
2.13 Use System time to generate unique IDTag(s): Date and Time Date and Time
Varia.......................................................................................................................................38
2.14 Get the day nameTag(s): Date and Time......................................................................38
2.15 Find the current date formatTag(s): Date and Time.......................................................39
2.16 Get a julian dateTag(s): Date and Time.........................................................................40
Real's [email protected]
2 Date and Time
2.17 Calculate the ageTag(s): Date and Time.......................................................................43
2.18 Format a duration in milliseconds into a humanreadable formatTag(s): Date and
Time......................................................................................................................................43
2.19 Get the atomic timeTag(s): Date and Time....................................................................46
2.20 Get a date intervalTag(s): Date and Time......................................................................48
2.21 Determine if an hour is between an intervalTag(s): Date and Time...............................50
2.22 Set the computer clockTag(s): Date and Time JNI........................................................51
2.23 Use System time to generate unique IDTag(s): Date and Time Date and Time
Varia.......................................................................................................................................52
2.24 Get the month (or day) name (localized)Tag(s): Date and Time Internationalization....52
2.25 Detect a leap yearTag(s): Date and Time......................................................................53
3 AWT................................................................................................................................................55
3.1 javaawt...........................................................................................................................55
3.2 Use The CardLayout managerTag(s): AWT....................................................................55
3.3 Detect which card is visible with a CardLayoutTag(s): AWT...........................................57
3.4 Use PopupsTag(s): AWT.................................................................................................58
3.5 Use a File DialogTag(s): AWT.........................................................................................60
3.6 Use TrueType fontTag(s): AWT.......................................................................................61
3.7 Display available fontsTag(s): AWT.................................................................................62
3.8 Font with 3D effectTag(s): AWT.......................................................................................62
3.9 Use the System ClipboardTag(s): AWT...........................................................................63
3.10 Maximize a FrameTag(s): AWT.....................................................................................64
3.11 Center a Frame/DialogTag(s): AWT..............................................................................65
3.12 Close a FrameTag(s): AWT...........................................................................................66
3.13 Call events on a Frame from a PanelTag(s): AWT........................................................68
3.14 Set the small topleft icon on a FrameTag(s): AWT......................................................70
3.15 Prevent a Frame to be resizedTag(s): AWT..................................................................70
3.16 Embed an image into a FrameTag(s): AWT AWT.........................................................72
3.17 Display a message boxTag(s): AWT.............................................................................74
3.18 Display a Splash screenTag(s): AWT............................................................................75
3.19 Vibrate a WindowTag(s): AWT......................................................................................77
3.20 Limit TextField input to numeric valueTag(s): AWT.......................................................79
3.21 Limit TextField input to a maximum lengthTag(s): AWT................................................81
3.22 React to the ENTER key in a TextfieldTag(s): AWT......................................................82
3.23 Make the ENTER key act like the TAB keyTag(s): AWT...............................................83
3.24 Reset all textfields in one shotTag(s): AWT...................................................................83
3.25 Limit a TextField to UppercaseTag(s): AWT..................................................................84
3.26 Have an ImageButtonTag(s): AWT................................................................................85
3.27 Reset a checkbox groupTag(s): AWT............................................................................88
3.28 Set the listbox widthTag(s): AWT...................................................................................89
3.29 Align the column in a ListTag(s): AWT...........................................................................90
3.30 Have a srolling text displayTag(s): AWT........................................................................90
3.31 Label dynamic resizingTag(s): AWT..............................................................................91
3.32 Make a TextArea "wordwrap"Tag(s): AWT..................................................................93
3.33 Synchronize a TextArea vs a ChoiceTag(s): AWT........................................................93
3.34 Display underlined textTag(s): AWT..............................................................................94
3.35 Display vertical textTag(s): AWT....................................................................................94
3.36 Have Label with many linesTag(s): AWT.......................................................................95
Real's [email protected]
3 AWT
3.37 Have a Label with underlined text Tag(s): AWT............................................................99
3.38 Have a Label acting as HTML HREF (URLLabel)Tag(s): AWT...................................100
3.39 Display a GIF in a CanvasTag(s): AWT.......................................................................102
3.40 Embed an image into a FrameTag(s): AWT AWT.......................................................103
3.41 Load several images from a single GIFTag(s): AWT...................................................105
3.42 Load an Image from a JAR fileTag(s): AWT................................................................106
3.43 Load an Icon from a jar (again)Tag(s): AWT...............................................................107
3.44 Scale an ImageTag(s): AWT........................................................................................107
3.45 Fade an imageTag(s): AWT.........................................................................................109
3.46 Rotate an imageTag(s): AWT......................................................................................111
3.47 Create a scrollable canvasTag(s): AWT......................................................................113
3.48 Use an Image as the Applet backgroundTag(s): Applet AWT.....................................117
3.49 Have a simple Image browserTag(s): AWT.................................................................118
3.50 Simulate a "mouse over" event to toggle an imageTag(s): AWT.................................121
3.51 Hide the mouse cursorTag(s): AWT............................................................................123
3.52 Make a color transparentTag(s): AWT.........................................................................123
3.53 Save an Image as a GIF or JPEG fileTag(s): AWT.....................................................124
3.54 Use the same background color as the browserTag(s): AWT.....................................126
3.55 Do simple animation using ImagesTag(s): AWT..........................................................126
3.56 Do simple animation to show "work in progress"Tag(s): AWT.....................................128
3.57 Get the color of a specific pixelTag(s): AWT................................................................129
3.58 Do "rubberband" drawingTag(s): AWT......................................................................130
3.59 Convert RGB value to Hexadecimal (to be used in HTML for example)Tag(s):
AWT....................................................................................................................................132
3.60 Draw a line or set a pixel in my own imageTag(s): AWT.............................................133
3.61 Draw a dashed lineTag(s): AWT..................................................................................133
3.62 Draw a line with a thicknessTag(s): AWT....................................................................134
3.63 Draw a pie chartTag(s): AWT......................................................................................136
3.64 Draw faster rectanglesTag(s): AWT.............................................................................138
3.65 Get a screen capture and save it as a JPEGTag(s): AWT..........................................139
3.66 Detect a double click vs simple clickTag(s): AWT.......................................................140
3.67 Detect the mouse button used when clickingTag(s): AWT..........................................141
3.68 Exit an application from a menuTag(s): AWT..............................................................142
3.69 Trigger a click on a ButtonTag(s): AWT Swing............................................................143
3.70 Display a TIFTag(s): AWT...........................................................................................144
3.71 Convert a multipage TIF into singlepage TIFTag(s): AWT......................................146
3.72 Convert many singlepage TIF into one multipage TIF Tag(s): AWT.......................147
3.73 Convert an Image to a BufferedImageTag(s): AWT....................................................148
3.74 Detect if a TIF is blank Tag(s): AWT............................................................................149
3.75 Convert TIF to PDFTag(s): AWT IO IO Open Source..................................................152
3.76 Convert a TIF to a JPGTag(s): AWT............................................................................153
4 Environment................................................................................................................................155
4.1 javaenv........................................................................................................................155
4.2 Read environment variables from an applicationTag(s): Environment..........................155
4.3 Retrieve environment variables (JDK1.5)Tag(s): Environment......................................159
4.4 Retrieve environment variable (JNI)Tag(s): Environment JNI.......................................159
4.5 Use a MAKE fileTag(s): Environment............................................................................160
4.6 Detect the browser/JVM type (deprecated)Tag(s): Environment DEPRECATED.........161
Real's [email protected]
4 Environment
4.7 Fix the "Wrong magic number" error messageTag(s): Environment.............................163
4.8 Use a precompiler " la C" with JavaTag(s): Environment............................................164
4.9 Open source packages..................................................................................................164
4.10 Ant................................................................................................................................164
4.11 Simple boolean flag.....................................................................................................165
4.12 Determine what are the classes actually used in a Java Applet or application
Tag(s): Environment............................................................................................................165
4.13 Set the memory available to the JVMTag(s): Environment..........................................166
4.14 Generate the Javadoc "en franais"Tag(s): Environment Environment
Internationalization...............................................................................................................166
4.15 Use JDK1.5 new featuresTag(s): Environment............................................................167
4.16 Check the class versionTag(s): Environment..............................................................168
4.17 Get the system properties or the JVM uptimeTag(s): Environment.............................169
4.18 Detect if running in a 64bit JVMTag(s): Environment..................................................170
4.19 Set the default JVM typeTag(s): Environment.............................................................171
4.20 Select a particular JRE from the command lineTag(s): Environment..........................172
4.21 Get the PID (pure Java solution)Tag(s): Environment.................................................173
4.22 Get the PIDTag(s): Environment JNI...........................................................................174
4.23 Set default value for java property (system wide)Tag(s): Environment.......................175
4.24 Detect if running in a debug modeTag(s): Environment..............................................176
4.25 Capture the output of JAVACTag(s): Environment......................................................176
4.26 Freeze the JVIEW window in MS VJ++Tag(s): Environment.......................................177
4.27 Wrap a Java beans in a COM objectTag(s): Environment...........................................177
4.28 Know details about the JAVA at runtimeTag(s): Environment...................................179
4.29 Detect the Microsoft JVM version installedTag(s): Environment.................................180
4.30 Run JAVA as a Windows serviceTag(s): Environment Open Source..........................181
4.31 Execute a class from Windows ExplorerTag(s): Environment.....................................181
4.32 Create an icon to launch java apps for Windows?Tag(s): Environment......................183
4.33 Fix the "out of environment" error when setting a new CLASSPATHTag(s):
Environment........................................................................................................................183
4.34 Query Windows registryTag(s): Environment..............................................................184
4.35 Read/Write the Registry (Windows)Tag(s): Environment............................................186
4.36 Quickly retrieve available Java JVM on a workstation (Windows)Tag(s):
Environment........................................................................................................................194
4.37 Using regedit................................................................................................................194
4.38 Using a CMD file..........................................................................................................195
4.39 Get a return code from a VBSTag(s): IO Environment................................................196
4.40 List currently running processes (Windows)Tag(s): Environment................................197
4.40.1 Using TASKLIST.EXE.........................................................................................197
4.40.2 Using a VBS........................................................................................................198
4.41 Check if a program or process is running (Windows)Tag(s): Environment..................199
4.42 Detect if a process is running using WMIC Tag(s): Misc Prog HowTo Java
Environment........................................................................................................................201
4.43 Windows registry vs. Java JDK/JRE installationTag(s): Environment.........................202
4.44 Get the current Java version from a BAT fileTag(s): Environment..............................203
4.45 Get the Windows "My Documents" pathTag(s): Environment.....................................204
4.46 Get the Windows Desktop pathTag(s): Environment...................................................204
4.47 Get the Windows Special FoldersTag(s): Environment...............................................206
4.48 Create an Internet Shortcut (Windows)Tag(s): Environment.......................................207
Real's [email protected]
4 Environment
4.49 Detect if running in remote session (Windows)Tag(s): Environment...........................208
4.50 Detect if running a Citrix session (Windows)Tag(s): IO...............................................210
4.51 Create a Taglet to document database access (Javadoc)Tag(s): Environment..........210
4.51.1 newMethod.........................................................................................................211
4.52 Generate the Javadoc "en franais"Tag(s): Environment Environment
Internationalization...............................................................................................................214
4.53 Document a package using Javadoc Tag(s): Environment.........................................215
4.54 Display a comment in a JavadocTag(s): Environment.................................................216
4.55 Display XML in a javadocTag(s): Environment............................................................217
4.56 Add a copyright notice to a JavadocTag(s): Environment...........................................218
4.57 Use a Log fileTag(s): Environment..............................................................................218
4.58 Trace the executionTag(s): Environment.....................................................................221
4.59 Time the executionTag(s): Environment......................................................................222
4.60 Log information efficiently (with Log4J)Tag(s): Environment.......................................223
4.61 Change the logging level onthefly (Log4J)Tag(s): Environment..............................224
4.62 Enable debug log level on OpenSource package(Apache Commons Logging)
Tag(s): Environment............................................................................................................225
4.63 Use a JAR/ZIP/CAB file with an AppletTag(s): Environment.......................................226
4.64 Make ZIP/JAR file always accessible from appletTag(s): Environment.......................228
4.65 Make a JAR executableTag(s): Environment..............................................................228
4.66 Accessing jars from within a jarTag(s): Environment...................................................230
4.67 Access a JAR outside the CLASSPATHTag(s): Environment.....................................230
4.68 Extract a file from a JarTag(s): IO Environment...........................................................231
4.69 Determine if running from JARTag(s): Environment....................................................232
4.70 Get list of classes in package (in a Jar)Tag(s): Environment.......................................234
4.71 Add version to Jar packagingTag(s): Environment......................................................235
4.72 Use ANT to Build a JAR with version/build numberTag(s): Environment....................237
4.73 Include all jars in the classpath definitionTag(s): Environment....................................241
4.74 Windows batch file.......................................................................................................241
4.75 JDK6............................................................................................................................242
4.76 JAR (and ANT).............................................................................................................242
4.77 Detect browser type from an AppletTag(s): Applet Environment Javascript
interaction...........................................................................................................................244
4.78 Call a Javascript from the Applet.................................................................................244
4.79 Get the value from the serverside..............................................................................245
4.80 Detect if Java is enabled from HTMLTag(s): Environment..........................................245
4.81 See the Java Console Window Log (Java plugin)Tag(s): Applet Environment............246
5 Internationalization.....................................................................................................................247
5.1 javainter.......................................................................................................................247
5.2 Load resources based upon client environment at startupTag(s):
Internationalization..............................................................................................................247
5.3 Load resources dynamicallyTag(s): Internationalization................................................250
5.4 Load resources via a resources fileTag(s): Internationalization.....................................253
5.5 Display "special character" using UnicodeTag(s): Internationalization..........................257
5.6 Display chinese/japanese charactersTag(s): Internationalization..................................258
5.7 Localize a JOptionPane dialogTag(s): Internationalization Swing.................................258
5.8 Validate/Convert a number using the current Locale()Tag(s): Internationalization
String/Number......................................................................................................................260
Real's [email protected]
5 Internationalization
5.9 Localize a JFileChooserTag(s): Internationalization Swing...........................................261
5.10 Disable localizationTag(s): Internationalization............................................................264
5.11 Generate the Javadoc "en franais"Tag(s): Environment Environment
Internationalization...............................................................................................................264
5.12 Sort a String arrayTag(s): Internationalization Varia....................................................266
5.13 Accentuated characters in Properties/ResourceBundle fileTag(s):
Internationalization Language.............................................................................................268
5.14 Compare accentuated lettersTag(s): Internationalization String/Number....................268
5.15 Unaccent lettersTag(s): Internationalization String/Number........................................270
5.15.1 Using java.text.Normalizer..................................................................................270
5.15.2 Using String.replaceAll().....................................................................................271
5.15.3 The String.indexOf()............................................................................................271
5.16 Output accentuated characters to the consoleTag(s): IO Internationalization.............273
5.17 Java 1.6 or more..........................................................................................................273
5.18 Java 1.5 or less............................................................................................................274
5.19 Get the default character set of the JVMTag(s): IO Internationalization......................274
5.20 Convert OEM (DOS) file to Ansi (Windows)Tag(s): IO Internationalization.................275
5.21 Detect nonASCII character in a StringTag(s): Internationalization String/Number....276
5.22 Get the month (or day) name (localized)Tag(s): Date and Time
Internationalization...............................................................................................................277
6 IO..................................................................................................................................................279
6.1 javaio...........................................................................................................................279
6.2 Redirect output(stdout/stderr) to a frameTag(s): IO.......................................................279
6.3 Redirect printStackTrace() to a StringTag(s): IO...........................................................280
6.4 Redirect to a NULL deviceTag(s): IO.............................................................................281
6.5 Print a text file using the javax.print APITag(s): IO........................................................282
6.6 Print a String to a printer Tag(s): IO...............................................................................284
6.7 Print text to a printer easilyTag(s): IO............................................................................285
6.8 Print without a DialogTag(s): IO.....................................................................................286
6.9 Initialize and write to a serial portTag(s): IO..................................................................286
6.10 Open or close a CD/DVD driveTag(s): IO....................................................................287
6.11 Get the volume labelTag(s): IO....................................................................................288
6.12 Detect the storage device typeTag(s): IO....................................................................289
6.13 Turn on MQ Debug mode Tag(s): IO...........................................................................290
6.14 Get faster console output (System.out.println() replacement)Tag(s): IO.....................291
6.15 Simple input from the keyboardTag(s): IO...................................................................292
6.16 Output accentuated characters to the consoleTag(s): IO Internationalization.............294
6.17 Java 1.6 or more..........................................................................................................294
6.18 Java 1.5 or less............................................................................................................294
6.19 Clear the console and control attributesTag(s): IO Open Source................................295
6.20 Jansi.............................................................................................................................295
6.21 JCurses........................................................................................................................296
6.22 Easy keyboard input (JDK1.5)Tag(s): IO.....................................................................297
6.23 Force keyboard input in CAPS LOCK onTag(s): IO.....................................................298
6.24 Automatic conversion of System.out output Tag(s): IO...............................................299
6.25 Execute an external programTag(s): IO.......................................................................301
6.26 Using Runtime.exec()..................................................................................................301
6.27 Launch a Windows CMD (or BAT) file and retrieve the errorlevel or exitcode.............302
Real's [email protected]
6 IO
6.28 Launch a Unix script....................................................................................................303
6.29 Using the ProcessBuilder.............................................................................................303
6.30 Windows rundll32 utility...............................................................................................303
6.31 PDF (Windows only)....................................................................................................304
6.32 PDF (Mac only)............................................................................................................304
6.33 Path to executable with spaces in them.......................................................................304
6.34 VBSCRIPT...................................................................................................................305
6.35 HTML Help (Windows only).........................................................................................305
6.36 Start Excel....................................................................................................................305
6.37 Start a Windows application under another account....................................................306
6.38 Windows : execute something in Program Files..........................................................306
6.39 Launch the application associated with a file extensionTag(s): IO..............................307
6.40 Launch an application from another applicationTag(s): IO Language.........................308
6.41 Start the default browser from an applicationTag(s): IO..............................................310
6.42 Execute a Windows Shortcut (.lnk)Tag(s): IO..............................................................312
6.43 Create a file association with a Java programTag(s): IO Misc Prog HowTo................312
6.44 Capture the output from a VBSTag(s): IO....................................................................314
6.45 Get a return code from a VBSTag(s): IO Environment................................................315
6.46 Execute a CMD file stored in a JARTag(s): IO............................................................316
6.47 Open the default file explorerTag(s): IO.......................................................................318
6.48 Read the content of a fileTag(s): IO.............................................................................318
6.49 From a Java application...............................................................................................318
6.50 From a Java applet......................................................................................................319
6.51 Read a text file from a jarTag(s): IO.............................................................................321
6.52 Read a file from the internet Tag(s): Networking IO....................................................323
6.53 Extract a file from a JarTag(s): IO Environment...........................................................324
6.54 Read a data file with floatsTag(s): IO...........................................................................325
6.55 Write to the end of a fileTag(s): IO...............................................................................326
6.56 Write "real" ascii fileTag(s): IO.....................................................................................327
6.57 Copy a fileTag(s): IO....................................................................................................328
6.58 Use a "log file"Tag(s): IO.............................................................................................330
6.59 Delete files with a certain extensionTag(s): IO............................................................332
6.60 Insert a line in a fileTag(s): IO......................................................................................333
6.61 Read a file into a variable in one shotTag(s): IO..........................................................334
6.62 Serialize an object to a fileTag(s): IO...........................................................................334
6.63 Redirect stdout to a fileTag(s): IO................................................................................336
6.64 Get the "last modified" date from a fileTag(s): IO........................................................336
6.65 Check if a file existsTag(s): IO.....................................................................................337
6.66 Detect file modificationTag(s): IO.................................................................................337
6.67 File/directory polling to detect changeTag(s): IO Open Source...................................340
6.68 jpoller (directory poller)................................................................................................340
6.69 JNotify..........................................................................................................................340
6.70 Java Native Access (JNA)...........................................................................................340
6.71 Call native methods in a DLL from Java (NativeCall)..................................................341
6.72 Java 7..........................................................................................................................341
6.73 The simple (and naive!) approach...............................................................................341
6.74 Get the current directoryTag(s): IO..............................................................................341
6.75 Get the "root" of an applicationTag(s): IO....................................................................342
6.76 Get the content of a directory with a FilterTag(s): IO...................................................342
Real's [email protected]
6 IO
6.77 Get the content of a directory with subdirectoriesTag(s): IO........................................345
6.78 Get directory content faster with many files Tag(s): IO................................................346
6.79 Make a directoryTag(s): IO..........................................................................................348
6.80 Create a fixedlength fileTag(s): IO.............................................................................348
6.81 Delete a nonempty directoryTag(s): IO......................................................................349
6.82 Create a temporary fileTag(s): IO................................................................................349
6.83 Get the default character set of the JVMTag(s): IO Internationalization......................350
6.84 Parse a pathnameTag(s): IO.......................................................................................351
6.85 Handle CSV fileTag(s): IO Open Source.....................................................................352
6.86 com.Ostermiller.util CSV Utils......................................................................................352
6.87 opencsv........................................................................................................................352
6.88 ServingXML.................................................................................................................352
6.89 Super CSV...................................................................................................................352
6.90 csvreader.....................................................................................................................352
6.91 CSVFile........................................................................................................................352
6.92 FlatPack.......................................................................................................................352
6.93 CSVJDBC....................................................................................................................353
6.94 FFP..............................................................................................................................353
6.95 Convert OEM (DOS) file to Ansi (Windows)Tag(s): IO Internationalization.................353
6.96 Close a stream in a try/catch blockTag(s): IO..............................................................354
6.97 Rename a file extensionTag(s): IO..............................................................................355
6.98 Remove file extension Tag(s): IO................................................................................357
6.99 Remove HTML tags from a file to extract only the TEXTTag(s): IO String/Number
Networking...........................................................................................................................357
6.100 Using regular expression...........................................................................................357
6.101 Using javax.swing.text.html.HTMLEditorKit...............................................................358
6.102 Using an HTML parser...............................................................................................358
6.103 Using Apache Tika.....................................................................................................359
6.104 Get the Mime Type from a FileTag(s): IO..................................................................360
6.104.1 Using Java 7.....................................................................................................360
6.104.2 Using javax.activation.MimetypesFileTypeMap................................................360
6.104.3 Using java.net.URL...........................................................................................361
6.104.4 Using Apache Tika............................................................................................362
6.104.5 Using JMimeMagic............................................................................................363
6.104.6 Using mimeutil................................................................................................363
6.104.7 Using Droid.......................................................................................................363
6.104.8 Aperture framework...........................................................................................364
6.105 Sort a directory listing (based on the last modified timestamp)Tag(s): IO.................364
6.106 Sort files by the extensionTag(s): IO..........................................................................365
6.107 Filter a directory listing by dateTag(s): IO..................................................................367
6.108 Convert wildcard to a regex expressionTag(s): IO.....................................................368
6.109 Shorten a long pathTag(s): IO String/Number...........................................................369
6.110 Force a valid Windows filenameTag(s): IO................................................................373
6.111 Check if filename is validTag(s): IO...........................................................................374
6.112 Dump a file to a HEX fileTag(s): IO............................................................................375
6.113 List all files in the classpath or in a JarTag(s): IO......................................................376
6.114 Handle UTF8 file with BOMTag(s): IO.......................................................................377
6.115 Touch a file Tag(s): IO...............................................................................................380
6.116 Handle Excel filesTag(s): IO JDBC Open Source......................................................380
Real's [email protected]
6 IO
6.117 JDBCODBC Excel driver.........................................................................................381
6.118 JExcel........................................................................................................................381
6.119 POI.............................................................................................................................382
6.120 JXLS..........................................................................................................................382
6.121 xlSQL.........................................................................................................................383
6.122 JCOM.........................................................................................................................383
6.123 OpenXLS Java Spreadsheet SDK.............................................................................385
6.124 Create an Excel fileTag(s): IO....................................................................................387
6.125 Detect if a XLS Excel file contains a macro (using POI)Tag(s): IO............................387
6.126 Create or process a PDF fileTag(s): IO Open Source...............................................388
6.127 Create a PDFTag(s): IO Open Source.......................................................................390
6.128 iText...........................................................................................................................390
6.129 Split a PDF file (using iText)Tag(s): IO Open Source................................................392
6.130 Concatenate PDF files (using iText)Tag(s): IO Open Source....................................393
6.131 Convert TIF to PDFTag(s): AWT IO IO Open Source................................................394
6.132 Convert HTML to PDF using iTextTag(s): IO Open Source.......................................396
6.133 Convert HTML to PDF using YAHP Tag(s): IO OpenSource.....................................398
6.134 Convert a png/jpg/gif file to PDF using iTextTag(s): IO Open Source.......................400
6.135 Print a PDFTag(s): IO Open Source..........................................................................401
6.136 Extract text from a PDF (with Apache Tika) Tag(s): IO OpenSource........................402
6.137 Create a compressed (ZIP) fileTag(s): IO..................................................................402
6.138 Display compressed (ZIP) file contentTag(s): IO.......................................................403
6.139 Expand the compressed (ZIP) fileTag(s): IO.............................................................405
6.140 Emit a beepTag(s): IO................................................................................................405
6.141 Emit a ToneTag(s): IO...............................................................................................406
6.142 Play an audio file from an applicationTag(s): IO........................................................407
6.143 Produce special sound effectTag(s): IO.....................................................................409
6.144 Use the Java Speech API (JSPAPI)Tag(s): IO..........................................................412
6.145 Play a Windows sound Tag(s): IO.............................................................................414
7 JDBC............................................................................................................................................416
7.1 javajdbc........................................................................................................................416
7.2 Get JDBC driver for major database vendorsTag(s): JDBC..........................................416
7.3 Connect to a database via JDBCODBCTag(s): JDBC.................................................416
7.4 SELECT data from a tableTag(s): JDBC.......................................................................417
7.5 INSERT data into a tableTag(s): JDBC.........................................................................419
7.6 Tag(s): JDBC.................................................................................................................420
7.7 Tag(s): JDBC.................................................................................................................421
7.8 Test for an empty ResultSetTag(s): JDBC.....................................................................421
7.9 Get a record count with a SQL StatementTag(s): JDBC...............................................422
7.10 Store and retrieve an object from a tableTag(s): JDBC...............................................422
7.11 Retrieve an ImageTag(s): JDBC..................................................................................424
7.12 Insert an ImageTag(s): JDBC......................................................................................425
7.13 Call a stored procedureTag(s): JDBC..........................................................................425
7.14 Stored procedure with Input/Output parms and a ResultSetTag(s): JDBC..................426
7.15 Fix incomplete field returned by the ResultSetTag(s): JDBC.......................................427
7.16 Transfer a ResultSet to a JTableTag(s): JDBC Swing.................................................427
7.17 Detect SQL errors or warningsTag(s): JDBC...............................................................428
7.18 Using DSNless connectionTag(s): JDBC...................................................................430
Real's [email protected]
7 JDBC
7.19 Specify a CharSet when connecting to a DBMSTag(s): JDBC....................................430
7.20 List tables in a databaseTag(s): JDBC........................................................................431
7.21 Enable JDBC loggingTag(s): JDBC.............................................................................432
7.22 Detect if a table existsTag(s): JDBC............................................................................433
7.23 Convert a ResultSet to XMLTag(s): JDBC XML..........................................................434
7.24 Display ResultSet data in an HTML Table in ServletTag(s): JDBC Servlet/JSP.........436
7.25 Escape special character in a LIKE clauseTag(s): JDBC............................................436
7.26 Log the SQL StatementsTag(s): JDBC........................................................................437
7.27 Plain JDBC Logging.....................................................................................................437
7.28 P6Spy..........................................................................................................................437
7.29 Proxool.........................................................................................................................438
7.30 JDBC Logger...............................................................................................................438
7.31 Log4JDBC....................................................................................................................438
7.32 Oracle JDBC................................................................................................................438
7.33 Insert data in batch modeTag(s): JDBC.......................................................................438
7.34 Retrieve large ResultSetTag(s): JDBC........................................................................440
7.35 Handle datesTag(s): JDBC..........................................................................................442
7.36 Get current date using JDBCTag(s): JDBC.................................................................443
7.37 Insert the current dateTag(s): JDBC............................................................................444
7.38 Read data from Excel worksheetTag(s): JDBC...........................................................444
7.39 Handle Excel filesTag(s): IO JDBC Open Source........................................................446
7.40 JDBCODBC Excel driver...........................................................................................446
7.41 JExcel..........................................................................................................................446
7.42 POI...............................................................................................................................447
7.43 JXLS............................................................................................................................448
7.44 xlSQL...........................................................................................................................449
7.45 JCOM...........................................................................................................................449
7.46 OpenXLS Java Spreadsheet SDK...............................................................................450
7.47 Connect to an Oracle database with JDBCTag(s): JDBC............................................452
7.48 Connect to Oracle using a connection poolTag(s): JDBC...........................................454
7.49 Retrieve the generated keys (JDBC Oracle)Tag(s): JDBC..........................................457
7.50 Debug Oracle JDBC connectionTag(s): JDBC............................................................458
7.51 Connect to an Oracle database using KerberosTag(s): JDBC....................................460
7.52 Identify the connected program to an Oracle databaseTag(s): JDBC.........................461
7.53 Use a CHAR field in the WHERE clause in a PreparedStatementTag(s): JDBC........463
8 JNI................................................................................................................................................465
8.1 javajni...........................................................................................................................465
8.2 Use native code through JNITag(s): JNI........................................................................465
8.3 Pass a string to/from Java to/from CTag(s): JNI............................................................465
8.4 Set the computer clockTag(s): Date and Time JNI........................................................467
8.5 Determine the signature of a methodTag(s): JNI...........................................................468
8.6 Use arraysTag(s): JNI....................................................................................................469
8.7 Load a DLLTag(s): JNI...................................................................................................471
8.8 Use the MouseWheelTag(s): JNI...................................................................................471
8.9 Throw an Exception (from JNI code)Tag(s): JNI............................................................472
8.10 Throw my own Exception (from JNI code)Tag(s): JNI.................................................472
8.11 JNI from a packageTag(s): JNI....................................................................................473
8.12 Make a Window "stay on top"Tag(s): JNI....................................................................474
Real's [email protected]
8 JNI
8.13 Start a JVM from CTag(s): JNI.....................................................................................474
8.14 Retrieve environment variable (JNI)Tag(s): Environment JNI.....................................475
8.15 Get the PIDTag(s): Environment JNI...........................................................................476
8.16 Clear the console, set color and cursor position (JNI)Tag(s): JNI...............................477
8.17 Call Windows API (Open source solution)Tag(s): JNI Open Source...........................480
8.18 Detect if a program is running (JNA)Tag(s): JNI/JNA..................................................480
8.19 Get Windows Special Folders (JNA) Tag(s): JNI/JNA.................................................481
9 Javascript interaction.................................................................................................................483
9.1 javajs............................................................................................................................483
9.2 * Read me *Tag(s): Javascript interaction.....................................................................483
9.3 Wakeup a Java appletTag(s): Javascript interaction...................................................483
9.4 Call a Java method from JavascriptTag(s): Javascript interaction.................................486
9.5 Calling Java applets methods using DOM and JavaScriptTag(s): Javascript
interaction...........................................................................................................................487
9.6 Access Java variables from JavascriptTag(s): Javascript interaction............................488
9.7 Call Javascript from a Java appletTag(s): Javascript interaction...................................489
9.8 Using the javascript: protocol.........................................................................................489
9.9 Using the netscape.javascript.JSObject package..........................................................490
9.10 Create dynamic HTML from a Java appletTag(s): Javascript interaction....................491
9.11 Have Applets on different frames communicates with each otherTag(s):
Javascript interaction..........................................................................................................492
9.12 Send a message from an Applet to another Applet on a different pageTag(s):
Javascript interaction..........................................................................................................494
9.13 Retrieve values from a Java applet for HTML form (CGI)Tag(s): Javascript
interaction...........................................................................................................................496
9.14 Detect if an Applet is readyTag(s): Javascript interaction............................................497
9.15 Read/Write HTML field values from JAVATag(s): Javascript interaction.....................498
9.16 Detect if Java is enabledTag(s): Javascript interaction................................................500
9.17 Detect if Java 1.1 (with event delegation) is availableTag(s): Javascript interaction...500
9.18 Access Cookies from a Java AppletTag(s): Javascript interaction..............................501
9.19 Set Applet PARAM VALUE from javascriptTag(s): Javascript interaction...................503
9.20 Pass an Array between Java and JavascriptTag(s): Javascript interaction.................504
9.21 Interaction without LiveConnectTag(s): Javascript interaction.....................................507
9.22 Directory listing on the Web server in a Java AppletTag(s): Javascript interaction.....512
9.23 Have a Java button close the browser windowTag(s): Javascript interaction..............514
9.24 Detect if cookies are enabledTag(s): Javascript interaction........................................515
9.25 Display a page after all applets are loadedTag(s): Javascript interaction....................516
9.26 Detect browser type from an AppletTag(s): Applet Environment Javascript
interaction...........................................................................................................................516
9.27 Call a Javascript from the Applet.................................................................................516
9.28 Get the value from the serverside..............................................................................518
10 Servlet/JSP................................................................................................................................519
10.1 javajsp........................................................................................................................519
10.2 Read meTag(s): Servlet/JSP.......................................................................................519
10.3 Get parameters passed to a servletTag(s): Servlet/JSP..............................................519
10.4 Detect no argument condition in a ServletTag(s): Servlet/JSP....................................520
10.5 Set a Cookie from a servletTag(s): Servlet/JSP..........................................................521
Real's [email protected]
10 Servlet/JSP
10.6 Read a Cookie from a servletTag(s): Servlet/JSP.......................................................521
10.7 Delete (or expire) a Cookie from a servletTag(s): Servlet/JSP....................................522
10.8 Ask for a password from a ServletTag(s): Servlet/JSP................................................522
10.9 Talk to a CGI/ServletTag(s): Networking Servlet/JSP.................................................523
10.10 Test for CookiesTag(s): Servlet/JSP..........................................................................524
10.11 Display ResultSet data in an HTML Table in ServletTag(s): JDBC Servlet/JSP.......524
10.12 Specify the filename to be used for a file sent by a ServletTag(s): Servlet/JSP........525
10.13 Pass information to another servlet/jspTag(s): Servlet/JSP.......................................526
10.14 Handle PDF outputTag(s): Servlet/JSP.....................................................................526
10.15 Detect if the connection is via a secure channelTag(s): Servlet/JSP.........................527
10.16 In a Servlet, check if Form Field is presentTag(s): Servlet/JSP.................................527
10.17 Get the root dir of a web appTag(s): Servlet/JSP Servlet/JSP..................................527
10.18 Get client IP address from JSPTag(s): Servlet/JSP...................................................528
10.19 Output a binary stream from a JSPTag(s): Servlet/JSP............................................528
10.20 Use a connection cache from JSPTag(s): Servlet/JSP Jaguar/EAServer.................529
10.21 Read a Web Application propertyTag(s): Servlet/JSP...............................................531
10.22 Use EJB from JSPTag(s): Servlet/JSP......................................................................531
10.23 Define a method in a JSP pageTag(s): Servlet/JSP..................................................532
10.24 Precompile JSP pagesTag(s): Servlet/JSP...............................................................532
10.25 Get a list of directories for JSPTag(s): Servlet/JSP...................................................533
10.26 Use and share a class in JSP pages Tag(s): Servlet/JSP.........................................534
10.27 Get the root dir of a web appTag(s): Servlet/JSP Servlet/JSP..................................535
10.28 Launch an applet from a JSPTag(s): Servlet/JSP.....................................................536
10.29 Prevent caching of a JSP outputTag(s): Servlet/JSP................................................536
10.30 Launch an external program, capture its output and display it in a JSPTag(s):
Servlet/JSP.........................................................................................................................537
10.31 Call another EJBTag(s): Servlet/JSP Jaguar/EAServer............................................539
10.32 Keep java files generated from JSP (BEA WLS)Tag(s): Servlet/JSP........................539
10.33 Get the server version (BEA WLS)Tag(s): Servlet/JSP.............................................539
10.34 Quickly create a Web application with BEA WLSTag(s): Servlet/JSP.......................540
10.35 Nicely display WEB.XML informationsTag(s): Servlet/JSP XML Jaguar/EAServer...540
10.36 Reverse the CLASSLOADER order (BEA)Tag(s): Servlet/JSP.................................542
10.37 Detect change in JSP and recompile (BEA)Tag(s): Servlet/JSP...............................543
10.38 Obtain a remote connection to a DataSource or EJB (Weblogic)Tag(s):
Servlet/JSP.........................................................................................................................543
11 Language...................................................................................................................................546
11.1 javalanguage.............................................................................................................546
11.2 * Read me *Tag(s): Language String/Number.............................................................546
11.3 Obtain from where a Class is loadedTag(s): Language Varia.....................................547
11.4 Get the class name in a static methodTag(s): Language............................................548
11.5 Get the current method nameTag(s): Language..........................................................549
11.6 JDK1.4.........................................................................................................................549
11.7 JDK1.5.........................................................................................................................549
11.8 Call a method dynamically (Reflection)Tag(s): Language...........................................550
11.9 Detect if a package is availableTag(s): Language.......................................................552
11.10 Create an object from a stringTag(s): Language.......................................................553
11.11 Get a variable value from the variable nameTag(s): Language.................................554
11.12 Make methods that have unspecified number of parametersTag(s): Language........555
Real's [email protected]
11 Language
11.13 Create a java source dynamically, compile and callTag(s): Language......................556
11.14 Java 1.6.....................................................................................................................556
11.15 Java 1.5 or less..........................................................................................................557
11.16 Launch an application from another applicationTag(s): IO Language.......................558
11.17 Access the enclosing class from an inner classTag(s): Language............................560
11.18 Access inner class from outsideTag(s): Language....................................................561
11.19 Use globally defined constantsTag(s): Language......................................................562
11.20 Serialize an ObjectTag(s): Language........................................................................563
11.21 Serialize an Object over a socketTag(s): Language..................................................565
11.22 Easily remove my debugging codeTag(s): Language................................................565
11.23 Have a singletonTag(s): Language............................................................................566
11.24 Multiple expressions in for loopsTag(s): Language...................................................566
11.25 Handle the List conflictTag(s): Language..................................................................567
11.26 Use a generic toString()Tag(s): Language.................................................................567
11.27 Use Object.clone()Tag(s): Language.........................................................................569
11.28 Static field, constructor and exceptionTag(s): Language...........................................570
11.29 Use a Label breakTag(s): Language.........................................................................571
11.30 Put printStackTrace() into a StringTag(s): Language................................................572
11.31 Iterate enum valuesTag(s): Language.......................................................................573
11.32 Get fields and values from an Object Tag(s): Language...........................................573
11.33 Use a HashtableTag(s): Language............................................................................575
11.34 Scan the content of a hashtableTag(s): Language....................................................575
11.35 Sort an arrayTag(s): Language Varia........................................................................575
11.36 Initialize multidimensional arrayTag(s): Language.....................................................577
11.37 Get array upperboundTag(s): Language...................................................................578
11.38 Convert a String to an array or an array to a stringTag(s): Language.......................578
11.38.1 String to Array...................................................................................................578
11.38.2 Array to String...................................................................................................579
11.39 Sort in reverse orderTag(s): Language......................................................................580
11.40 Resize an arrayTag(s): Language.............................................................................580
11.41 Dump array contentTag(s): Language.......................................................................582
11.42 Initialize a static arrayTag(s): Language....................................................................583
11.43 Sort an HashtableTag(s): Language..........................................................................583
11.44 Eliminate "[unchecked] unchecked call ..." compiler warning Tag(s): Language.......585
12 ANT............................................................................................................................................587
12.1 Sort on many fieldsTag(s): Language..........................................................................587
12.2 Optimize Collection usageTag(s): Language...............................................................589
12.3 Sort an HashMapTag(s): Language.............................................................................591
12.4 Get keys corresponding to a value from a MapTag(s): Language...............................592
12.5 Iterate a Collection and remove an itemTag(s): Language..........................................594
12.6 Count distinct elements in a VectorTag(s): Language.................................................595
12.7 Dump the content of a Collection (JDK 1.5)Tag(s): Language....................................596
12.7.1 List......................................................................................................................596
12.7.2 Map.....................................................................................................................597
12.8 Initialize a CollectionTag(s): Language........................................................................597
12.9 Merge (or add) two arrays into oneTag(s): Language.................................................600
12.10 Define an array (or Map, or ENUM) of functionsTag(s): Language...........................601
12.10.1 Using an interface.............................................................................................601
Real's [email protected]
12 ANT
12.10.2 Using an enum..................................................................................................602
12.11 Join a List as a StringTag(s): Language....................................................................603
12.12 Remove duplicates from a List Tag(s): Language.....................................................604
12.13 Convert a Map to a Properties (or vice versa)Tag(s): Language...............................605
12.14 Use an INI file (properties)Tag(s): Language.............................................................606
12.15 Open Source packages.............................................................................................606
12.16 Using Properties........................................................................................................606
12.17 Load a properties fileTag(s): Language.....................................................................608
12.18 Accentuated characters in Properties/ResourceBundle fileTag(s):
Internationalization Language.............................................................................................609
12.19 Have a multiline value in a properties fileTag(s): Language....................................609
12.20 Use XML with PropertiesTag(s): Language XML.......................................................610
12.21 Use the Registry to store informations (Preferences API)Tag(s): Language.............611
12.22 Sort Properties when savingTag(s): Language..........................................................612
13 Networking................................................................................................................................614
13.1 javanet.......................................................................................................................614
13.2 Extract network card addressTag(s): Networking........................................................614
13.3 Get the workstation name/ipTag(s): Networking..........................................................617
13.4 Find port number not in useTag(s): Networking...........................................................618
13.5 Disable DNS cachingTag(s): Networking.....................................................................619
13.6 Allow user:password in URLTag(s): Networking Security Common problems
WinAPI/Registry...................................................................................................................620
13.7 Encode/Decode to/from Base64Tag(s): String/Number Networking...........................621
13.8 Using javax.mail.internet.MimeUtility...........................................................................621
13.9 Using Apache Commons Codec..................................................................................622
13.10 MiGBase64................................................................................................................622
13.11 Lookup using MX record to validate mail serverTag(s): Networking..........................622
13.12 Send an email using the SMTP protocolTag(s): Networking.....................................631
13.13 Check if there is mail waitingTag(s): Networking.......................................................632
13.14 Receive emailTag(s): Networking..............................................................................634
13.15 Send email with an attachmentTag(s): Networking...................................................636
13.16 Send email with JavaMailTag(s): Networking............................................................641
13.17 Send email with authenticationTag(s): Networking....................................................644
13.18 Send HTML mail with images (Javamail)Tag(s): Networking....................................645
13.19 Debug a JavaMail ProgramTag(s): Networking.........................................................647
13.20 JavaMail Debug mode...............................................................................................647
13.21 Verify connectivity to the MailServer with Telnet :.....................................................648
13.22 Use a JavaMail server mockup to act as "inmemory" mail server.........................648
13.23 Send email with SMTPS (eg. Google GMail) (Javamail)Tag(s): Networking.............648
13.23.1 Settings for well known mail providers..............................................................650
13.24 Mix plain text and HTML content in a mailTag(s): Networking...................................650
13.25 Read an Outlook MSG fileTag(s): Networking Open Source.....................................651
13.26 Apache POI HSMF....................................................................................................651
13.27 msgparser..................................................................................................................653
13.28 jmbox.........................................................................................................................654
13.29 Handle EML file with JavaMailTag(s): Networking.....................................................654
13.30 Loading an .EML file..................................................................................................654
13.31 Saving an email to .EML file......................................................................................655
Real's [email protected]
13 Networking
13.32 Receive email using IMAPTag(s): Networking...........................................................656
13.33 Receive email using POP3Tag(s): Networking..........................................................659
13.34 Check if a file was modified on the serverTag(s): Networking...................................661
13.35 Check if a page existsTag(s): Networking.................................................................661
13.36 Connect through a ProxyTag(s): Networking Networking..........................................663
13.36.1 The Networking Properties................................................................................663
13.36.2 Proxy and Username/Password........................................................................664
13.36.3 Bypass a Proxy.................................................................................................666
13.37 Identify yourself using HTTP AuthentificationTag(s): Networking..............................666
13.38 Talk to a CGI/ServletTag(s): Networking Servlet/JSP...............................................668
13.39 Write/Read cookies using HTTPTag(s): Networking.................................................669
13.40 Read a file from the internet Tag(s): Networking IO..................................................671
13.41 Read a GIF or CLASS from an URL save it locallyTag(s): Networking.....................672
13.42 Resolve a relative URLTag(s): Networking................................................................674
13.43 File size from URLTag(s): Networking.......................................................................674
13.44 Use the HTTPS protocolTag(s): Networking..............................................................675
13.45 Fix certificate problem in HTTPSTag(s): Networking.................................................675
13.46 Fetch a page from GoogleTag(s): Networking...........................................................677
13.47 Upload a file to a serverTag(s): Networking...............................................................678
13.48 Remove HTML tags from a file to extract only the TEXTTag(s): IO
String/Number Networking...................................................................................................679
13.49 Using regular expression...........................................................................................679
13.50 Using javax.swing.text.html.HTMLEditorKit...............................................................679
13.51 Using an HTML parser...............................................................................................680
13.52 Using Apache Tika.....................................................................................................681
13.53 Extract links from an HTML pageTag(s): String/Number Networking........................682
13.54 Using javax.swing.text.html.HTMLEditorKit...............................................................682
13.55 Using an HTML parser...............................................................................................682
13.56 Call a web service (generated with BEA ServiceGen)Tag(s): Networking................683
13.57 Do basic authentication when calling a webservice Tag(s): Networking...................685
13.58 WS authentication from Weblogic..............................................................................686
13.59 Have a simple HTTP serverTag(s): Networking........................................................686
13.60 Connect through a ProxyTag(s): Networking Networking..........................................688
13.60.1 The Networking Properties................................................................................688
13.60.2 Proxy and Username/Password........................................................................690
13.60.3 Bypass a Proxy.................................................................................................691
13.61 Have timeout on socket connectionTag(s): Networking.............................................691
13.62 Ping a serverTag(s): Networking...............................................................................692
13.63 Get the Date from serverTag(s): Networking.............................................................693
13.64 Use the java.net.Socket.setSoLinger methodTag(s): Networking.............................694
13.65 Use the java.net.Socket.setTcpNoDelay methodTag(s): Networking........................694
13.66 Find out who is accessing my ServerSocketTag(s): Networking...............................695
13.67 Transfer a file via SocketTag(s): Networking.............................................................695
14 Security......................................................................................................................................698
14.1 javasecurity................................................................................................................698
14.2 Encrypt a passwordTag(s): Security............................................................................698
14.3 Transmit a password with MessageDigest..................................................................698
14.4 Store a password in a properties file............................................................................699
Real's [email protected]
14 Security
14.5 Create a checksumTag(s): Security.............................................................................702
14.6 Get the user nameTag(s): Applet Security...................................................................706
14.7 Get username using NT Challenge (NTLM)Tag(s): Security.......................................707
14.8 Check if the current user belongs a specific Windows group/roleTag(s): Security
Powerscript..........................................................................................................................709
14.9 Allow user:password in URLTag(s): Networking Security Common problems
WinAPI/Registry...................................................................................................................709
14.10 Prompt for password from the consoleTag(s): Security.............................................710
14.11 Prevent XSS exploitTag(s): Security..........................................................................711
14.12 Sanitize the input by removing suspicious tags.........................................................711
14.13 Sanitize the input based on a policy file.....................................................................712
14.14 Sanitize the output by removing suspicious characters.............................................712
14.15 Display a simple username/password Dialog from an AppletTag(s): Security..........713
15 Swing.........................................................................................................................................716
15.1 javaswing...................................................................................................................716
15.2 * Read me *Tag(s): Swing...........................................................................................716
15.3 Change component default fontTag(s): Swing.............................................................716
15.4 Repaint problem under the mouse cursor (JDK1.2)Tag(s): Swing..............................717
15.5 Set the LookAndFeelTag(s): Swing.............................................................................717
15.6 Use any LookAndFeel on any plateformTag(s): Swing................................................718
15.7 Use a TimerTag(s): Swing...........................................................................................719
15.8 Share ActionEvent handlerTag(s): Swing....................................................................719
15.9 Get default values for Swingbased user interfaceTag(s): Swing...............................721
15.10 Have a systray icon (Windows)Tag(s): Swing...........................................................722
15.11 Close a JFrame under conditionTag(s): Swing..........................................................724
15.12 Maximize a JFrameTag(s): Swing.............................................................................725
15.13 Capture System.out into a JFrameTag(s): Swing......................................................725
15.14 Remove the titlebar of JInternalFrameTag(s): Swing................................................728
15.15 Have borders on a JWindow/JFrameTag(s): Swing..................................................728
15.16 Display HTML in a JScrollPaneTag(s): Swing...........................................................729
15.17 Use a JOptionPaneTag(s): Swing..............................................................................730
15.18 Localize a JOptionPane dialogTag(s): Internationalization Swing.............................731
15.19 Customize JOptionPane buttonsTag(s): Swing.........................................................733
15.20 Localize a JFileChooserTag(s): Internationalization Swing.......................................733
15.21 Select a directory with a JFileChooserTag(s): Swing................................................736
15.22 Disable the JFileChooser's "New folder" buttonTag(s): Swing..................................737
15.23 Validate a filename from a JFileChooserTag(s): Swing.............................................739
15.24 Make a JFrame looks like a JDialogTag(s): Swing....................................................740
15.25 Make a JFrame always visibleTag(s): Swing.............................................................741
15.26 Show a JFrame on a specific screen in a dual monitor configuration Tag(s):
Swing..................................................................................................................................742
15.27 Make a JFrame not visible in the the TaskBar Tag(s): Swing....................................742
15.28 Based on JTextField content, enable or disable a JButtonTag(s): Swing..................743
15.29 Apply special filter to a JtextFieldTag(s): Swing........................................................744
15.30 Limit JTextField input to a maximum lengthTag(s): Swing........................................747
15.31 Validate a value on the lostFocus eventTag(s): Swing..............................................748
15.32 Make sure that my jTextfield has the focus when a JFrame is createdTag(s):
Swing..................................................................................................................................751
Real's [email protected]
15 Swing
15.33 Stop the beep on JFormattedTextFieldTag(s): Swing...............................................752
15.34 Right justified JTextfield contentTag(s): Swing..........................................................752
15.35 Set the focus on a particuliar JTextFieldTag(s): Swing..............................................752
15.36 Make JTextField unselectableTag(s): Swing.............................................................753
15.37 Disable copy paste functionality on JTextFieldTag(s): Swing....................................754
15.38 Use a JTree to navigate in a siteTag(s): Swing.........................................................755
15.39 Expand or collapse a JTreeTag(s): Swing.................................................................761
15.40 Have a popup attached to a JTreeTag(s): Swing......................................................763
15.41 Traverse a JTreeTag(s): Swing.................................................................................765
15.42 Show dotted lines in a JTreeTag(s): Swing...............................................................767
15.43 Explore directories with a JTreeTag(s): Swing..........................................................768
15.44 Prevent JTree collapsingTag(s): Swing.....................................................................769
15.45 Single selection in a JTreeTag(s): Swing...................................................................769
15.46 Reduce JTree children indentationTag(s): Swing......................................................770
15.47 Use + or for JTree IconsTag(s): Swing...................................................................770
15.48 Change the JTable header colorTag(s): Swing.........................................................772
15.49 Double click on a JTableTag(s): Swing......................................................................773
15.50 Read a data file into a JTableTag(s): Swing..............................................................775
15.51 Disable row selection in a JTableTag(s): Swing........................................................777
15.52 Read a data file into a JTable and reload if data file have changedTag(s): Swing....777
15.53 Hide a column in JTableTag(s): Swing......................................................................780
15.54 Scroll a JTable to the last rowTag(s): Swing..............................................................781
15.55 Transfer a ResultSet to a JTableTag(s): JDBC Swing...............................................782
15.56 Have on a JScrollPane/JTable an horizontal JScrollbarTag(s): Swing......................782
15.57 Make a JList select an item on doubleclick or the ENTER keyTag(s): Swing............783
15.58 Make a JList like a scrolling text displayTag(s): Swing..............................................784
15.59 Have images in a JListTag(s): Swing.........................................................................785
15.60 Add a row and clear a JListTag(s): Swing.................................................................787
15.61 Sort a JListTag(s): Swing...........................................................................................788
15.62 Double click on a JListTag(s): Swing.........................................................................790
15.63 Have a PopUp on a JListTag(s): Swing.....................................................................791
15.64 Make a JLabel selectable with the mouseTag(s): Swing...........................................792
15.65 Change JLabel background colorTag(s): Swing........................................................793
15.66 Bold / Unbold a JLabelTag(s): Swing.........................................................................794
15.67 Multiline JLabelTag(s): Swing..................................................................................794
15.68 Underline a stringTag(s): Swing.................................................................................794
15.69 Update a JLabelTag(s): Swing...................................................................................795
15.70 Display a blinking JLabelTag(s): Swing.....................................................................796
15.71 Set the cursor position in a JTextAreaTag(s): Swing.................................................797
15.72 Have Multiline string in a JToolTipTag(s): Swing.....................................................798
15.73 Change Tooltip colorTag(s): Swing............................................................................798
15.74 Change a JTooltip fontTag(s): Swing.........................................................................798
15.75 Keep a JTooltip visibleTag(s): Swing.........................................................................799
15.76 Display icon associated with an executableTag(s): Swing........................................800
15.77 Have items in JMenubar at rightmost positionTag(s): Swing.....................................802
15.78 Have an JButton with an ImageTag(s): Swing...........................................................803
15.79 Trigger a click on a ButtonTag(s): AWT Swing..........................................................804
16 Thread
Real's [email protected]
16 Thread........................................................................................................................................806
16.1 javathread..................................................................................................................806
16.2 Pipe the output of a thread to the input of another oneTag(s): Thread........................806
16.3 Pipe the output of a thread to the input of other threadsTag(s): Thread......................808
16.4 Wait the for the completion of a threadTag(s): Thread................................................810
16.5 Control a thread from outsideTag(s): Thread...............................................................811
16.6 Create a Timer objectTag(s): Thread...........................................................................812
16.7 Pause the executionTag(s): Thread.............................................................................813
16.8 Execute a method at a specified time intervalTag(s): Thread......................................814
16.9 Execute a process at regular intervalTag(s): Thread...................................................815
16.10 Handle concurrent read/writeTag(s): Thread.............................................................816
16.11 Communicate between threads using a QueueTag(s): Thread.................................818
16.12 Get a unique identifierTag(s): String/Number Thread Varia......................................823
16.13 Using java.rmi.dgc.VMID...........................................................................................823
16.14 Using java.util.UUID...................................................................................................823
16.15 Using Apache commons............................................................................................824
16.16 Using java.util.concurrent.AtomicLong.......................................................................824
17 Varia...........................................................................................................................................825
17.1 javavaria....................................................................................................................825
17.2 Use System time to generate unique IDTag(s): Date and Time Date and Time
Varia.....................................................................................................................................825
17.3 Get a unique identifierTag(s): String/Number Thread Varia........................................825
17.4 Using java.rmi.dgc.VMID.............................................................................................825
17.5 Using java.util.UUID.....................................................................................................826
17.6 Using Apache commons..............................................................................................826
17.7 Using java.util.concurrent.AtomicLong.........................................................................826
17.8 Get the hard disk serial number or Motherboard serial numberTag(s): Varia..............827
17.9 Motherboard serial number..........................................................................................827
17.10 Hard disk serial number.............................................................................................828
17.11 Sort an arrayTag(s): Language Varia........................................................................829
17.12 Sort a String arrayTag(s): Internationalization Varia..................................................831
17.13 Do a selection sortTag(s): Varia................................................................................833
17.14 Validate a Social Security Number (canadian)Tag(s): Varia......................................834
17.15 Validate a Credit Card NumberTag(s): Varia.............................................................835
17.16 Obtain from where a Class is loadedTag(s): Language Varia...................................838
17.17 Get the class name with or without the packageTag(s): Varia...................................839
17.18 See the generated bytecodeTag(s): Varia.................................................................841
17.19 Self replicating programsTag(s): Varia......................................................................843
17.20 A curiosity (strange Java code)Tag(s): Varia.............................................................844
17.21 Classic bugsTag(s): Varia..........................................................................................846
17.22 Number of the beast!Tag(s): Varia.............................................................................846
17.23 Use Java scripting engine (JDK 1.6)Tag(s): Varia.....................................................847
17.24 Pass or retrieve values from a scripting engine (jdk1.6)Tag(s): Varia.......................848
17.25 Preventing multiple instances of an applicationTag(s): Varia....................................850
17.26 Trap JVM shutdownTag(s): Varia..............................................................................854
17.27 Minimize all programs on Windows to show the DesktopTag(s): Varia.....................854
17.28 Display a progress indicator in the consoleTag(s): Varia...........................................855
Real's [email protected]
18 XML............................................................................................................................................857
18.1 javaxml.......................................................................................................................857
18.2 Read meTag(s): XML...................................................................................................857
18.3 Display XML using plain HTMLTag(s): XML................................................................858
18.4 Transform XML into HTML using XSLTTag(s): XML...................................................859
18.5 Parse using SAX or DOMTag(s): XML........................................................................860
18.6 Parse an XML stringTag(s): XML.................................................................................863
18.7 Create an XML document with DOMTag(s): XML.......................................................864
18.8 Attach a stylesheet to an XML fileTag(s): XML............................................................865
18.9 Create an XML file and attach an XSLTag(s): XML XML............................................866
18.10 Nicely display WEB.XML informationsTag(s): Servlet/JSP XML Jaguar/EAServer...869
18.11 Serialize an object using XMLTag(s): XML................................................................871
18.12 Convert a flat file to XML (SAX)Tag(s): XML.............................................................872
18.13 Convert a flat file to XML (DOM)Tag(s): XML............................................................874
18.14 Convert a ResultSet to XMLTag(s): JDBC XML........................................................876
18.15 Parse with XPathTag(s): XML....................................................................................878
18.16 Strip extra spaces in a XML stringTag(s): XML.........................................................882
18.17 Create an XML file and attach an XSLTag(s): XML XML..........................................882
18.18 Use XML with PropertiesTag(s): Language XML.......................................................885
18.19 Change a particular node in XMLTag(s): XML...........................................................886
18.20 Validate XML using a DTDTag(s): XML.....................................................................887
18.21 Validate XML using a XSD (XML Schema)Tag(s): XML............................................891
18.22 Sanitize XML String Tag(s): XML...............................................................................896
18.23 Produce HTML entities when using XSLTTag(s): XML.............................................897
18.24 Create a RSS feed (part 1)Tag(s): XML....................................................................897
18.24.1 RSS 2.0.............................................................................................................898
18.24.2 Atom..................................................................................................................899
18.24.3 Creating a feed..................................................................................................900
18.24.4 Creating a feed with Apache Commons Digester.............................................900
18.24.5 Creating a feed with Rome................................................................................901
18.25 Creating an RSS Feed (part 2)Tag(s): XML..............................................................903
18.26 Parse a RSS XML fileTag(s): XML............................................................................908
18.26.1 Parsing a feed with Apache Commons Digester...............................................909
18.26.2 Parsing a feed with ROME................................................................................910
18.26.3 RSSUTIL.TLD.................................................................................................910
18.27 Add a Live bookmarkTag(s): XML.............................................................................911
18.28 Validate a RSS feedTag(s): XML...............................................................................911
18.29 Attach a CSS to RSS feedTag(s): XML.....................................................................911
19 DEPRECATED...........................................................................................................................914
19.1 javadeprecated..........................................................................................................914
19.2 * Read me * (this howto is deprecated)Tag(s): DEPRECATED.................................914
19.3 Keep the console open after execution (this howto is deprecated)Tag(s):
DEPRECATED...................................................................................................................914
19.4 Read the Registry (this howto is deprecated)Tag(s): DEPRECATED.........................915
19.5 Call a Win API (this howto is deprecated)Tag(s): DEPRECATED...............................916
19.6 Display a BMP image (this howto is deprecated)Tag(s): DEPRECATED...................917
19.7 Play a WAV audio file (this howto is deprecated)Tag(s): DEPRECATED...................918
19.8 Detect if the MS JVM is used (this howto is deprecated)Tag(s): DEPRECATED........919
19.9 Get the latest MS JVM (this howto is deprecated)Tag(s): DEPRECATED..................919
Real's [email protected]
19 DEPRECATED
19.10 Uninstalling the MS JVM (this howto is deprecated)Tag(s): DEPRECATED.............919
19.11 Wrap a Java class in a COM object (this howto is deprecated)Tag(s):
DEPRECATED...................................................................................................................920
19.12 Sign an applet (this howto is deprecated)Tag(s): DEPRECATED.............................921
19.13 Bypass the need for a certificate (this howto is deprecated)Tag(s):
DEPRECATED...................................................................................................................922
19.14 Start an executable on the client (this howto is deprecated)Tag(s):
DEPRECATED...................................................................................................................923
19.15 Get rid of the message "Warning unsigned applet window" (this howto is
deprecated)Tag(s): DEPRECATED....................................................................................924
19.16 Read/write a local file from an Applet (this howto is deprecated)Tag(s):
DEPRECATED...................................................................................................................924
19.17 Write "otherbrowserfriendly" code when using the Netscape Capabilities
package (this howto is deprecated)Tag(s): DEPRECATED...............................................926
19.18 Disable the JIT compiler in Netscape or IE (this howto is deprecated)Tag(s):
DEPRECATED...................................................................................................................926
19.19 Start automatically JAVA when opening Netscape (this howto is deprecated)
Tag(s): DEPRECATED........................................................................................................927
19.20 Use Netscape Java Console hidden commands (this howto is deprecated)
Tag(s): DEPRECATED........................................................................................................927
19.21 Avoid the Netscape "Couldn't connect to '' with origin from
'localclasspathclasses'" message. (this howto is deprecated)Tag(s): DEPRECATED...928
19.22 Get the client IP address (deprecated)Tag(s): DEPRECATED.................................928
19.23 Detect the browser/JVM type (deprecated)Tag(s): Environment DEPRECATED.....929
19.24 Post a message on a newsserver using NNTP protocol (this howto is
deprecated)Tag(s): DEPRECATED....................................................................................931
19.25 Read messages from a newsserver (this howto is deprecated)Tag(s):
DEPRECATED...................................................................................................................932
19.26 Get a list of headers from a newsgroup (this howto is deprecated)Tag(s):
DEPRECATED...................................................................................................................933
19.27 Get a list of all available newsgroup from a newsserver (this howto is
deprecated)Tag(s): DEPRECATED....................................................................................934
19.28 Detect if Swing is installed (this howto is deprecated)Tag(s): DEPRECATED..........935
19.29 Make Swing always available from Netscape (this howto is deprecated)Tag(s):
DEPRECATED...................................................................................................................935
19.30 Send email with attachment (DEPRECATED)Tag(s): DEPRECATED......................936
20 String/Number...........................................................................................................................937
20.1 javastringnumber.......................................................................................................937
20.2 * Read me *Tag(s): Language String/Number.............................................................937
20.3 Convert from type X to type YTag(s): String/Number String/Number..........................938
20.4 Strip certain characters from a StringTag(s): String/Number.......................................940
20.5 Replace/remove character in a StringTag(s): String/Number......................................941
20.6 Replace every occurences of a string within a stringTag(s): String/Number...............943
20.7 "Tokenize" a stringTag(s): String/Number...................................................................944
20.8 Split a string using String.split()Tag(s): String/Number................................................949
20.9 Optimize String operationsTag(s): String/Number.......................................................952
20.9.1 StringBuilder (JDK1.5)........................................................................................954
20.10 Remove spaces from a stringTag(s): String/Number.................................................954
Real's [email protected]
20 String/Number
20.11 Test if a String starts with a digit or uppercase letterTag(s): String/Number.............955
20.12 Get InputStream from a StringTag(s): String/Number...............................................956
20.13 Easy String paddingTag(s): String/Number...............................................................956
20.14 Replace \r\n with the <br> tagTag(s): String/Number................................................958
20.15 Unaccent lettersTag(s): Internationalization String/Number......................................958
20.15.1 Using java.text.Normalizer................................................................................959
20.15.2 Using String.replaceAll()...................................................................................959
20.15.3 The String.indexOf()..........................................................................................960
20.16 Apply a mask to StringTag(s): String/Number...........................................................962
20.17 Format a String (JDK1.5)Tag(s): String/Number.......................................................963
20.18 Replace a "\" by "\\"Tag(s): String/Number................................................................964
20.19 Substitute tokens in a StringTag(s): String/Number...................................................965
20.20 Compare accentuated lettersTag(s): Internationalization String/Number..................965
20.21 Create a String with fixed length and filled with a specific characterTag(s):
String/Number.....................................................................................................................967
20.22 Unquote a StringTag(s): String/Number....................................................................967
20.23 Escape HTML special characters from a StringTag(s): String/Number.....................968
20.24 Unescape HTML special characters from a StringTag(s): String/Number.................970
20.25 Using HashMap.........................................................................................................970
20.26 Using Array................................................................................................................972
20.27 Detect nonASCII character in a StringTag(s): Internationalization
String/Number......................................................................................................................974
20.28 Remove HTML tags from a file to extract only the TEXTTag(s): IO
String/Number Networking...................................................................................................975
20.29 Using regular expression...........................................................................................975
20.30 Using javax.swing.text.html.HTMLEditorKit...............................................................976
20.31 Using an HTML parser...............................................................................................977
20.32 Using Apache Tika.....................................................................................................977
20.33 Extract links from an HTML pageTag(s): String/Number Networking........................978
20.34 Using javax.swing.text.html.HTMLEditorKit...............................................................978
20.35 Using an HTML parser...............................................................................................979
20.36 Convert a byte array to a Hex stringTag(s): String/Number.......................................980
20.37 Apply proper uppercase and lowercase on a StringTag(s): String/Number...............981
20.38 Encode/Decode to/from Base64Tag(s): String/Number Networking.........................982
20.39 Using javax.mail.internet.MimeUtility.........................................................................982
20.40 Using Apache Commons Codec................................................................................983
20.41 MiGBase64................................................................................................................984
20.42 Justify a string with wordwrapTag(s): String/Number................................................984
20.43 Shorten a long pathTag(s): IO String/Number...........................................................985
20.44 Ellipse a StringTag(s): String/Number.......................................................................989
20.45 Display Ascii Banner Tag(s): String...........................................................................990
20.46 Convert from type X to type YTag(s): String/Number String/Number........................991
20.47 Type conversion (JDK1.5)Tag(s): String/Number......................................................993
20.48 Round a doubleTag(s): String/Number......................................................................994
20.49 Display numbers with commasTag(s): String/Number...............................................995
20.50 Display numbers in scientific notationTag(s): String/Number....................................996
20.51 Display numbers with leading zeroesTag(s): String/Number.....................................997
20.52 Get a random numberTag(s): String/Number............................................................999
20.53 Convert an UNSIGNED byte to a JAVA typeTag(s): String/Number.........................999
Real's [email protected]
20 String/Number
20.54 Deal with bigendian and littleendian orderTag(s): String/Number.......................1000
20.55 Pass an integer by referenceTag(s): String/Number...............................................1001
20.56 Pass floats as string literals to a methodTag(s): String/Number..............................1001
20.57 Get random numbersTag(s): String/Number...........................................................1002
20.58 Convert number into wordsTag(s): String/Number..................................................1002
20.59 Arithmetic with doubleTag(s): String/Number..........................................................1011
20.60 Detect even/odd numberTag(s): String/Number......................................................1011
20.61 Convert bytes to megabytesTag(s): String/Number.................................................1012
20.62 Validate a numberTag(s): String/Number................................................................1012
20.63 Get a unique identifierTag(s): String/Number Thread Varia....................................1013
20.64 Using java.rmi.dgc.VMID.........................................................................................1013
20.65 Using java.util.UUID.................................................................................................1014
20.66 Using Apache commons..........................................................................................1014
20.67 Using java.util.concurrent.AtomicLong.....................................................................1014
20.68 Validate/Convert a number using the current Locale()Tag(s):
Internationalization String/Number....................................................................................1015
20.69 Convert a fraction to a DoubleTag(s): String/Number..............................................1016
21 Open Source...........................................................................................................................1018
21.1 javaos......................................................................................................................1018
21.2 Call Windows API (Open source solution)Tag(s): JNI Open Source.........................1018
21.3 Call COM objectTag(s): Open Source.......................................................................1018
21.4 com4j.........................................................................................................................1018
21.5 jinterop.....................................................................................................................1019
21.6 jxchange..................................................................................................................1019
21.7 Run JAVA as a Windows serviceTag(s): Environment Open Source........................1019
21.8 Create entityrelation diagramTag(s): Open Source Open Source...........................1020
21.9 Java Remote desktop toolTag(s): Open Source........................................................1020
21.10 Create entityrelation diagramTag(s): Open Source Open Source.........................1021
21.11 Launch a java program as a Windows EXE fileTag(s): Open Source.....................1021
21.12 WinRun4J................................................................................................................1021
21.13 JSmooth...................................................................................................................1022
21.14 Launch4J.................................................................................................................1022
21.15 Handle CSV fileTag(s): IO Open Source.................................................................1022
21.16 com.Ostermiller.util CSV Utils..................................................................................1023
21.17 opencsv....................................................................................................................1023
21.18 ServingXML.............................................................................................................1023
21.19 Super CSV...............................................................................................................1023
21.20 csvreader.................................................................................................................1023
21.21 CSVFile....................................................................................................................1023
21.22 FlatPack...................................................................................................................1023
21.23 CSVJDBC................................................................................................................1023
21.24 FFP..........................................................................................................................1023
21.25 Handle Excel filesTag(s): IO JDBC Open Source....................................................1024
21.26 JDBCODBC Excel driver.......................................................................................1024
21.27 JExcel......................................................................................................................1024
21.28 POI...........................................................................................................................1025
21.29 JXLS........................................................................................................................1025
21.30 xlSQL.......................................................................................................................1026
Real's [email protected]
21 Open Source
21.31 JCOM.......................................................................................................................1027
21.32 OpenXLS Java Spreadsheet SDK...........................................................................1028
21.33 Browse a Queue (JMS/MQ)Tag(s): Open Source...................................................1030
21.34 Convert a .class to .java file (decompiler)Tag(s): Open Source..............................1030
21.35 Jad...........................................................................................................................1030
21.36 JadClipse.................................................................................................................1031
21.37 JD Java decompiler..............................................................................................1031
21.38 JarPlug.....................................................................................................................1031
21.39 Deploy an application as only 1 jarTag(s): Open Source.........................................1032
21.40 OneJar...................................................................................................................1032
21.41 Fat Jar......................................................................................................................1032
21.42 Read an Outlook MSG fileTag(s): Networking Open Source...................................1032
21.43 Apache POI HSMF..................................................................................................1033
21.44 msgparser................................................................................................................1035
21.45 jmbox.......................................................................................................................1035
21.46 File/directory polling to detect changeTag(s): IO Open Source...............................1036
21.47 jpoller (directory poller)............................................................................................1036
21.48 JNotify......................................................................................................................1036
21.49 Java Native Access (JNA).......................................................................................1036
21.50 Call native methods in a DLL from Java (NativeCall)..............................................1036
21.51 Java 7......................................................................................................................1037
21.52 The simple (and naive!) approach...........................................................................1037
21.53 Clear the console and control attributesTag(s): IO Open Source............................1037
21.54 Jansi.........................................................................................................................1037
21.55 JCurses....................................................................................................................1038
21.56 Disable Checkstyle from code Tag(s): OpenSource................................................1039
21.57 Create or process a PDF fileTag(s): IO Open Source.............................................1040
21.58 Create a PDFTag(s): IO Open Source.....................................................................1042
21.59 iText.........................................................................................................................1042
21.60 Split a PDF file (using iText)Tag(s): IO Open Source..............................................1043
21.61 Concatenate PDF files (using iText)Tag(s): IO Open Source..................................1045
21.62 Convert TIF to PDFTag(s): AWT IO IO Open Source..............................................1046
21.63 Convert HTML to PDF using iTextTag(s): IO Open Source.....................................1048
21.64 Convert HTML to PDF using YAHP Tag(s): IO OpenSource...................................1050
21.65 Convert a png/jpg/gif file to PDF using iTextTag(s): IO Open Source.....................1052
21.66 Print a PDFTag(s): IO Open Source........................................................................1053
21.67 Extract text from a PDF (with Apache Tika) Tag(s): IO OpenSource......................1053
21.68 Detect and remove blank page in pdf (iText)Tag(s): PDF.......................................1054
1 Applet
1.1 javaapplet
or
getAppletContext().showDocument
(new URL("http://www.whatever.com"),"HTML FRAME ID");
If "HTML frame ID" do not exists then a new browser window will be opened. The following "HTML
frame ID" have special meanings :
"_self"
"_parent"
"_top"
"_blank"
current frame
parent frame
base frame
new window
For example, we want to display lowres.html page if resolution is 640x480 else the hires.html is
used.
import java.applet.*;
import java.awt.*;
import java.net.*;
public class whatres extends Applet {
public void init() {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
if (dim.width==640 &dim.height==480) {
try {
getAppletContext().showDocument
(new URL(getCodeBase()+"lowres.html"),"_top");
}
catch (Exception ex) {}
}
else {
try {
getAppletContext().showDocument
(new URL(getCodeBase()+"hires.html"),"_top");
}
catch (Exception ex) {}
}
1 Applet
}
}
NOTE: The previous example works only so long as the document was retrieved without specifying an actual document name, since
getDocumentBase() returns the full URL including the name of the document. If the document name was specified, you should try something
like this or specify the complete URL (thanks to Rob Judd): :
try {
String docString = getDocumentBase().toString();
if (docString.endsWith("/")) {
getAppletContext().showDocument
(new URL(getDocumentBase()+"lowres.html"), "_top");
}
else {
getAppletContext().showDocument
(new URL(getDocumentBase()+"/../lowres.html"), "_top");
}
}
catch (Exception e) {}
Another example, type a new URL in a textfield, and press a button to go to that page.
import
import
import
import
java.applet.*;
java.awt.*;
java.awt.event.*;
java.net.*;
Try it here.
1 Applet
Try it here
1.3 Determine the host from where the Applet is loadedTag(s): Applet
int width;
public void init(){
message = getParameter("message");
if(message == null)
message = " Isn't scrolling text in the status line annoying? ";
String ws = getParameter("width");
if(ws == null) {
width = 36;
}
else{
width = Integer.valueOf(ws).intValue();
}
if(width < 5 || width > 180) {
width = 36;
}
buffer = new StringBuffer(width);
buffer.setLength(width);
at = 0;
if(message.length() < width) {
char buf[] = new char[width];
for(int i = 0; i < width; ++i) {
buf[i] = ' ';
}
message.getChars
(0, message.length(), buf, (width message.length()) / 2);
message = new String(buf);
}
}
public void start(){
thread = new Thread(this);
thread.start();
}
public void stop(){
thread.stop();
}
public void scroll(){
int ml = message.length();
int k = at;
for(int i = 0; i < width; ++i, ++k){
if(k >= ml) {
k = 0;
}
buffer.setCharAt(i, message.charAt(k));
}
getAppletContext().showStatus(buffer.toString());
at++;
if(at >= ml) {
at = 0;
}
}
public void run(){
while(true){
scroll();
try{
Thread.sleep(25); // wait 25 ms
1.3 Determine the host from where the Applet is loadedTag(s): Applet
}
catch(InterruptedException e){
break;
}
}
}
}
Try it here.
Try it here.
It's not easy to call Google from an Applet but you can do it in application as seen in this HowTo.
java.applet.*;
java.awt.*;
java.util.*;
java.text.*;
SimpleDateFormat formatter;
String previousDateText = "";
String dateText;
MyPanel(String df) {
super();
formatter = new SimpleDateFormat(df);
validate();
setBackground(new Color(0).black);
setForeground(new Color(0).yellow);
b = this.getBackground();
f = this.getForeground();
mct = new MyClockThread(this);
mct.start();
}
public Dimension getPreferredSize() {
return new Dimension
(this.getFontMetrics(this.getFont()).stringWidth(getNow()) + 25, 30);
}
public void paint(Graphics g) {
if (g != null) {
g.setColor(b);
g.drawString(previousDateText,10,15);
g.setColor(f);
dateText = getNow();
g.drawString(dateText,10,15);
previousDateText = dateText;
}
}
public String getNow() {
return formatter.format(new Date());
}
}
class MyClockThread extends Thread {
MyPanel mp;
public MyClockThread(MyPanel a) {
mp = a;
}
public void run() {
while (true) {
try {
mp.repaint();
this.sleep(1000);
}
catch(InterruptedException e) { }
}
}
}
<HTML><HEAD></HEAD><BODY>
<APPLET CODE="MyClock.class"
HEIGHT=25 WIDTH=200>
<PARAM NAME="format" VALUE="yyyyMMdd hh:mm:ss">
</APPLET><P>
<APPLET CODE="MyClock.class"
HEIGHT=25 WIDTH=200>
<PARAM NAME="format" VALUE="h:mm a">
</APPLET><P>
<APPLET CODE="MyClock.class"
HEIGHT=25 WIDTH=200>
<PARAM NAME="format" VALUE="yyyy.MMMMM.dd GGG hh:mm aaa">
</APPLET><P>
<APPLET CODE="MyClock.class"
HEIGHT=25 WIDTH=200>
<PARAM NAME="format" VALUE="H:mm:ss:SSS">
</APPLET><P>
/BODY/HTML
Try it here.
1.7 Have Applets on the same page communicate with each otherTag(s): Applet
[Applet2_0022.java]
import java.awt.*;
public class Applet2_0022 extends java.applet.Applet {
TextArea textBox;
public void init() {
setLayout(new FlowLayout());
textBox = new TextArea( 5, 40 );
add( textBox );
}
public void append( String msg ) {
textBox.append( msg );
textBox.append( "\n" );
}
}
[HTML]
<HTML><HEAD></HEAD><BODY>
<APPLET CODE="Applet1_0022.class"
NAME="applet1"
HEIGHT=200 WIDTH=150>
</APPLET>
<APPLET CODE="Applet2_0022.class"
NAME="applet2"
HEIGHT=200 WIDTH=400>
</APPLET>
</BODY></HEAD>
Try it here.
1.8 Have Applets on different frames communicates with each otherTag(s): Applet
Try it here.
Check this DDJ article for a more elaborate way to implement this principle.
There is one way to do it by using a Javascript function as a bridge, take a look at this Howto.
1.8 Have Applets on different frames communicates with each otherTag(s): Applet
FirstAppletJ.java
import
import
import
import
java.applet.*;
java.awt.*;
java.awt.event.*;
java.net.*;
SecondAppletJ.html
<HTML><HEAD></HEAD><BODY>
<APPLET CODE="SecondAppletJ.class"
HEIGHT=100
WIDTH=400>
/APPLET/BODY/HTML
1.9 Send a message from an Applet to another Applet on a different pageTag(s): Applet
SecondApplet.java
import java.applet.*;
import java.awt.*;
import java.net.*;
public class
public void
Label l =
add (l);
TextField
add(tf);
tf.setText(theMessage);
}
}
You can try it here! NOTE : On IE, you must be connected to the Internet
1.9 Send a message from an Applet to another Applet on a different pageTag(s): Applet
System.out.println( e );
}
validate();
}
public void start(){
appletThread = new Thread(this);
appletThread.start();
}
public void stop() {
appletThread.stop();
appletThread = null;
}
public void appletResize( int width, int height ){
resize( width, height );
}
}
try it here.
will print the current user. You can't use this technique to secure your application since it is very to
spoof.
1.11 Get the user nameTag(s): Applet Security
In Applet there is no way unless you ask for it or use a signed applet. If you have access to a
serverside, something like an ASP page can be used to detect the current NT user name if the
client and the server are configured correcty (SSO).
See this related HowTo for a JSP hack!
java.applet.Applet;
java.io.UnsupportedEncodingException;
java.util.HashMap;
java.util.Map;
@SuppressWarnings("serial")
public class AppletUrlParams extends Applet {
HashMap<String,String> parmsMap ;
public void init() {
/*
dump to the console the URL, the search and search values
the URL http://myserver.com/mypage.html?value1=x&value2=y&value3=z
the search value1=x&value2=y&value3=z
the values value1=x
value2=y
value3=z
then the values are stored in a map for easy reference.
ex. String name = parmsMap.get("name")
*/
try {
doit();
dumpMap(parmsMap);
Test it here.
The result in the Java console should be :
key : firsparam value : Hello
key : secondparam value : World
key : thirdparam value : Hello World
To be able to use the same class as an application, we simply extend a Panel instead of an Applet,
put it in Frame and call the init() method.
import java.awt.*;
public class UnderlineText extends Panel{
String s = "Java Howto";
int x=20;
int y=50;
public static void main(String[] args) {
Frame f = new Frame();
f.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
};
});
UnderlineText ut = new UnderlineText();
ut.setSize(100,100); // same size as defined in the HTML APPLET
f.add(ut);
f.pack();
ut.init();
f.setSize(100,100 + 20); // add 20, seems enough for the Frame title,
f.show();
}
public void init() {
add(new Button("Real's"));
}
public void paint(Graphics g) {
g.drawString(s, x,y);
g.drawLine(x , y+2 , x+getFontMetrics(getFont()).stringWidth(s) , y+2 );
}
}
CROSSHAIR_CURSOR, DEFAULT_CURSOR,
E_RESIZE_CURSOR, HAND_CURSOR
MOVE_CURSOR, N_RESIZE_CURSOR,
NE_RESIZE_CURSOR, NW_RESIZE_CURSOR;
S_RESIZE_CURSOR,SE_RESIZE_CURSOR,
SW_RESIZE_CURSOR, TEXT_CURSOR,
W_RESIZE_CURSOR, WAIT_CURSOR
[JDK1.1]
// setCursor is supported at the component level
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
TILE BACKGROUND
in the HTML use :
PARAM NAME="bgImage" VALUE="images/myImage.jpg"
in the APPLET tag
/HMTL
Try it here.
1.16.1 Solution #1
The workaround for an APPLET (to bypass the manual activation) is to generate in Javascript the
APPLET tag but you need to generate it from an outside JS page!
<html>
<body leftmargin=0 topmargin=0 scroll=no>
<script src="myapplet.js"></script>
</body>
</html>
NOTE If you uncheck the Disable Script Debugging (Internet Explorer) option in the Advanced Tab
of the Internet Options Control Panel, controls will still require activation.
NOTE: While inactive controls do not respond to direct user interaction; they do respond to script
commands.
Try a page with the regular APPLET tag here.
And now the same APPLET but with an external JS file here.
Both on the same page (same Applet), here!
The workaround suggested by Microsoft is fine with static APPLET tag but if your APPLET tag
needs to be generated by a JSP ou Servlet (to adjust the PARAM parameters for example) then
you're out of luck because the APPLET declaration is in a JS file which is a static file.
1.16.2 Solution #2
As seen in this article, all you need is to change the content from an outside file. So you need a
generic JS function to rewrite the APPLET tag with the original and that's it!
The main HTML (in BODY tag we call our "rewrite" function) :
<HTML><HEAD></HEAD>
<BODY onload="rewriteApplet();">
<p>This example "rewrite" the applet tag from an external JS.
This way you can generate the Applet tag from a JSP like before.
<P>
<script language="Javascript1.2" src="./rewriteapplet.js">
</script>
<APPLET CODE="TextFieldWithLimitApplet.class"
HEIGHT=100
WIDTH=300>
</APPLET>
</BODY></HTML>
Try it here!
The same principle can be used for the OBJECT tag.
This site http://www.ediy.co.nz/internetexplorerflashappletactivationfixxidc19237.html offers
a really small JS script (only 292 bytes long) to handle the situation.
IMPORTANT NOTES :
AFAIK, this trick does not work from a FRAME!
If you have PARAM tags associated with the applet then they will be replaced by two strange
PARAMS (_CX and _CY)! So beware... It looks that this behaviour has something to do with the
1.16.2 Solution #2
fact that the Java plugin is an ActiveX. PreXP SP2 installation are not supposed to do that kind
of substitution (not verified!).
For simple applet with no param, this is an interesting generic solution.
1.16.3 Solution #3
This solution is a little bit ugly but there is no better solution when you have dynamic APPLET
PARAM generated on the serverside.
The requirement is to write only the APPLET tag from an outside JS file, the PARAMS can be
handled by the main page like before! The trick is to have 2 external JS function, one to write the
<APPLET> tag (and the static PARAM if any) and a second function to write the </APPLET>. The
enclosed dynamic PARAM parameters are generated by the JSP (ASP page).
[rewriteapplet.js]
function writeHeader(urlApplet) {
document.write
('<applet codebase="' + urlApplet + '" code="myApplet.class"')
document.write
(' width="100%" height="98%" hspace="0" vspace="0" align="middle" >')
document.write
('
<PARAM NAME="printdialog" VALUE="false">')
}
function writeFooter() {
document.write('</applet>')
}
1.16.3 Solution #3
<script>
writeFooter();
/script
Next, on the Advanced tab, select Java Console > Display the console.
The next time when loading an applet, the java console will display with a full trace.
The log is stored in a file. For Windows, the file is C:\Documents and
Settings\[YourAccount]\Application Data\Sun\Java\Deployment\log\plugin[version].log/trace
1.18 See the Java Console Window Log (Java plugin)Tag(s): Applet Environment
.. or you can insert your Applet into an invisible frame. See this HowTo for an example.
or you unselect the new generation Java plugin option in the Java Panel.
java.applet.*;
java.awt.event.*;
java.awt.*;
netscape.javascript.*;
Don't forget the MAYSCRIPT parameter in the APPLET tag, it's required since the Applet is using
the JSObject to interact with the Javascript.
<html>
<head>
<script>
function getUserAgent() {
return navigator.userAgent;
}
</script>
</head><body>
<applet code="GetUserAgent.class" MAYSCRIPT height=100 width=500></Applet>
</body>
</html>
Try it here
You need to parse the returned value to detect browser type. Look at this utility,
http://code.google.com/p/useragentutils/ or at this code :
http://nerds.palmdrive.net/useragent/code.html to get the idea.
The getYear() method returns the number of years elapsed after the year 1900. So for year 2000,
mydate.getYear() will return 100. So 100 + 1900 = 2000.
2.3 Get the current Date and TimeTag(s): Date and Time
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java0106.html
import java.util.Calendar;
import java.text.SimpleDateFormat;
public class DateUtils {
public static final String DATE_FORMAT_NOW = "yyyyMMdd HH:mm:ss";
public static String now() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime());
}
public static void main(String arg[]) {
System.out.println("Now : " + DateUtils.now());
}
}
Another way would be to compute the julian day number of both dates and then do the substraction.
See this HowTo. Thanks to P. Hill for the tip.
The package java.util.concurrent.TimeUnit; provides a class to make conversion between
milliseconds and days easier.
import java.util.*;
import java.util.concurrent.TimeUnit;
public class DateUtils {
private DateUtils() { }
public static long getDifference(Calendar a, Calendar b, TimeUnit units) {
return
units.convert(b.getTimeInMillis() a.getTimeInMillis(), TimeUnit.MILLISECONDS);
}
/*
testing
*/
public static void main(String[] args) {
java.text.SimpleDateFormat sdf =
new java.text.SimpleDateFormat("yyyyMMdd");
Calendar augustfirst2008 = Calendar.getInstance();
augustfirst2008.set(2008, Calendar.AUGUST, 1); // 20080801
Calendar today = Calendar.getInstance();
// today
System.out.println
(getDifference(augustfirst2008,today,TimeUnit.DAYS)
+ " day(s) between "
+ sdf.format(augustfirst2008.getTime()) + " and "
+ sdf.format(today.getTime()));
}
/*
* output :
*
921 day(s) between 20080801 and 20110208
*/
}
Actually, the Calendar class provides a method to that very simply. For a given Calendar or
GregorianCalendar object :
calObject.getActualMaximum(calobject.DAY_OF_MONTH)
In the Java API documentation there is a note saying that The version (getActualMaximum()) of this
function on Calendar uses an iterative algorithm to determine the actual maximum value for the
field. There is almost always a more efficient way to accomplish this (in most cases, you can simply
return getMaximum()). GregorianCalendar overrides this function with a more efficient
implementation. So it looks like it's a lot more efficient to call getActualMaximum from a
GregorianCalendar object than a Calendar object. (Thanks to P. Harris for the tip)
gregCalObject.getActualMaximum(gregCalObject.DAY_OF_MONTH)
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(" 19001213 valid ? "
+ DateUtils.isValidDateStr("19001213"));
// "199012/13" throws a ParseException
System.out.println(" 190012/13 valid ? "
+ DateUtils.isValidDateStr("190012/13"));
// "19901312" throws a IllegalArgumentException
System.out.println(" 19001312 valid ? "
+ DateUtils.isValidDateStr("19001312"));
/*
* output :
* 19001213 valid ? true
* 190012/13 valid ? false
* 19001312 valid ? false
*/
}
}
Using SimpleDateFormat
package com.rgagnon.howto;
import java.text.*;
public class DateUtils {
public static boolean isValidDateStr(String date, String format) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setLenient(false);
sdf.parse(date);
}
catch (ParseException e) {
return false;
}
catch (IllegalArgumentException e) {
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(" 19001213 valid ? "
+ DateUtils.isValidDateStr("19001213","yyyyMMdd"));
// "199012/13" throws a ParseException
System.out.println(" 190012/13 valid ? "
+ DateUtils.isValidDateStr("190012/13","yyyyMMdd"));
// "19901312" throws a IllegalArgumentException
System.out.println(" 19001312 valid ? "
+ DateUtils.isValidDateStr("19001312","yyyyMMdd"));
/*
* output :
* 19001213 valid ? true
* 190012/13 valid ? false
* 19001312 valid ? false
*/
}
+ sdf.format(c1.getTime()));
c1.set(1999, 0 , 20); // 1999 jan 20
System.out.println("Date is : " + sdf.format(c1.getTime()));
c1.add(Calendar.MONTH, 1); // substract 1 month
System.out.println
("Date minus 1 month : "
+ sdf.format(c1.getTime()));
/*
* output :
* Date is : 19990120
* Date roll down 1 month : 19991220
* Date is : 19990120
* Date minus 1 month : 19981220
*/
}
}
if (c1.equals(c2)) {
System.out.print(" same as ");
}
System.out.println(sdf.format(c2.getTime()));
}
}
java.util.Date;
java.util.Locale;
java.util.Calendar;
java.text.SimpleDateFormat;
2.13 Use System time to generate unique IDTag(s): Date and Time Date and Time Varia
e.printStackTrace();
return "";
}
}
}
An alternate way :
import
import
import
import
java.util.Calendar;
java.text.SimpleDateFormat;
java.text.DateFormat;
java.text.DateFormatSymbols;
ja = (int) julian
if (ja>= JGREG) {
jalpha = (int) (((ja 1867216) 0.25) / 36524.25);
ja = ja + 1 + jalpha jalpha / 4;
}
jb = ja + 1524;
jc = (int) (6680.0 + ((jb 2439870) 122.1) / 365.25);
jd = 365 * jc + jc / 4;
je = (int) ((jb jd) / 30.6001);
day = jb jd (int) (30.6001 * je);
month = je 1;
if (month > 12) month = month 12;
year = jc 4715;
if (month > 2) year;
if (year <= 0) year;
return new int[] {year, month, day};
}
public static void main(String args[]) {
// FIRST TEST reference point
System.out.println("Julian date for May 23, 1968 : "
+ toJulian( new int[] {1968, 5, 23 } ));
// output : 2440000
int results[] = fromJulian(toJulian(new int[] {1968, 5, 23 }));
System.out.println
("... back to calendar : " + results[0] + " "
+ results[1] + " " + results[2]);
// SECOND TEST today
Calendar today = Calendar.getInstance();
double todayJulian = toJulian
(new int[]{today.get(Calendar.YEAR), today.get(Calendar.MONTH)+1,
today.get(Calendar.DATE)});
System.out.println("Julian date for today : " + todayJulian);
results = fromJulian(todayJulian);
System.out.println
("... back to calendar : " + results[0] + " " + results[1]
+ " " + results[2]);
// THIRD TEST
double date1 = toJulian(new int[]{2005,1,1});
double date2 = toJulian(new int[]{2005,1,31});
System.out.println("Between 20050101 and 20050131 : "
+ (date2 date1) + " days");
/*
expected output :
Julian date for May 23, 1968 : 2440000.0
... back to calendar 1968 5 23
Julian date for today : 2453487.0
... back to calendar 2005 4 26
Between 20050101 and 20050131 : 30.0 days
*/
}
}
There is a lot of variation around the idea of a "Julian date". You can have the Modified Julian Date
(JD) or the Truncated Julian Date (TJD). The main difference is the starting for counting the days.
Before Y2K, many applications (especially mainframe systems) were storing dates in a format
called "the Julian format". This format is a 5 digit number, consisting of a 2 digit year and a 3 digit
dayofyear number. For example, 17July1998 is stored as 98221, since 17July is the 221th
day of the year. This format is not really useful since Y2K! The main reason for using the 5digits
Julian date was to save disk space and still have a format easy to use to handle. dates.
A variation of this idea is to used the first four digits for the year and 3 digits for dayofyear,
17July1998 will be represented by 1998221.
This is a very simple format which can be manipulated easily from Java.
import
import
import
import
java.util.Calendar;
java.util.Date;
java.text.ParseException;
java.text.SimpleDateFormat;
sb.append(cal.get(Calendar.YEAR))
.append(String.format("%03d", cal.get(Calendar.DAY_OF_YEAR)))
.toString();
}
public static void main(String[] args) throws Exception {
String test = "1998221";
Date d = DateUtils.getDateFromJulian7(test);
System.out.println(d);
System.out.println(DateUtils.getJulian7FromDate(d));
/*
* output :
*
Sun Aug 09 00:00:00 EDT 1998
*
1998221
*/
}
}
Using java.util.concurrent.TimeUnit
import java.util.concurrent.TimeUnit;
...
/**
* converts time (in milliseconds) to humanreadable format
* "<dd:>hh:mm:ss"
*/
java.io.*;
java.text.*;
java.util.*;
java.net.*;
}
}
System.out.println("DEBUG : " + atomicTime);
String[] fields = atomicTime.split(" ");
GregorianCalendar calendar = new GregorianCalendar();
String[] date = fields[1].split("");
calendar.set(Calendar.YEAR, 2000 + Integer.parseInt(date[0]));
calendar.set(Calendar.MONTH, Integer.parseInt(date[1])1);
calendar.set(Calendar.DATE, Integer.parseInt(date[2]));
// deals with the timezone and the daylightsavingtime
TimeZone tz = TimeZone.getDefault();
int gmt = (tz.getRawOffset() + tz.getDSTSavings()) / 3600000;
System.out.println("DEBUG : " + gmt);
String[] time = fields[2].split(":");
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time[0]) + gmt);
calendar.set(Calendar.MINUTE, Integer.parseInt(time[1]));
calendar.set(Calendar.SECOND, Integer.parseInt(time[2]));
return calendar;
}
catch (IOException e){
throw e;
}
finally {
if (in != null) {
in.close();
}
}
}
public static void main(String args[]) throws IOException {
SimpleDateFormat sdf =
new SimpleDateFormat("yyyyMMdd HH:mm:ss");
System.out.println("Atomic time : " +
sdf.format(DateUtils.getAtomicTime().getTime()));
}
/*
ref : http://www.bldrdoc.gov/doctour/atomic_clock.html
49825 950418 22:24:11 50 0 0 50.0 UTC(NIST) *
|
These are the last +
five digits of the
Modified Julian Date
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
It's not possible to set your local computer clock in pure Java.
You need to use an external utility provided by the OS or call a JNI routine, see this HowTo.
Month, Week
}
return new Calendar[] { startDate, endDate };
}
public static void main(String[] args) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
System.out.println("** previous month (relative today)");
Calendar [] results = DateUtils.getDateIntervals(IntervalType.Month, null);
System.out.println(sdf.format(results[0].getTime()));
System.out.println(sdf.format(results[1].getTime()));
System.out.println("** previous week (relative today)");
results = DateUtils.getDateIntervals(IntervalType.Week, null);
System.out.println(sdf.format(results[0].getTime()));
System.out.println(sdf.format(results[1].getTime()));
System.out.println("** previous month (relative jan 1, 2007)");
results = DateUtils.getDateIntervals(IntervalType.Month,
new GregorianCalendar(2007, 00, 1));
System.out.println(sdf.format(results[0].getTime()));
System.out.println(sdf.format(results[1].getTime()));
System.out.println("** previous week (relative jan 1, 2007)");
results = DateUtils.getDateIntervals(IntervalType.Week,
new GregorianCalendar(2007, 00, 1));
System.out.println(sdf.format(results[0].getTime()));
System.out.println(sdf.format(results[1].getTime()));
}
catch (Exception e) {
e.printStackTrace();
}
}
/*
output :
** previous
20080601
20080630
** previous
20080630
20080706
** previous
20061201
20061231
** previous
20061225
20061231
*/
}
2.24 Get the month (or day) name (localized)Tag(s): Date and
Time Internationalization
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java0650.html
import java.text.DateFormatSymbols;
import java.util.Locale;
public class DateUtils {
private DateUtils() { }
public static String getMonthName(int month) {
return getMonthName(month, Locale.getDefault());
}
public static String getMonthName(int month, Locale locale) {
DateFormatSymbols symbols = new DateFormatSymbols(locale);
String[] monthNames = symbols.getMonths();
return monthNames[month 1];
}
2.23 Use System time to generate unique IDTag(s): Date and Time Date and Time Varia
args) {
DateUtils.isLeap0(1900));
DateUtils.isLeap0(1996));
DateUtils.isLeap0(2000));
DateUtils.isLeap0(2010));
DateUtils.isLeap1(1900));
DateUtils.isLeap1(1996));
DateUtils.isLeap1(2000));
DateUtils.isLeap1(2010));
DateUtils.isLeap2(1900));
DateUtils.isLeap2(1996));
DateUtils.isLeap2(2000));
DateUtils.isLeap2(2010));
3 AWT
3.1 javaawt
java.awt.Color;
java.awt.Dimension;
java.awt.LayoutManager;
java.awt.Panel;
and then
import
import
import
import
import
import
3 AWT
java.applet.Applet;
java.awt.Button;
java.awt.CardLayout;
java.awt.Choice;
java.awt.Color;
java.awt.Component;
import
import
import
import
import
java.awt.FlowLayout;
java.awt.Panel;
java.awt.TextField;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
3 AWT
b3.addActionListener(this);
b4.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
//Show the first
((CardLayout)p0.getLayout()).show(p0, "First card");
}
else if (e.getSource() == b2) {
//Show the second
((CardLayout)p0.getLayout()).show(p0, "2nd card");
}
else if (e.getSource() == b3) {
//Show the third
((CardLayout)p0.getLayout()).show(p0, "3rd card");
}
else if (e.getSource() == b4) {
// get the current card
Component c[] = p0.getComponents();
int i = 0;
int j = c.length;
while (i < j) {
if (c[i].isVisible()) {
t2.setText("" + (i+1));
break;
}
else
i ++;
}
}
}
}
<HTML>
<TABLE><TR><TD>
<APPLET CODE=CardLayoutDemo.class WIDTH=300 HEIGHT=300>
</APPLET>
/HMTL
Try it here.
add(b, "South");
addWindowListener
(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
/*
** handle actions related to popup
*/
System.out.println("actionPerformed, event=" + e );
System.out.println(" command=" + e.getActionCommand());
System.out.println(" param=" + e.paramString());
System.out.println(" source=" + e.getSource());
}
}
void setHash(Component c, PopupMenu p) {
/*
** associate a Component with a particular Popup
*/
popupTable.put(c, p);
}
PopupMenu getHash(Component c) {
/*
** return a Popup associated with a particular Component
*/
return (PopupMenu)(popupTable.get(c));
}
public static void main (String argv[]) {
new PopupTest();
}
}
System.out.println
("Loading : "
+ ufd.loadFile(new Frame(), "Open...", ".\\", "*.java"));
System.out.println
("Saving : "
+ ufd.saveFile(new Frame(), "Save...", ".\\", "*.java"));
System.exit(0);
}
}
by
return fd.getDirectory() +
System.getProperty("file.separator") + fd.getFile();
[JDK1.5]
@todo
[JDK1.2]
import java.awt.*;
public class FontList {
public static void main(String args[]) {
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
String fontNames[] = ge.getAvailableFontFamilyNames();
int j = fontNames.length;
for (int i = 0 ; i < j ;i++ ) {
System.out.println(fontNames[i]);
}
}
}
sm.checkSystemClipboardAccess();
}
catch (Exception e) {e.printStackTrace();}
}
Toolkit tk = Toolkit.getDefaultToolkit();
StringSelection st =
new StringSelection("Hello world from Java");
Clipboard cp = tk.getSystemClipboard();
cp.setContents(st, this);
}
public void lostOwnership(Clipboard clip, Transferable tr) {
System.out.println("Lost Clipboard Ownership?!?");
}
}
NOTE: You can only use text (no graphic) with this functionality provided by the current JDK (1.4).
The "fullscreen" Frame is in exclusive mode. In this mode you can change the resolution
import java.awt.*;
class ScreenRes {
public static void main(String args[]) {
new ScreenRes().doit();
}
public void doit() {
Frame frame = new Frame();
GraphicsDevice device;
device =
GraphicsEnvironment.
getLocalGraphicsEnvironment().
getDefaultScreenDevice();
if ( device.isFullScreenSupported() ) {
device.setFullScreenWindow(frame);
if (device.isDisplayChangeSupported()) {
device.setDisplayMode(
new DisplayMode( 1024, 768,
8, // bitDepth 8 bits 256 colors
DisplayMode.REFRESH_RATE_UNKNOWN ));
}
else {
System.err.println("Change display mode not supported");
}
}
else {
System.err.println("Full screen not supported");
}
}
}
SWING jdk1.3
JFrame frame = new JFrame();
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
// can be
// frame.setExtendedState(Frame.MAXIMIZED_HORIZ);
// frame.setExtendedState(Frame.MAXIMIZED_VERT);
New with JDK1.4, JDialog has method to position a JDialog relative to a parent. For a JWindow or a
JFrame with no parent, then
f.setSize(100,100);
f.setLocationRelativeTo(NULL);
System.exit(0);
return true;
}
return super.handleEvent(evt);
}
[JDK1.1 Method 1]
public aFrame extends Frame implements WindowListener {
public aFrame(){
addWindowListener( this );
}
public void windowActivated(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}
public void windowOpened(WindowEvent e){}
public void windowClosing(WindowEvent e){ System.exit(0); }
public void windowClosed(WindowEvent e){}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
}
[JDK1.1 Method 2]
public class aFrame extends Frame {
public aFrame(){
addWindowListener( new Terminate() );
}
}
class Terminate extends WindowAdapter{
public void windowClosing(WindowEvent e){
System.exit(0);
}
}
[JDK1.1 Method 3]
public class aFrame extends Frame {
public aFrame() {
addWindowListener
(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
}
}
For a Dialog or a Window, a System.exit(0) may not be appropriate, call the dispose() method
instead.
class SimplePopUp extends Dialog
{
SimplePopUp() {
super(new Frame(), "simple popup");
this.addWindowListener
(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
e.getWindow().dispose();
}
}
);
}
The Frame after adding the Panel, will act as an ActionListener for events for the 2 Panel buttons.
[TestEventFrame.java]
import java.awt.*;
import java.awt.event.*;
public class TestEventFrame extends Frame implements
ActionListener, WindowListener {
TestEventPanel p1;
Button b1;
TestEventFrame(String title){
super(title);
setLayout(new FlowLayout());
p1 = new TestEventPanel();
b1 = new Button("A dummy button");
add(b1);
}
{ }
{ }
}
and finally
[Java0268.java]
import java.awt.*;
public class Java0268 extends java.applet.Applet {
TestEventFrame myTestEventFrame;
public void init() {
myTestEventFrame =
new TestEventFrame("TestEvent Frame");
}
}
Try it here.
or
frame.setIconImage(
new ImageIcon(
YourApp.class.getResource("logo.png")
).getImage()
);
import java.awt.*;
import java.awt.event.*;
public class TestNoMaximize {
MyFrame theFrame;
public static void main (String args[]){
TestNoMaximize t = new TestNoMaximize();
t.theFrame = new MyFrame("A Dummy Frame");
t.theFrame.setVisible(true);
}
}
class MyFrame extends Frame {
public MyFrame(String title){
super(title);
addWindowListener
(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
// no minimize or maximize
this.setResizable(false);
this.setSize(200,200);
}
public void paint(Graphics g) {
g.drawString("try to resize me...", 50, 50);
}
}
There is no way to allow minimizing but not maximizing unless you trap the maximizing in the paint
method and then resize to the original size.
import java.awt.*;
import java.awt.event.*;
public class TestNoMaximize {
MyFrame theFrame;
public static void main (String args[]){
TestNoMaximize t = new TestNoMaximize();
t.theFrame = new MyFrame("A Dummy Frame");
t.theFrame.setVisible(true);
}
}
class MyFrame extends Frame {
public MyFrame(String title){
super(title);
addWindowListener
(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
this.setSize(200,200);
}
System.out.println("Bye.");
System.exit(0);
}
}
);
}
public void update( Graphics g) {
paint(g);
}
public void paint(Graphics g) {
if(image != null) {
int x = 0, y = 0;
while(y < getSize().height) {
x = 0;
while(x< getSize().width) {
g.drawImage(image, x, y, this);
x= x + image.getWidth(null);
}
y = y + image.getHeight(null);
}
}
else {
g.clearRect(0, 0, getSize().width, getSize().height);
}
}
static public void main(String[] args) {
ImageFrame iframe = new ImageFrame();
iframe.setVisible(true);
}
}
The result :
void createFrame() {
Dimension d = getToolkit().getScreenSize();
setLocation(d.width/3,d.height/3);
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource() == ok) {
isOk = true;
setVisible(false);
}
else if(ae.getSource() == can) {
setVisible(false);
}
}
public static void main(String args[]){
Frame f = new Frame();
f.setSize(200,200);
f.setVisible(true);
MsgBox message = new MsgBox
(f , "Hey you user, are you sure ?", true);
if (message.isOk)
System.out.println("Ok pressed");
if (!message.isOk)
System.out.println("Cancel pressed");
message.dispose();
}
}
this.imgName = imgName;
tk = Toolkit.getDefaultToolkit();
splashImage = loadSplashImage();
showSplashScreen();
f.addWindowListener(new WindowListener());
}
public Image loadSplashImage() {
MediaTracker tracker = new MediaTracker(this);
Image result;
result = tk.getImage(imgName);
tracker.addImage(result, 0);
try {
tracker.waitForAll();
}
catch (Exception e) {
e.printStackTrace();
}
imgWidth = result.getWidth(this);
imgHeight = result.getHeight(this);
return (result);
}
public void showSplashScreen() {
Dimension screenSize = tk.getScreenSize();
setBackground(BORDERCOLOR);
int w = imgWidth + (BORDERSIZE * 2);
int h = imgHeight + (BORDERSIZE * 2);
int x = (screenSize.width w) /2;
int y = (screenSize.height h) /2;
setBounds(x, y, w, h);
setVisible(true);
}
public void paint(Graphics g) {
g.drawImage(splashImage, BORDERSIZE, BORDERSIZE,
imgWidth, imgHeight, this);
}
class WindowListener extends WindowAdapter {
// was windowActivated, thanks to H.Grippa for the fix!
public void windowOpened(WindowEvent we) {
setVisible(false);
dispose();
}
}
}
theFrame.setVisible(true);
}
}
class MyFrame extends Frame {
Splash mySplash;
public MyFrame(String title){
super(title);
addWindowListener
(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
mySplash = new Splash(this, "jht.gif");
// dummy delay so we can see the Splash!
for(int i = 0; i < 3000; i++) {
System.out.println(i) ;
}
setSize(200,200);
}
}
To make it more Swingoriented, you change the method signature for a JFrame instead.
Here an example.
We display a small window. When a file is added or deleted, the window is shaking for a brief
moment and display the event. By default, the folder c:/temp is used but you can specify another
one on the command line.
First get the code to detect a file modfication in a folder (in this HowTo, you need the DirWatcher
and DirFilterWatcher classes). Plus the following classes.
import java.awt.*;
import java.awt.event.*;
public class DirWatchWindow extends Frame {
Label folder;
Label info;
public DirWatchWindow() {
setTitle("DirWatchWindow");
setSize(600, 100);
setLayout(new BorderLayout());
folder = new Label("");
info
= new Label("");
add(folder, BorderLayout.NORTH);
add(info, BorderLayout.SOUTH);
setVisible(true);
addWindowListener
(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
}
public void setInfo(String text) {
info.setText(text);
}
public void setFolder(String dir) {
folder.setText("Watching folder : " + dir);
}
}
import java.util.*;
import java.io.*;
public class DirWatchTest {
public static void main(String args[]) {
String folderToWatch = "c:/temp";
if (args.length > 0) {
folderToWatch = args[0];
}
final DirWatchWindow dww = new DirWatchWindow();
dww.setFolder(folderToWatch);
TimerTask task = new DirWatcher(folderToWatch, "txt" ) {
protected void onChange( File file, String action ) {
// here we code the action on a change
dww.setInfo("File : "+ file.getName() +" action: " + action);
FrameUtils.vibrate(dww);
}
};
Timer timer = new Timer();
timer.schedule( task , new Date(), 1000 );
}
}
c:/myfolder
to specify your own folder. This demo is watching for files with the extension txt only.
[JDK1.1]
thanks to Lionel Giltay
import java.awt.TextField ;
import java.awt.event.KeyAdapter ;
import java.awt.event.KeyEvent ;
public class NumericTextField extends TextField
{
public NumericTextField (String _initialStr, int _col)
{
super (_initialStr, _col) ;
this.addKeyListener(new KeyAdapter()
{
public void keyTyped (KeyEvent e)
{
char c = e.getKeyChar() ;
if (!
((c==KeyEvent.VK_BACK_SPACE) || (c==KeyEvent.VK_DELETE)
|| (c== KeyEvent.VK_ENTER)
|| (c == KeyEvent.VK_TAB)
|| (Character.isDigit(c))))
{
e.consume() ;
}
}
});
}
public NumericTextField (int _col)
{
this ("", _col) ;
}
3.23 Make the ENTER key act like the TAB keyTag(s): AWT
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java0254.html
First create a TextField that listen to the Enter and react like a Tab key [JDK11]
import java.awt.*;
import java.awt.event.*;
public class MyTextField extends TextField {
MyTextField(int len) {
super(len);
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
int key = evt.getKeyCode();
if (key == KeyEvent.VK_ENTER)
transferFocus();}});
}
}
3.23 Make the ENTER key act like the TAB keyTag(s): AWT
Button b;
public void init() {
add(t1= new TextField(20));
add(t2= new TextField(20));
add(t3= new TextField(20));
t4onPanel = new TextField(20);
p1 = new Panel();
p1.setBackground(new Color(0).yellow);
p1.add(t4onPanel);
add(p1);
add(b = new Button("reset TextFields"));
b.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == b)
resetTextFields(this);
}
public static void resetTextFields(Container c) {
Component [] components = c.getComponents();
for (int i = 0; i <components.length; i++ ) {
if (components[i] instanceof Container)
resetTextFields((Container) components[i]) ;
else if (components[i] instanceof TextField)
((TextField) components[i]).setText("") ;
}
}
}
<HTML><HEAD></HEAD><BODY>
<APPLET CODE="FirstApplet.class"
NAME="myApplet"
HEIGHT=200 WIDTH=200>
</APPLET></BODY></HTML>
add(tf);
tf.addKeyListener(
new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (Character.isLetter(e.getKeyChar()))
e.setModifiers(Event.SHIFT_MASK);
}
});
pack();
addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
}
public Dimension getPreferredSize() {
return new Dimension(200,200);
}
}
down=false;
enabled=true;
InitImage(up_b,down_b);
setSize(w,h);
addMouseListener(new ImageButtonMouseListener());
addMouseMotionListener(new ImageButtonMouseMotionListener());
}
public void InitImage(URL up, URL down) {
MediaTracker tracker;
try {
UPimage = getToolkit().getImage(up);
DOWNimage = getToolkit().getImage(down);
tracker = new MediaTracker(this);
tracker.addImage(UPimage,0);
tracker.addImage(DOWNimage,1);
tracker.waitForAll();
}
catch (InterruptedException e) {
e.printStackTrace();
}
disabledimage=createImage(new FilteredImageSource
(UPimage.getSource(),new ImageButtonDisableFilter()));
w=UPimage.getWidth(this);
h=UPimage.getHeight(this);
}
public void paint(Graphics g) {
if (down) {
g.drawImage(DOWNimage,0,0,this);
}
else {
if (enabled) {
g.drawImage(UPimage,0,0,this);
}
else {
g.drawImage(disabledimage,0,0,this);
}
}
}
public void setEnabled(boolean b) {
enabled=b;
repaint();
}
public boolean isEnabled() {
return (enabled);
}
public void addActionListener(ActionListener l) {
actionListener =
AWTEventMulticaster.add(actionListener,l);
}
public void removeActionListener(ActionListener l) {
actionListener =
AWTEventMulticaster.remove(actionListener, l);
}
public class ImageButtonMouseListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
if ((p.x < w)&&(p.y < h)&&(p.x > 0)&&(p.y > 0)&&(enabled==true)) {
clicked=true;
down=true;
repaint();
}
}
public void mouseReleased(MouseEvent e) {
Point p = e.getPoint();
if (down) {
down=false;
repaint();
}
if ((p.x < w)&&(p.y < h)&&(p.x > 0)&&(p.y > 0)&&(clicked==true)) {
ActionEvent ae =
new ActionEvent(e.getComponent(),0,"click");
if (actionListener != null) {
actionListener.actionPerformed(ae);
}
}
clicked=false;
}
}
public class ImageButtonMouseMotionListener extends
MouseMotionAdapter {
public void mouseDragged(MouseEvent e) {
Point p = e.getPoint();
if ((p.x < w)&&(p.y < h)&&(p.x > 0)&&(p.y > 0)&&(clicked==true)) {
if (down==false) {
down=true;
repaint();
}
}
else {
if (down==true) {
down=false;
repaint();
}
}
}
}
public Dimension getPreferredSize() {
return (new Dimension(UPimage.getWidth(this),
UPimage.getHeight(this)));
}
public Dimension getMinimumSize() {
return getPreferredSize();
}
class ImageButtonDisableFilter extends RGBImageFilter {
public ImageButtonDisableFilter() {
canFilterIndexColorModel=true;
}
public int filterRGB(int x, int y, int rgb) {
return (rgb &~0xff000000) | 0x80000000;
}
}
}
[TestImageButton.java]
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.net.*;
When inserting a line, we simply pad spaces as needed. Here the first column is 20 characters
wide, the second 10 and the last one the remaining.
insertItem(ml, "ARCHIVE", "STATUS", "PORT");
With a Layout Manager, you have to validate() the layout to redraw the components invalidated.
Label aLabel = new Label("short label");
aLabel.setText ("A very long label");
this.validate();
While this method works in Netscape or the Appletviewer, on IE4/5 there is no resizing. You may
want to try this instead (thanks to Dan for the tip):
Label aLabel = new Label("short label");
aLabel.setText(""A very long label");
aLabel.invalidate(); // make sure the component is marked as nonvalid
this.validate();
This example how to change a Label or a String drawn with the drawString method by clicking on a
button.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class TestPaint extends Applet
implements ActionListener {
MyPanel p;
Label l;
Button b1, b2;
TextField t1, t2;
public void init() {
setLayout(new FlowLayout());
t1 = new TextField(10);
b1 = new Button("Change Label");
add(t1); add(b1);
t2 = new TextField(10);
b2 = new Button("Change drawString");
add(t2); add(b2);
l = new Label("label text");
add(l);
// a Panel with a drawString call
p = new MyPanel();
add(p);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
l.setText(t1.getText());
l.invalidate();
validate();
}
if (e.getSource() == b2) {
p.someString = t2.getText();
p.repaint();
}
}
}
class MyPanel extends Panel {
String someString = "drawstring";
MyPanel() { super(); }
public void paint (Graphics g) {
g.drawString(someString, 10,50);
}
public Dimension getPreferredSize() {
return new Dimension (100,100);
}
}
g.drawString(s.substring(j,j+1),x, y+(j*v));
j++;
}
}
}
[JDK1.4]
import java.awt.geom.AffineTransform;
import java.awt.Graphics2D;
Dimension offDimension;
Image offImage;
Graphics offGraphics;
Color borderColor = new Color(0).black;
public MultiLineLabel(String s, int i, boolean b) {
// s the label
// i alignement MultiLineLabel.CENTER, MultiLineLabel.RIGHT,
//
MultiLineLabel.LEFT
//
default MultiLineLabel.LEFT
// b border present or not
setAlignment(i);
setText(s);
setBorder(b);
}
public MultiLineLabel(String string, int i) {
this(string, i, false);
}
public MultiLineLabel(String string) {
this(string, 0);
}
public MultiLineLabel() {
this("", 0);
}
public void addNotify() {
super.addNotify();
calc();
}
public void setX(int i) { x = i;
public void setY(int i) { y = i;
}
}
Font f = getFont();
if (f != null) {
FontMetrics fm = getFontMetrics(f);
if (fm != null) {
line_height = fm.getHeight();
line_ascent = fm.getAscent();
max_width = 0;
for (int i = 0; i < num_lines; i++) {
line_widths[i] =
fm.stringWidth(lines[i]);
if (line_widths[i] > max_width)
max_width = line_widths[i];
}
}
}
}
public void update(Graphics g) {
super.paint(g);
Dimension d = getSize();
if ( (offGraphics == null) ||
(d.width != offDimension.width) ||
(d.height != offDimension.height)
) {
offDimension = d;
offImage = createImage(d.width, d.height);
offGraphics = offImage.getGraphics();
}
offGraphics.setColor(getBackground());
offGraphics.fillRect
(x, y, getSize().width 1,
getSize().height 1);
if (border) {
offGraphics.setColor(borderColor);
offGraphics.drawRect
(x, y, getSize().width 1, getSize().height 1);
}
int j = line_ascent +
(d.height num_lines * line_height) / 2;
for (int k = 0; k < num_lines; ) {
int i;
switch (alignment) {
case 0:
i = 0;
break;
case 2:
i = d.width line_widths[k];
break;
default:
i = (d.width line_widths[k]) / 2;
break;
}
i += leftRightMargin;
offGraphics.setColor(getForeground());
offGraphics.drawString(lines[k], i + x, j + y);
k++;
j += line_height;
}
g.drawImage(offImage,0,0,this);
}
public void paint(Graphics g) {
update(g);
}
public static void main(String args[]){
Frame f = new Frame("Test MultiLineLabel");
f.setSize(200,200);
f.setLayout(new FlowLayout());
f.setVisible(true);
MultiLineLabel mll1 = new MultiLineLabel
("This a test!\nsecond line\nthird line",
MultiLineLabel.LEFT, true);
// mll1.setBorderColor(new Color(0).blue);
mll1.setLeftRightMargin(15);
mll1.setTopBottomMargin(15);
f.add(mll1);
Button b = new Button("Dummy");
f.add(b);
MultiLineLabel mll2 = new MultiLineLabel
("123\n4\n567", MultiLineLabel.RIGHT, false);
mll2.setForeground(new Color(0).yellow);
mll2.setBackground(new Color(0).black);
f.add(mll2);
f.validate();
}
}
this.getFontMetrics(this.getFont()).stringWidth(this.getText()),
r.height this.getFontMetrics(this.getFont()).getDescent());
}
}
[TestUnderlinedLabel.java]
import java.applet.*;
import java.awt.*;
public class TestUnderlinedLabel extends Applet {
public void init() {
UnderlinedLabel ul1 =
new UnderlinedLabel
("Java Howto");
add(ul1);
}
}
[testapplet.html]
<HTML><HEAD></HEAD><BODY>
<APPLET CODE="TestUnderlinedLabel.class"
NAME="myApplet"
HEIGHT=200 WIDTH=200>
/APPLET/BODY/HTML
Check this Howto for underlined text in Swing.
java.applet.*;
java.awt.*;
java.awt.event.*;
java.net.*;
public URLLabel
(Applet applet , String url, String text, String target){
super(text);
setForeground(unvisitedURL);
try {
this.applet = applet;
this.url = new URL(url);
this.target = target;
addMouseListener( new Clicked() );
}
catch (Exception e) {
e.printStackTrace();
}
}
public void paint(Graphics g) {
Rectangle r;
super.paint(g);
r = g.getClipBounds();
g.drawLine(0,
r.height this.getFontMetrics(this.getFont()).getDescent(),
this.getFontMetrics(this.getFont()).stringWidth(this.getText()),
r.height this.getFontMetrics(this.getFont()).getDescent());
}
public void setUnvisitedURLColor(Color c) {
unvisitedURL = c;
}
public void setVisitedURLColor(Color c) {
visitedURL = c;
}
class Clicked extends MouseAdapter{
public void mouseClicked(MouseEvent me){
setForeground(visitedURL);
applet.getAppletContext().showDocument(url, target);
}
}
}
[TestURLLabel.java]
import java.applet.*;
import java.awt.*;
public class TestURLLabel extends Applet {
public void init() {
URLLabel ull1 = new URLLabel(this,
"http://www.rgagnon.com/howto.html",
"Java Howto");
add(ull1);
URLLabel ull2 = new URLLabel(this,
"http://www.rgagnon.com/bigindex.html",
"Java Howto BigIndex");
add(ull2);
URLLabel ull3 = new URLLabel(this,
"http://www.rgagnon.com/javadetails/java0001.html",
"Java Howto 0001");
add(ull3);
URLLabel ull4 = new URLLabel(this,
"http://www.rgagnon.com/javadetails/java0002.html",
"Java Howto 0002");
add(ull4);
validate();
}
}
[testapplet.html]
<HTML><HEAD></HEAD><BODY>
<APPLET CODE="TestURLLabel.class"
NAME="myApplet"
HEIGHT=200 WIDTH=200>
</APPLET></BODY></HTML>
Try it here.
frame.resize(400,400);
frame.show();
}
}
}
public void update( Graphics g) {
paint(g);
}
public void paint(Graphics g) {
if(image != null) {
int x = 0, y = 0;
while(y < getSize().height) {
x = 0;
while(x< getSize().width) {
g.drawImage(image, x, y, this);
x= x + image.getWidth(null);
}
y = y + image.getHeight(null);
}
}
else {
g.clearRect(0, 0, getSize().width, getSize().height);
}
}
static public void main(String[] args) {
ImageFrame iframe = new ImageFrame();
iframe.setVisible(true);
}
}
The result :
java.applet.*;
java.awt.*;
java.io.*;
java.net.*;
{
this);
this);
this);
Remember that it is always possible to the Java builtin icons so that you don't have to include your
own standard icons.
public static Icon getIconForType(int iconType) {
switch (iconType) {
case 0:
return UIManager.getIcon("OptionPane.errorIcon");
case 1:
return UIManager.getIcon("OptionPane.informationIcon");
case 2:
return UIManager.getIcon("OptionPane.warningIcon");
case 3:
return UIManager.getIcon("OptionPane.questionIcon");
}
return null;
}
Image resizedImage;
public void init() {
MediaTracker media = new MediaTracker(this);
// java howto image for example, can be JPG
source = getImage(getDocumentBase(),"../images/jht.gif");
media.addImage(source,0);
try {
media.waitForID(0);
// scale down, half the original size
ImageFilter replicate =
new ReplicateScaleFilter
(source.getWidth(this)/2, source.getHeight(this)/2);
ImageProducer prod =
new FilteredImageSource(source.getSource(),replicate);
resizedImage = createImage(prod);
media.addImage(resizedImage,1);
media.waitForID(1);
}
catch(InterruptedException e) {}
}
public void paint(Graphics g) {
g.drawImage(source, 10,10,this);
g.drawImage(resizedImage,10, 80,this);
}
}
Try it here.
Modern JDK has now a complete library devoted to graphic manipulation.
The following exampe takes a JPG file as input , rescale it to the passed parameters and writes the
result in the specified output file.
import
import
import
import
import
java.awt.*;
java.awt.geom.*;
java.awt.image.*;
java.io.*;
javax.imageio.*;
catch (Exception e) {
e.printStackTrace();
}
}
else {
System.out.println("\nUsage: java ScaleJPG src width height dest\n");
}
}
}
Example :
>java ScaleJPG javahowto.jpg 250 70 javahowto2.jpg
Input:
Ouput:
java.applet.*;
java.awt.*;
java.awt.image.*;
java.net.*;
e.printStackTrace();
}
f = new AlphaFilter();
f.setLevel(level);
fis = new FilteredImageSource(img.getSource(), f) ;
FadeThread ft = new FadeThread();
ft.delayedFading(this, 20);
ft.start();
}
public void paint(Graphics g) {
if (faded != null) {
g.drawImage(faded,0,0,this);
}
}
public void fadeIt() {
Graphics g = this.getGraphics();
level += sign;
if (level < 0) {
level=0;
sign = sign * 1;
}
if (level > 255) {
level=255;
sign = sign * 1;
try {
Thread.sleep(1000);
}
catch (Exception e) {}
}
f.setLevel(level);
if (faded != null) faded.flush();
faded = this.createImage(fis);
tracker.addImage(faded,0);
try {
tracker.waitForID(0);
}
catch (Exception ex) {
ex.printStackTrace();
}
repaint();
}
class FadeThread extends Thread {
FadeImage fadeApplet;
int delay;
public void delayedFading(FadeImage f, int delay) {
this.fadeApplet = f;
this.delay = delay;
}
public void run() {
while (true) {
try {
sleep(delay);
fadeApplet.fadeIt();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
class AlphaFilter extends RGBImageFilter {
private int level;
public AlphaFilter() {
canFilterIndexColorModel = true;
}
public void setLevel(int lev) {
level = lev;
}
public int filterRGB(int x, int y, int rgb) {
int a = level * 0x01000000;
return (rgb &
0x00ffffff) | a;
}
}
}
Try it here.
import
import
import
import
java.applet.Applet;
java.awt.*;
java.awt.image.*;
java.net.*;
try {
grabber.grabPixels();
}
catch(InterruptedException e) {
e.printStackTrace();
}
for(int y = 0; y < 32; y++) {
for(int x = 0; x < 32; x++) {
rotate[((32x1)*32)+y] = buffer[(y*32)+x];
}
}
rot = createImage(new MemoryImageSource(32, 32, rotate, 0, 32));
}
catch (Exception e) {
e.printStackTrace();
}
}
public void update( Graphics g) {
paint(g);
}
public void paint(Graphics g) {
g.drawImage(img, 0, 0,this);
g.drawImage(rot,0, 40, this);
}
}
The next example will rotate a picture 5 degrees at a time. We are using the Java2D package (and
Swing).
import
import
import
import
java.awt.*;
java.awt.event.*;
java.awt.geom.*;
javax.swing.*;
switch (e.id) {
case Event.SCROLL_ABSOLUTE:
case Event.SCROLL_PAGE_DOWN:
case Event.SCROLL_PAGE_UP:
case Event.SCROLL_LINE_UP:
case Event.SCROLL_LINE_DOWN:
sc.redraw();
return true;
}
}
return super.handleEvent(e);
}
}
class ScrollCanvas extends Panel {
int vw,vh;
int rw,rh;
Color b,f;
myCanvas c;
Scrollbar sv, sh;
// constructor
//
visible h w
//
real
h w
//
background foreground
ScrollCanvas
(int vw1, int vh1, int rw1, int rh1, Color b1, Color f1) {
super();
vw = vw1; vh = vh1;
rh = rh1; rw = rw1;
b = b1; f = f1;
int ScrollIncrement = 10;
setLayout(new BorderLayout());
c = new myCanvas(vw, vh, rw, rh, b ,f);
add("West", c);
sv = new Scrollbar
(Scrollbar.VERTICAL,0, ScrollIncrement, 0, rh);
add("East", sv);
sh = new Scrollbar
(Scrollbar.HORIZONTAL, 0, ScrollIncrement, 0, rw);
add("South", sh);
}
public void redraw() {
int y = sv.getValue();
int x = sh.getValue();
c.draw(x,y);
}
public Dimension minimumSize() {
return new Dimension(vw,vh);
}
public Dimension preferredSize() {
return new Dimension(vw,vh);
}
}
class myCanvas extends Canvas {
int vw, vh;
int rw, rh;
Color b, f;
int x, y;
Image buffImage;
Graphics offscreen;
boolean initDone;
myCanvas
(int vw1, int vh1, int rw1, int rh1, Color b1, Color f1) {
super();
vw = vw1; vh = vh1;
rh = rh1; rw = rw1;
b = b1; f = f1;
initDone = false;
repaint();
}
public void paint(Graphics g) {
if (!initDone)
initpaint(g);
else
g.drawImage(buffImage, x, y, this);
}
public void update(Graphics g) {
g.drawImage(buffImage, x, y, this);
}
public void initpaint(Graphics g) {
try {
buffImage = this.createImage(rw, rh);
offscreen = buffImage.getGraphics();
offscreen.setColor(b);
offscreen.fillRect(0, 0, rw, rh);
offscreen.setColor(f);
offscreen.setFont(new Font("Courier", Font.ITALIC, 42));
offscreen.drawString("Hello World!", 0, 50);
initDone = true;
g.drawImage(buffImage,0,0, this);
}
catch (Exception e) {
System.out.println("oups...");
}
}
public void draw (int x1, int y1)
x = x1;
y = y1;
update(getGraphics());
}
TILE BACKGROUND
in the HTML use :
PARAM NAME="bgImage" VALUE="images/myImage.jpg"
in the APPLET tag
Try it here.
[application version]
import
import
import
import
java.awt.*;
java.awt.event.*;
java.net.*;
java.io.*;
[applet version]
import
import
import
import
import
java.applet.*;
java.awt.*;
java.awt.event.*;
java.net.*;
java.io.*;
}
}
class APanel extends Panel implements ActionListener {
private List lbx;
private MyCanvas can;
private Applet parent = null;
private String url[] = new String[50];
public APanel(Applet a) {
parent = a;
setLayout(new GridLayout(1,2));
lbx = new List();
can = new MyCanvas();
add(lbx); add(can);
initLbx();
// action on listbox double click
lbx.addActionListener(this);
setBackground(new Color(0).white);
}
public void actionPerformed (ActionEvent ae) {
try {
URL theUrl =
new URL(parent.getCodeBase(), url[lbx.getSelectedIndex()]);
MediaTracker media = new MediaTracker(this);
Image image =
Toolkit.getDefaultToolkit().getImage(theUrl);
media.addImage(image, 0);
media.waitForID(0);
can.setImage(image);
}
catch (Exception e) { e.printStackTrace();}
}
public void initLbx() {
int i = 0;
try {
String aLine = "";
URL source =
new URL(parent.getCodeBase(), "imagelist.txt");
BufferedReader in
= new BufferedReader
(new InputStreamReader(source.openStream()));;
while(null != (aLine = in.readLine())) {
java.util.StringTokenizer st =
new java.util.StringTokenizer(aLine, "|");
url[i++] = st.nextToken();
// lbx.addItem(st.nextToken());
lbx.add(st.nextToken());
}
}
catch(Exception e) { e.printStackTrace();}
}
}
class MyCanvas extends Canvas {
private Image image;
public MyCanvas() {
super();
}
public void setImage(Image i) {
image = i;
repaint();
}
public void paint(Graphics g) {
if (image != null)
g.drawImage(image, 0,0, this);
}
}
NOTE : You can try this example here
else {
g.drawImage(img2,0,0,this);
index;
}
}
}
public Dimension getPreferredSize (){
return new Dimension
(img1.getHeight(this), img2.getWidth(this));
}
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {
index = 1;
repaint();
}
public void mouseExited(MouseEvent e) {
index = 0;
repaint();
}
}
To use such Canvas, try something like this. This example needs our Gumby GIFs (
).
import java.applet.*;
import java.awt.*;
import java.net.*;
public class TestToogleGifCanvas extends Applet {
ToggleGifCanvas tgc;
public void init() {
try {
tgc = new ToggleGifCanvas
(new URL(getDocumentBase(),"images/gumby.gif"),
new URL(getDocumentBase(),"images/gumby2.gif"));
add(tgc);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Try it here.
and
a white background. All we have to do is to look for the blue color with the "Alpha bits" set to opaque
and make them transparent.
[Transparency.java]
import java.awt.*;
import java.awt.image.*;
public class Transparency {
public static Image makeColorTransparent
(Image im, final Color color) {
ImageFilter filter = new RGBImageFilter() {
// the color we are looking for... Alpha bits are set to opaque
public int markerRGB = color.getRGB() | 0xFF000000;
public final int filterRGB(int x, int y, int rgb) {
if ( ( rgb | 0xFF000000 ) == markerRGB ) {
// Mark the alpha bits as zero transparent
return 0x00FFFFFF &rgb;
}
else {
// nothing to do
return rgb;
}
}
};
ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
return Toolkit.getDefaultToolkit().createImage(ip);
}
[app.java]
import java.awt.image.*;
import java.awt.*;
import java.net.*;
public class app extends java.applet.Applet {
Image GifOriginalWithWithBlueBackground;
Image GifModifiedWithTransparentBackground;
public void init() {
setBackground(new Color(0).white);
MediaTracker media = new MediaTracker(this);
// image of our friend, Gumby with a blue background
GifOriginalWithWithBlueBackground =
getImage(getDocumentBase(),"gumbyblu.gif");
media.addImage(GifOriginalWithWithBlueBackground,0);
try {
media.waitForID(0);
GifModifiedWithTransparentBackground =
Transparency.makeColorTransparent
(GifOriginalWithWithBlueBackground, new Color(0).blue);
}
catch(InterruptedException e) {}
}
public void paint(Graphics g) {
g.drawImage(GifOriginalWithWithBlueBackground, 10,10,this);
g.drawImage(GifModifiedWithTransparentBackground,10, 80,this);
}
}
[x.html]
<HTML><HEAD></HEAD><BODY>
<APPLET CODE="app.class"
NAME="myApplet"
HEIGHT=200 WIDTH=200>
</APPLET>
</BODY></HTML>
Since JDK1.4.2, javax.imageio.ImageIO lets you save and restore Images to disk in a platform
independent format. "png" and "jpeg" format are supported. With ImageIO, instead of Image you
use BufferedImage which is a subclass of Image.
import java.io.*;
import javax.imageio.*;
import java.awt.image.*;
public class FileOperations {
public static BufferedImage readImageFromFile(File file)
throws IOException
{
return ImageIO.read(file);
}
public static void writeImageToJPG
(File file,BufferedImage bufferedImage)
throws IOException
{
ImageIO.write(bufferedImage,"jpg",file);
}
}
import
import
import
import
and
java.applet.*;
java.awt.*;
java.awt.image.*;
java.net.*;
Try it here.
java.applet.*;
java.awt.*;
java.awt.image.*;
java.awt.event.*;
java.net.*;
and
g.drawImage(img[index],68,0,this);
index = (index <maxImg) ? index + 1 : 0;
}
}
}
public void animate() {
repaint();
}
public void actionPerformed(ActionEvent ae) {
working = !working;
}
class AnimationThread extends Thread {
AnimationProgress animationApplet;
int delay;
public void delayedAnimation(AnimationProgress a, int delay) {
this.animationApplet = a;
this.delay = delay;
}
public void run() {
while (true) {
try {
sleep(delay);
animationApplet.animate();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
From here, individual pixel can be accessed via the pixels array.
3.57 Get the color of a specific pixelTag(s): AWT
/*
** rubberband effect
*/
g.setXORMode(getBackground());
setForeground(new Color(0).blue);
if (xl != 1){
// erase the old line
g.drawLine(x1, y1, xl, yl);
if (x2 != 1) {
// draw the new one
g.drawLine(x1, y1, x2, y2);
}
}
}
public void update(Graphics g) {
// draw an offScreen drawing
Dimension dim = getSize();
if (offGra == null) {
offImg = createImage(dim.width, dim.height);
offGra = offImg.getGraphics();
}
offGra.setColor(new Color(0).black);
offGra.fillRect(0,0,dim.width, dim.height);
offGra.setColor(new Color(0).white);
offGra.setPaintMode();
for (int i=0; i < np; i++) {
Rectangle p = (Rectangle)lines.elementAt(i);
if (p.width != 1) {
offGra.drawLine(p.x, p.y, p.width, p.height);
}
}
// put the OffScreen image OnScreen
g.drawImage(offImg,0,0,null);
}
public boolean handleEvent(Event e) {
switch (e.id) {
case Event.MOUSE_DOWN:
// new starting point
x1 = e.x;
y1 = e.y;
// begin an new drawing process
x2 = 1;
return true;
case Event.MOUSE_UP:
// end a drawing process
lines.addElement(new Rectangle(x1, y1, e.x, e.y));
np++;
x2 = xl = 1;
repaint();
return true;
case Event.MOUSE_DRAG:
// xl yl line to be erased
xl = x2;
yl = y2;
// x2 y2 last current point
x2 = e.x;
y2 = e.y;
Dragupdate(getGraphics());
return true;
}
return super.handleEvent(e);
}
public boolean action(Event e, Object o) {
if (e.target == btnClear) resetDrawing();
if (e.target == btnUndo) undo();
return true;
}
public void undo() {
if (np>0) {
lines.removeElementAt(np1);
np;
repaint();
}
}
public void resetDrawing() {
lines.removeAllElements();
np=0;
repaint();
}
}
3.59 Convert RGB value to Hexadecimal (to be used in HTML for example)Tag(s): AWT
double xincdash=(x2x1)/(linelength/(dashlength));
double yincdash=(y2y1)/(linelength/(dashlength));
int counter=0;
for (double i=0;i<linelengthdashlength;i+=dashlength+spacelength){
g.drawLine((int) (x1+xincdashspace*counter),
(int) (y1+yincdashspace*counter),
(int) (x1+xincdashspace*counter+xincdash),
(int) (y1+yincdashspace*counter+yincdash));
counter++;
}
if ((dashlength+spacelength)*counter<=linelength)
g.drawLine((int) (x1+xincdashspace*counter),
(int) (y1+yincdashspace*counter),
x2,y2);
}
double
double
ddx +=
ddy +=
int dx
int dy
=
=
=
=
x1
x1
x2
x2
dx;
dx;
dx;
dx;
yPoints[0]
yPoints[1]
yPoints[2]
yPoints[3]
=
=
=
=
y1
y1
y2
y2
dy;
dy;
dy;
dy;
Using JDK1.2
public void paint(Graphics g){
Graphics2D g2d = (Graphics2D)g;
int width = 10;
g2d.setStroke(new BasicStroke(width));
g2d.drawLine(x1, y1, x2, y2);
}
On a Component
int width = 10;
BasicStroke bs = new BasicStroke(width);
JLabel l = new JLabel();
l.getGraphics().setStroke(bs);
l.drawLine(0,0,100,100);
Using JDK1.3
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class TestLine extends JFrame{
private MyPanel panel;
public TestLine() {
setSize(200, 200);
panel = new MyPanel();
getContentPane().add( panel, "Center" );
}
public static void main( String [] args ){
TestLine tl = new TestLine();
tl.setVisible( true );
}
}
class MyPanel extends JPanel {
final static BasicStroke stroke = new BasicStroke(2.0f);
final static BasicStroke wideStroke = new BasicStroke(8.0f);
public MyPanel(){}
public void paintComponent( Graphics g ){
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint
(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke( stroke );
g2.draw(new Line2D.Double(10.0, 10.0, 100.0, 10.0));
g2.setStroke( wideStroke );
g2.draw(new Line2D.Double(10.0, 50.0, 100.0, 50.0));
}
}
s = t.nextToken();
i = s.indexOf('');
value = Float.valueOf(s.substring(0, i)).floatValue();
c.addSlice(value, (Color)colors.get(s.substring(i + 1)));
}
resize(c.getMinimumSize().width, c.getMinimumSize().height);
add("Center", c);
}
}
class PieChartCanvas extends Canvas {
/*
** author
Ciaran Treanor [email protected]
*/
final double aspectFudge = 2.5;
int radius, depth, called = 1, numSlices = 0;
float total = 0, value[] = new float[10];
Color color[] = new Color[10];
Graphics offGraphics;
Image gfxBuff;
public PieChartCanvas(int radius, int depth) {
this.value = value;
this.color = color;
this.radius = radius;
this.depth = depth;
}
public void paint(Graphics g) {
int startAngle;
float angle;
Dimension d = getSize();
if(gfxBuff == null) {
gfxBuff = createImage(d.width, d.height);
offGraphics = gfxBuff.getGraphics();
offGraphics.setColor(getBackground());
offGraphics.fillRect(0, 0, d.width, d.height);
}
// do the 3d effect
for(int x = depth; x >= 1; x) {
startAngle = 45;
for(int i = 0; i < numSlices; i++) {
offGraphics.setColor(color[i].darker());
angle = Math.round(360 * (value[i] / total));
offGraphics.fillArc(0, x, radius, (int)(radius / aspectFudge),
startAngle, (int)angle);
startAngle += angle;
}
}
// draw the pie slice
startAngle = 45;
for(int i = 0; i < numSlices; i++) {
offGraphics.setColor(color[i]);
angle = Math.round(360 * (value[i] / total));
offGraphics.fillArc(0, 0, radius, (int)(radius / aspectFudge),
startAngle, (int)angle);
startAngle += angle;
}
g.drawImage(gfxBuff, 0, 0, null);
}
public void addSlice(float value, Color color) {
this.value[numSlices] = value;
this.color[numSlices++] = color;
total += value;
}
public Dimension getPreferredSize() {
return getMinimumSize();
}
public Dimension getMinimumSize() {
return new Dimension(radius, (int)((radius / aspectFudge) + depth));
}
}
[JavaPie.hmtl]
<HTML>
<TABLE><TR><TD>
<APPLET CODE=Graph.class WIDTH=150 HEIGHT=150>
<PARAM NAME="depth" VALUE="30">
<PARAM NAME="width" VALUE="120">
<PARAM NAME="values" VALUE="1red,5green,7blue">
</APPLET>
<TD>
<TABLE>
<TR><TD>item 1<TD BGCOLOR="#FF0000">
<TR><TD>item 2<TD BGCOLOR="#008000">
<TR><TD>item 3<TD BGCOLOR="#0000FF">
</TABLE>
</TABLE>
</HMTL>
Try it here
It seems that drawRoundRect(.) 1,5 faster then drawRect(..) , because one of them is
completely native.
import java.awt.*;
import java.awt.event.*;
public class Class1 extends Frame implements ActionListener{
public void paint(Graphics g){
super.paint(g);
long t=System.currentTimeMillis();
for(int i=0;i<10000;i++){
g.drawRect(10,70,100,50);
}
t=System.currentTimeMillis()t;
g.drawString(String.valueOf(t),10,70);
t=System.currentTimeMillis();
for(int i=0;i<10000;i++){
g.drawRoundRect(10,130,100,50,0,0);
}
t=System.currentTimeMillis()t;
g.drawString(String.valueOf(t),10,130);
}
public void actionPerformed(ActionEvent p1){
repaint(0,10,200,300);
}
public static void main (String[] args){
Class1 c=new Class1();
c.setSize(300,300);
c.setLayout(new BorderLayout());
Button b=new Button("Refresh");
c.add(BorderLayout.SOUTH , b);
b.addActionListener(c);
c.show();
}
}
java.awt.AWTException;
java.awt.Robot;
java.awt.Rectangle;
java.awt.Toolkit;
java.awt.image.BufferedImage;
java.io.*;
javax.imageio.ImageIO;
class ScreenCapture {
public static void main(String args[]) throws
AWTException, IOException {
// capture the whole screen
BufferedImage screencapture = new Robot().createScreenCapture(
new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()) );
// Save as JPEG
File file = new File("screencapture.jpg");
ImageIO.write(screencapture, "jpg", file);
// Save as PNG
// File file = new File("screencapture.png");
// ImageIO.write(screencapture, "png", file);
}
}
[JDK11]
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class d extends Applet
implements MouseListener {
public void init() {
this.addMouseListener(this);
}
public void paint(Graphics g) {
g.drawString("Click here", 10,10);
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {
System.out.println
( "Click at (" + e.getX() + ":" + e.getY() + ")" );
if (e.getClickCount() == 2)
System.out.println( " and it's a double click!");
else
System.out.println( " and it's a simple click!");
}
}
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {
switch(e.getModifiers()) {
case InputEvent.BUTTON1_MASK: {
System.out.println("That's the LEFT button");
break;
}
case InputEvent.BUTTON2_MASK: {
System.out.println("That's the MIDDLE button");
break;
}
case InputEvent.BUTTON3_MASK: {
System.out.println("That's the RIGHT button");
break;
}
}
}
}
}
);
add(new Label
("You can quit by clicking on the 'X'"),"South");
add(new Label
("You can quit by clicking on the menu item 'Exit'"),"Center");
add(new Label
("You can quit with the MenuShortcut 'ctrlx'"),"North");
setSize(300, 300);
show();
}
public void actionPerformed(ActionEvent evt) {
String what = evt.getActionCommand();
if (what.equals("Exit"))
processEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
}
static public void main(String[] args) {
new ExitFromMenu();
}
}
The regular JDK can only deal with JPG, GIF, BMP or PNG file with the package ImageIO, see this
HowTo.
To deal with TIF file, you must use the JAI (Java Advanced Imaging) package.
This example will display a given TIF file. It will also display other types (JPG,...) by detecting the
type.
import
import
import
import
import
import
import
import
import
import
javax.media.jai.PlanarImage;
com.sun.media.jai.codec.ByteArraySeekableStream;
com.sun.media.jai.codec.ImageCodec;
com.sun.media.jai.codec.ImageDecoder;
com.sun.media.jai.codec.SeekableStream;
java.io.FileInputStream;
java.nio.ByteBuffer;
java.nio.channels.FileChannel;
java.awt.Image;
java.awt.image.RenderedImage;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
public class ImageViewer
com.sun.media.jai.codec.FileSeekableStream;
com.sun.media.jai.codec.ImageDecoder;
com.sun.media.jai.codec.ImageCodec;
com.sun.media.jai.codec.TIFFEncodeParam;
import
import
import
import
java.awt.image.RenderedImage;
javax.media.jai.RenderedOp;
javax.media.jai.JAI;
java.awt.image.renderable.ParameterBlock;
irfanview is an amazing software when it comes to transform a graphic format to another one. You
can use it from a command line or from a GUI.
See also : Convert many singlepage TIF into one multipage TIF
java.io.FileOutputStream;
java.io.OutputStream;
java.util.ArrayList;
java.util.List;
java.awt.image.BufferedImage;
import javax.media.jai.NullOpImage;
import javax.media.jai.OpImage;
3.72 Convert many singlepage TIF into one multipage TIF Tag(s): AWT
import javax.media.jai.PlanarImage;
import
import
import
import
import
import
com.sun.media.jai.codec.ImageEncoder;
com.sun.media.jai.codec.SeekableStream;
com.sun.media.jai.codec.FileSeekableStream;
com.sun.media.jai.codec.ImageDecoder;
com.sun.media.jai.codec.ImageCodec;
com.sun.media.jai.codec.TIFFEncodeParam;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
public class ImageUtils {
public static BufferedImage imageToBufferedImage(Image im) {
BufferedImage bi = new BufferedImage
(im.getWidth(null),im.getHeight(null),BufferedImage.TYPE_INT_RGB);
Graphics bg = bi.getGraphics();
bg.drawImage(im, 0, 0, null);
bg.dispose();
return bi;
}
public static BufferedImage readImageFromFile(File file)
throws IOException
{
return ImageIO.read(file);
}
public static void writeImageToPNG
(File file,BufferedImage bufferedImage)
throws IOException
{
ImageIO.write(bufferedImage,"png",file);
}
public static void writeImageToJPG
(File file,BufferedImage bufferedImage)
throws IOException
{
ImageIO.write(bufferedImage,"jpg",file);
}
}
javax.media.jai.PlanarImage;
com.sun.media.jai.codec.ByteArraySeekableStream;
com.sun.media.jai.codec.ImageCodec;
com.sun.media.jai.codec.ImageDecoder;
com.sun.media.jai.codec.SeekableStream;
java.io.FileInputStream;
java.nio.ByteBuffer;
java.nio.channels.FileChannel;
java.awt.Color;
import
import
import
import
import
java.awt.Graphics;
java.awt.Image;
java.awt.image.PixelGrabber;
java.awt.image.BufferedImage;
java.awt.image.RenderedImage;
/**
* This utility loads a given TIF and try to detect if it's
* blank or not.
*
* We create inmemory image and then calculate the standard
* deviation of the color information. If a certain value is not
* reached then we assume that the image is mainly uniform and
* probably blank. The threshold value is an estimate. Depending
* the source of the TIF this value can be higher. For example,
* TIF from a FAX machine or a scanner can be dirty, with hair/dust presence,
* but with no content.
*
* jai_core.jar and jai_codec.jar are required.
* http://java.sun.com/products/javamedia/jai/index.jsp
*
* @author http://www.rgagnon.com/howto.html
*/
public class BlankDetection {
public static final int FAILURE = 2;
public static final int BLANK = 0;
public static final int NOTBLANK = 1;
// value where we can consider that this is a blank image
// can be much higher depending of the TIF source
// (ex. scanner or fax)
public static final int BLANK_THRESHOLD = 1000;
/**
* Creates an Image from a byte array
* @param data
* @return Image
* @throws Exception
*/
public static Image load(byte[] data) throws Exception {
Image image = null;
SeekableStream stream = new ByteArraySeekableStream(data);
String[] names = ImageCodec.getDecoderNames(stream);
ImageDecoder dec =
ImageCodec.createImageDecoder(names[0], stream, null);
RenderedImage im = dec.decodeAsRenderedImage();
image = PlanarImage.wrapRenderedImage(im).getAsBufferedImage();
// scaledown the image , maximum width : 500 px
// to preserve memory
Image imageScaled =
image.getScaledInstance(500, 1, Image.SCALE_SMOOTH);
return imageScaled;
}
/**
* Converts an Image to a BufferedImage
* @param im une Image
* @return BufferedImage
*/
public static BufferedImage imageToBufferedImage(Image im) {
BufferedImage bi = new BufferedImage
(im.getWidth(null),im.getHeight(null),BufferedImage.TYPE_INT_RGB);
Graphics bg = bi.getGraphics();
bg.drawImage(im, 0, 0, null);
bg.dispose();
return bi;
}
/**
* Check if an Image is blank or not
* Computes the standard deviation based on the color information
* @param bi bufferedimage
* @return true it's blank
*/
public static boolean isBlank(BufferedImage bi) throws Exception {
long count = 0;
long total = 0;
double totalVariance = 0;
double stdDev = 0;
int height = bi.getHeight();
int width = bi.getWidth();
int[] pixels = new int[width * height];
PixelGrabber pg = new PixelGrabber
(bi, 0, 0, width, height, pixels, 0, width);
pg.grabPixels();
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
count++;
int pixel = pixels[j * width + i];
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = (pixel) & 0xff;
int pixelValue = new Color(red, green,blue,0).getRGB();
total += pixelValue;
double avg = total /count;
totalVariance += Math.pow(pixelValue avg, 2);
stdDev = Math.sqrt(totalVariance / count);
}
}
return (stdDev <BLANK_THRESHOLD);
}
/**
* Accept on the command line the path to a TIF file
*
* Returns an errorlevel based on the analysis
* 0 blank
* 1 not blank
* 2 IO error
*
* @param args path vers complet vers un PROPS
*/
public static void main(String[] args) {
try {
if (args.length==0) {
System.out.println("Missing parameter.");
System.exit(FAILURE);
}
String path = args[0];
FileInputStream in = new FileInputStream(path);
FileChannel channel = in.getChannel();
ByteBuffer buffer = ByteBuffer.allocate((int)channel.size());
channel.read(buffer);
com.lowagie.text.Document;
com.lowagie.text.Image;
com.lowagie.text.PageSize;
com.lowagie.text.Rectangle;
com.lowagie.text.pdf.PdfContentByte;
com.lowagie.text.pdf.PdfWriter;
com.lowagie.text.pdf.RandomAccessFileOrArray;
com.lowagie.text.pdf.codec.TiffImage;
PdfContentByte cb = writer.getDirectContent();
RandomAccessFileOrArray ra = null;
int comps = 0;
try {
ra = new RandomAccessFileOrArray(tiff);
comps = TiffImage.getNumberOfPages(ra);
}
catch (Throwable e) {
System.out.println("Exception in " + tiff + " "
+ e.getMessage());
continue;
}
System.out.println("Processing: " + tiff);
for (int c = 0; c < comps; ++c) {
try {
Image img = TiffImage.getTiffImage(ra, c + 1);
if (img != null) {
System.out.println("page " + (c + 1));
img.scalePercent
(7200f / img.getDpiX(), 7200f / img.getDpiY());
document.setPageSize
(new Rectangle(img.getScaledWidth(), img.getScaledHeight()));
img.setAbsolutePosition(0, 0);
cb.addImage(img);
document.newPage();
++pages;
}
}
catch (Throwable e) {
System.out.println("Exception " + tiff + " page "
+ (c + 1) + " " + e.getMessage());
}
}
ra.close();
document.close();
}
catch (Throwable e) {
e.printStackTrace();
}
System.out.println("done");
}
}
}
import
import
import
import
import
import
import
import
import
import
java.io.FileOutputStream;
java.io.IOException;
java.awt.image.RenderedImage;
com.sun.image.codec.jpeg.JPEGCodec;
com.sun.image.codec.jpeg.JPEGImageEncoder;
com.sun.media.jai.codec.SeekableStream;
com.sun.media.jai.codec.FileSeekableStream;
com.sun.media.jai.codec.TIFFDecodeParam;
com.sun.media.jai.codec.ImageDecoder;
com.sun.media.jai.codec.ImageCodec;
4 Environment
4.1 javaenv
then in myClass
String myvar = System.getProperty("myvar");
String myothervar = System.getProperty("myothervar");
If you don't know in advance, the name of the variable to be passed to the JVM, then there is no
100% Java way to retrieve them.
One approach (not the easiest one), is to use a JNI call to fetch the variables, see this HowTo.
A more lowtech way, is to launch the appropriate call to the operating system and capture the
output. The following snippet puts all environment variables in a Properties class and display the
value the TEMP variable.
import java.io.*;
import java.util.*;
public class ReadEnv {
public static Properties getEnvVars() throws Throwable {
Process p = null;
Properties envVars = new Properties();
Runtime r = Runtime.getRuntime();
String OS = System.getProperty("os.name").toLowerCase();
// System.out.println(OS);
if (OS.indexOf("windows 9") > 1) {
p = r.exec( "command.com /c set" );
}
else if ( (OS.indexOf("nt") > 1)
|| (OS.indexOf("windows 2000") > 1 )
|| (OS.indexOf("windows xp") > 1) ) {
// thanks to JuanFran for the xp fix!
p = r.exec( "cmd.exe /c set" );
}
4 Environment
else {
// our last hope, we assume Unix (thanks to H. Ware for the fix)
p = r.exec( "env" );
}
BufferedReader br = new BufferedReader
( new InputStreamReader( p.getInputStream() ) );
String line;
while( (line = br.readLine()) != null ) {
int idx = line.indexOf( '=' );
String key = line.substring( 0, idx );
String value = line.substring( idx+1 );
envVars.setProperty( key, value );
// System.out.println( key + " = " + value );
}
return envVars;
}
public static void main(String args[]) {
try {
Properties p = ReadEnv.getEnvVars();
System.out.println("the current value of TEMP is : " +
p.getProperty("TEMP"));
}
catch (Throwable e) {
e.printStackTrace();
}
}
}
thanks to w.rijnders for the w2k fix.
// ok
// but specific to 2003
// better,
// since no other OS would
// return "windows"
|| (OS.indexOf("windows xp") > 1) ) {
I started with "windows 200" but thought "what the hell" and made it "windows 20" to lengthen its
longivity. You could push it further and use "windows 2," I suppose. The only thing to watch out for
is to not overlap with "windows 9."
On Windows, preJDK 1.2 JVM has trouble reading the Output stream directly from the SET
command, it never returns. Here 2 ways to bypass this behaviour.
First, instead of calling directly the SET command, we use a BAT file, after the SET command we
print a known string. Then, in Java, when we read this known string, we exit from loop.
4 Environment
[env.bat]
@set
@echo **end
[java]
...
if (OS.indexOf("windows") > 1) {
p = r.exec( "env.bat" );
}
...
while( (line = br.readLine()) != null ) {
if (line.indexOf("**end")>1) break;
int idx = line.indexOf( '=' );
String key = line.substring( 0, idx );
String value = line.substring( idx+1 );
hash.put( key, value );
System.out.println( key + " = " + value );
}
The other solution is to send the result of the SET command to file and then read the file from Java.
...
if (OS.indexOf("windows 9") > 1) {
p = r.exec( "command.com /c set > envvar.txt" );
}
else if ( (OS.indexOf("nt") > 1)
|| (OS.indexOf("windows 2000") > 1
|| (OS.indexOf("windows xp") > 1) ) {
// thanks to JuanFran for the xp fix!
p = r.exec( "cmd.exe /c set > envvar.txt" );
}
...
// then read back the file as a Proprties
Properties p = new Properties();
p.load(new FileInputStream("envvar.txt"));
Thanks to JP Daviau
// UNIX
public Properties getEnvironment() throws java.io.IOException {
Properties env = new Properties();
env.load(Runtime.getRuntime().exec("env").getInputStream());
return env;
}
Properties env = getEnvironment();
String myEnvVar = env.get("MYENV_VAR");
4 Environment
Java's System properties contains some useful informations about the environment, for example,
the TEMP and PATH environment variables (on Windows).
public class ShowSome {
public static void main(String args[]){
System.out.println("TEMP : "
+ System.getProperty("java.io.tmpdir"));
System.out.println("PATH : "
+ System.getProperty("java.library.path"));
System.out.println("CLASSPATH : "
+ System.getProperty("java.class.path"));
System.out.println("SYSTEM DIR : " +
System.getProperty("user.home")); // ex. c:\windows on Win9x
System.out.println("CURRENT DIR: "
+ System.getProperty("user.dir"));
}
}
Here some tips from H. Ware about the PATH on different OS.
PATH is not quite the same as library path. In unixes, they are completely differentthe libraries
typically have their own directories.
System.out.println("the current value of PATH is:
p.getProperty("PATH")+"}");
{" +
System.out.println("LIBPATH: {" +
System.getProperty("java.library.path")+"}");
gives
the current value of PATH is:
{/home/hware/bin:/usr/local/bin:/usr/xpg4/bin:/opt/SUNWspro/bin:
/usr/ucb:/bin:/usr/bin:/home/hware/linuxbin:/usr/openwin/bin/:
/usr/local/games:/usr/ccs/lib/:/usr/new:/usr/sbin/:/sbin/:
/usr/openwin/lib:/usr/X11/bin:/usr/bin/X11/:/usr/local/bin/X11:
/usr/bin/pbmplus:/usr/etc/:/usr/dt/bin/:/usr/lib:
/usr/lib/nis:/usr/share/bin:/usr/share/bin/X11:
/home/hware/work/cdk/main/cdk/../bin:.}
LIBPATH:
{/usr/lib/j2re1.3/lib/i386:/usr/lib/j2re1.3/lib/i386/native_threads:
/usr/lib/j2re1.3/lib/i386/client:/usr/lib/j2sdk1.3/lib/i386:/usr/lib:/lib}
on my linux workstation. (java added all those except /lib and /usr/lib). But these two lines aren't the
same on window either:
This system is windows nt
the current value of PATH is:
{d:\OrbixWeb3.2\bin;D:\jdk1.3\bin;c:\depot\cdk\main\cdk\bin;c:\depot\
cdk\main\cdk\..\bin;d:\OrbixWeb3.2\bin;D:\Program
Files\IBM\GSK\lib;H:\pvcs65\VM\win32\bin;c:\cygnus
\cygwinb20\Hi586cygwin32\bin;d:\cfn\bin;D:\orant\bin;
C:\WINNT\system32;C:\WINNT;
d:\Program Files\Symantec\pcAnywhere;
C:\Program Files\Executive Software\DiskeeperServer\;}
LIBPATH:
{D:\jdk1.3\bin;.;C:\WINNT\System32;C:\WINNT;D:\jdk1.3\bin;
c:\depot\cdk\main\cdk\bin;c:\depot\cdk\main\cdk\..\bin;
4 Environment
d:\OrbixWeb3.2\bin;D:\Program Files\IBM\GSK\lib;
H:\pvcs65\VM\win32\bin;c:\cygnus\cygwinb20\Hi586cygwin32\bin;d:\cfn\bin;
D:\orant\bin;C:\WINNT\system32;
C:\WINNT;C:\Program Files\Dell\OpenManage\ResolutionAssistant\Common\bin;
d:\Program Files\Symantec\pcAnywhere;
C:\Program Files\Executive Software\DiskeeperServer\;}
Java is prepending itself! That confused me and broke my exec from ant.
Belorussian translation
For some odd reasons, the getenv() method was removed from the JDK. Rumors is that a
mechanism to retrieve an environment will be back in JDK1.5 (see this HowTo). But for now, you
can use D switch to retrieve named environment variable and pass them to the JVM (see this
HowTo) or use this JNI routine :
JNIEXPORT jstring JNICALL JavaHowTo_getenv
(JNIEnv *env, jclass c, jstring jname){
if ( jname == NULL ) {
return NULL ;
}
const char *name =
(*env)>GetStringUTFChars(env, jname, (jboolean *)NULL) ;
const char *value = getenv(name) ;
(*env)>ReleaseStringUTFChars(env, jname, name) ;
return value ? (*env)>NewStringUTF(env, value) : NULL ;
}
NOTE : This is fine if the environment variable contains only regular 7bit ASCII characters.
See also this HowTo.
= GetImage.class \
myCanvas.class
SOURCEFILES = GetImage.java \
myCanvas.java
$(CLASSFILES)
Name: myCanvas.class
JavaBean: True
<<
# end JAR support
all : $(JARFILE) $(CLASSFILES) doc
doc : $(CLASSFILES)
javadoc version author d $(DOC) $(SOURCEFILES)
install :
copy $CLASSESFILE $(DEST)
clean:
del $(CLASSFILES)
}
public static boolean isMicrosoft() {
try {
Class.forName("com.ms.applet.GenericAppletContext");
}
catch (ClassNotFoundException e) {
System.out.println("This browser is not a Microsoft Browser.");
return false;
}
return true;
}
}
For example, our MyApplet.class exists in three versions. One is using Microsoftspecific classes,
the other is a JDK1.1 applet and finally a version for JDK102only browser. The idea is to put all the
required classes in an ARCHIVE file. By using a javascript entities, we decide which archive to use.
During layout time, the javascript entity is remplaced by the right archive name.
<HTML></HTML><HEAD>
<SCRIPT>
function isBrowser(b,v) {
browserOk = false;
versionOk = false;
browserOk = (navigator.appName.indexOf(b) != 1);
versionOk = (v <= parseInt(navigator.appVersion));
return browserOk &versionOk;
}
archiveToBeUsed = "java102.jar";
if (isBrowser("Microsoft", 4)) {
archiveToBeUsed = "ie4.jar";
}
else {
if isBrowser("Netscape", 4) {
archiveToBeUsed = "n4.jar";
}
}
</SCRIPT></HEAD><BODY>
<APPLET CODE ="MyApplet.class"
HEIGHT=100
WIDTH=400
ARCHIVE=}; >
</APPLET>
</BODY></HTML>
NOTE: You may need to use the document.write() method to generate the right APPLET tag instead of a the Javascript entity to be compatible
with Netscape and IE.
4.10 Ant
For simple need, Ant can be used to do substitution in your sources.
We insert into the code a special tag to delimit code that need to be stripped by the Ant script. Let's
say we use //@STARTDEBUG@// and //@ENDDEBUG@//.
package com.rgagnon.howto;
import javax.swing.JFrame;
public class Example {
public static void main(String args[]){
JFrame f = new JFrame();
f.setSize(300,200);
f.setVisible(true);
f.setTitle("HowTo");
//@STARTDEBUG@//
f.setTitle(f.getTitle() + " DEBUG version");
//@ENDDEBUG@//
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
If you execute this code, the JFrame title will have the word "DEBUG" appended to it.
The Ant script to remove the debugging code is :
<project default="buildme">
<target name="compileprod">
<copy todir="../out" includeEmptyDirs="false">
<filterchain>
<tokenfilter>
<replacestring from="//@STARTDEBUG@//" to="/*" />
<replacestring from="//@ENDDEBUG@//" to="*/" />
</tokenfilter>
</filterchain>
<fileset dir=".">
<include name="**/*.java" />
</fileset>
</copy>
<javac srcdir="../out" />
</target>
<target name="compiledebug">
<javac srcdir="." />
</target>
After running this script, the source (in the ..\out directory)
package com.rgagnon.howto;
import javax.swing.JFrame;
public class Example {
public static void main(String args[]){
JFrame f = new JFrame();
f.setSize(300,200);
f.setVisible(true);
f.setTitle("HowTo");
/*
f.setTitle(f.getTitle() + " DEBUG version");
*/
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
NOTE: This can be useful if you want to trim a JAR to include only classes actually used.
The default value for the minimum is 2Mb, for the maximum it's 64Mb.
doclet.Packages=Packages
doclet.SerialData=Serial Data\:
doclet.Since=Since\:
doclet.Warn_inline_taglet=Inline tag {0} should only be used with a {1}.
doclet.ClassUse_Subinterface=Subinterfaces of {0} in {1}
doclet.Frame_Version=Frame version
doclet.Generated_Docs_Untitled=Generated Documentation (Untitled)
[standard_fr.properties (extract)]
doclet.Window_Split_Index={0}\: {1}Index
doclet.Packages=Paquetages
doclet.SerialData=Donn\u00E9e s\u00E9rialis\u00E9e\:
doclet.Since=Depuis\:
doclet.Warn_inline_taglet=Inline tag {0} should only be used with a {1}.
doclet.ClassUse_Subinterface=Sousinterfaces de {0} dans {1}
doclet.Frame_Version=Version avec cadres
doclet.Generated_Docs_Untitled=Documentation g\u00E9n\u00E9r\u00E9e
Once everything translated, put your standard_fr.properties into the tools.jar making sure that the
file is located in the right package (along standard.properties in
com.sun.tools.doclets.standard.resources).
To generate in french, use the locale switch on the command line
javadoc locale fr ....
java version
On Windows, if you have a "file not found" message, it's because the JVM can't be found
through the PATH. Do it again but with the complete path (if the path contains spaces, make
sure to use quotes!) :
"c:\program files\java\j2sdk1.5.0\bin\java" version
Compile it (again you may need to specify the complete path to the compiler if the PATH is
not set correctly):
"c:\program files\java\j2sdk1.5.0\bin\javac" source 1.5 Test15.java
Note the switch "source 1.5", if you don't specify it you won't be able to access the new
features (like System.out.printf()).
Run it
>"C:\Program Files\Java\j2sdk1.5.0\bin\java" Test15
Local time: 15:26:04
import java.io.*;
The RuntimeMXBean defines several convenient methods for accessing system properties about
the Java virtual machine.
[J2SE 1.5]
import java.util.Date;
import java.lang.management.RuntimeMXBean;
import java.lang.management.ManagementFactory;
class JMXTest {
public static void main(String args[]) {
JMXTest x = new JMXTest();
x.doit();
}
public void doit() {
try{
RuntimeMXBean mx = ManagementFactory.getRuntimeMXBean();
System.out.println("BOOTCLASSPATH:\n" + mx.getBootClassPath());
System.out.println("CLASSPATH:\n" + mx.getClassPath());
// the input arguments passed to the Java virtual machine
// which does not include the arguments to the main method.
System.out.println("COMMAND LINE ARGS:\n" + mx.getInputArguments());
// a map of names and values of all system properties.
System.out.println("SYSTEM PROPERTIES:\n" + mx.getSystemProperties());
System.out.println("VM start time : " + new Date(mx.getStartTime()));
System.out.println("VM up time : " + mx.getUptime() + " ms");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
System.getProperty("java.vm.name")
.toLowerCase().indexOf("64") >= 0;
}
// probably 32bit
return false;
}
}
you get
java version "1.5.0"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0b64)
Java HotSpot(TM) Client VM (build 1.5.0b64, mixed mode, sharing)
The default JVM with a JIT (JustInTime compiler) for a "client" mode is used. The other available
mode is "server".
From the Hot Spot FAQ at http://java.sun.com/docs/hotspot/HotSpotFAQ.html#compiler_types.
What's the difference between the client and server systems?
These two systems are different binaries. They are essentially two different compilers
(JITs)interfacing to the same runtime system. The client system is optimal for applications which
need fast startup times or small footprints, the server system is optimal for applications where the
overall performance is most important. In general the client system is better suited for interactive
applications such as GUIs. Some of the other differences include the compilation policy,heap
defaults, and inlining policy.
Where do I get the server and client systems?
Client and server systems are both downloaded with the 32bit Solaris and Linux downloads. For
32bit Windows, if you download the JRE, you get only the client, you'll need to download the SDK
to get both systems.
For 64bit, only the server system is included. On Solaris, the 64bit JRE is an overlay on top of the
32bit distribution. However, on Linux and Windows, it's a completely separate distribution. The
default setting is defined the file jvm.cfg.
On Debian GNU/Linux with Sun Java 1.5.0, the file is in /etc/java1.5.0sun.
4.19 Set the default JVM typeTag(s): Environment
It's probably the 1.6 JRE that will be used since it's the last installed.
If the bytecode is incompatible with the given JRE then .. it won't work, of course.
ref : Java 6 technotes
You can always give the complete path to use a specific installation. Launching the JVM this way
does not use the registry setting at all.
>"C:\Program Files\Java\j2re1.4.1_02\bin\java" version
java version "1.4.1_02"
The result is
In Linux:
export _JAVA_OPTIONS='Xms64m Xmx128m Dawt.useSystemAAFontSettings=lcd'
ref : http://java.sun.com/j2se/1.5.0/docs/guide/2d/flags.html
If the Java process is launch via javaw.exe (Applet) then the environment variable is called
_JPI_VM_OPTIONS.
For example :
_JPI_VM_OPTIONS = Dsome.property=true
For a Java Web Start process (javaws.exe), the environment variable is called
JAVAWS_VM_ARGS.
For example :
JAVAWS_VM_ARGS = Dsome.property=true
ref : http://docs.oracle.com/javase/7/docs/webnotes/tsg/TSGDesktop/html/plugin.html#gcexdd
4.23 Set default value for java property (system wide)Tag(s): Environment
[JDK 1.1]
to compile: java JC mySource.java
(use redirection to keep the output)
java JC mySource.java >output.txt
import java.io.*;
public class JC {
public static void main( String args[] )
throws IOException, InterruptedException {
String fn = "JC.java";
if( args.length > 0 ) fn = args[0];
System.out.println( "BEGIN (" + fn + ")" );
Process p =
Runtime.getRuntime().exec( "javac verbose " + fn );
String buf;
BufferedReader se = new BufferedReader
or you can always use a small text editor like Textpad where you can write with Java code (with
syntax coloring), compile, capture compiler output and launch your Applet or Application directly
from the editor.
and the JVIEW window won't close until you hit ENTER.
Or simply execute JVIEW directly in a DOS window with
jview <classname>
Check this Howto for a better way...
package JavaCom;
public class JavaBeanSays {
private String _hello = "Hello World!";
public String getHello() {
return _hello ;
}
public void setHello(String s) {
_hello = s;
}
}
NOTE: This is not really a Bean but let's keep it simple!
The next step is to build a manifest file to identify the bean in the jar. Here it is (manifest.txt):
Name: JavaCom/JavaBeanSays
JavaBean: true
NOTE: If no manifest is present all classes in the jar are treated as beans.
The JavaBeanSays class is in the directory JavaCom, the manifest.txt is the directory under it. From
the directory under (the one containing manifest.txt), we built the jar with :
jar cfm javacom.jar manifest.txt javacom\JavaBeanSays.class
NOTE: You can download my JavaCom.jar if you to proceed more rapidly.
The next step is to run the packager. You run it from the JDK installation directory. If the JDK is
installed in c:\dev\java\jdk1.2.1\ for example , you go there. And you start the packager with
bin\java.exe cp jre\lib\rt.jar;jre\lib\jaws.jar sun.beans.ole.Packager
A wizard is started, you follow the 5 steps to create the "JavaBeans bridge for ActiveX" for the
JavabeanSays component.
The first step is to specify where is located the JavaCom.jar file. When selected, the wizard should
list the JavaCom.JavaBeanSays bean, press Next. The "ActiveX" name under which the beans will
be seen is shown, press Next (in VbScript, the beans suffix must be added to this name).
An output directory is needed, be careful because this directory name will be hardcoded in the
generated files (REG and TLB), you need to specify a valid directory name. The packager assume
that a subdirectory bin is present with the file beans.ocx in it. You can create it and then copy
beans.ocx from the JRE\bin into it or edit the REG file to specify the original JRE\bin and update the
registry with the good location.
The Bean is now registered and ready to be used as a COM object.
NOTE: There is a commandline interface available in the packager if you want to bypass the wizard.
strFromJava = objJava.getHello
MsgBox strFromJava, _
0,
_
"JAVA BEAN OUTPUT"
objJava.setHello("Bonjour le monde!")
strFromJava = objJava.getHello
MsgBox strFromJava, _
0,
_
"JAVA BEAN OUTPUT"
NOTE: Check the JAVA PLUGIN SCRIPTING documentation (jdk1.2) or (jsdk1.4). document for more infos.
But applets are prevented from reading these system properties (for security reason):
java.home
java.class.path
user.name
user.home
user.dir
To read a system property from within an applet, simply invoke System.getProperty(key) on the
property you are interested in.
String s = System.getProperty("java.vendor");
You need a second script to launch a java class with a console (useful to see debugging traces or
textonly Java program). Called it CRunJava.vbs . Then you will have two choices from the
SendTo menu, one for consolebased program and one for GUIbased (Windows) program.
' [CRunJava.vbs] start a java class with a console
Dim WSHShell, FSO, javaclass, javacompletepath, cmdline
Set WSHShell = WScript.CreateObject("WScript.Shell")
Set FSO = WScript.CreateObject("Scripting.FileSystemObject")
If WScript.Arguments.Count = 0 Then
WScript.Echo "no argument on the command line."
Else
javaclass = WScript.Arguments(0)
If fso.GetExtensionName(javaclass) = "class" Then
javacompletepath = fso.GetAbsolutePathName(javaclass)
javapath = fso.GetParentFolderName(javacompletepath)
javaclass = fso.GetBaseName(javaclass)
' keep the console open
Note : A JAR can be made self executable (with double click), see this HowTo
to
javaw MyApp
In the properties tab panel, you also havethe possibility to assign an icon to the Shortcut. If you click
on the newly created icon, your Java application will start without opening a DOS box. If your
application is Text mode application use "java" instead of "javaw".
If the Microsoft JVM is used then use "wjview" (instead of "jview") to start a GUI Java application
from an icon.
In this example,we query the registry to extract the personal folder path ("My Documents") and the
processor ID and its name.
import java.io.*;
public class RegQuery {
private static final String REGQUERY_UTIL = "reg query ";
private static final String REGSTR_TOKEN = "REG_SZ";
private static final String REGDWORD_TOKEN = "REG_DWORD";
private static final String PERSONAL_FOLDER_CMD = REGQUERY_UTIL +
"\"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\"
+ "Explorer\\Shell Folders\" /v Personal";
private static final String CPU_SPEED_CMD = REGQUERY_UTIL +
"\"HKLM\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\""
+ " /v ~MHz";
private static final String CPU_NAME_CMD = REGQUERY_UTIL +
"\"HKLM\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\""
+ " /v ProcessorNameString";
}
catch (Exception e) {
return null;
}
}
static class StreamReader extends Thread {
private InputStream is;
private StringWriter sw;
StreamReader(InputStream is) {
this.is = is;
sw = new StringWriter();
}
public void run() {
try {
int c;
while ((c = is.read()) != 1)
sw.write(c);
}
catch (IOException e) { ; }
}
String getResult() {
return sw.toString();
}
}
public static void main(String s[]) {
System.out.println("Personal directory : "
+ getCurrentUserPersonalFolderPath());
System.out.println("CPU Name : " + getCPUName());
System.out.println("CPU Speed : " + getCPUSpeed() + " Mhz");
}
}
Remember : This code is a hack and may break anytime. A better alternative is to use JNA.
import
import
import
import
import
import
import
java.lang.reflect.InvocationTargetException;
java.lang.reflect.Method;
java.util.HashMap;
java.util.Map;
java.util.ArrayList;
java.util.List;
java.util.prefs.Preferences;
static
static
static
static
static
static
static
static
static
static
static
static
static
static
static
static {
try {
regOpenKey = userClass.getDeclaredMethod("WindowsRegOpenKey",
new Class[] { int.class, byte[].class, int.class });
regOpenKey.setAccessible(true);
regCloseKey = userClass.getDeclaredMethod("WindowsRegCloseKey",
new Class[] { int.class });
regCloseKey.setAccessible(true);
regQueryValueEx = userClass.getDeclaredMethod("WindowsRegQueryValueEx",
new Class[] { int.class, byte[].class });
regQueryValueEx.setAccessible(true);
regEnumValue = userClass.getDeclaredMethod("WindowsRegEnumValue",
new Class[] { int.class, int.class, int.class });
regEnumValue.setAccessible(true);
regQueryInfoKey = userClass.getDeclaredMethod("WindowsRegQueryInfoKey1",
new Class[] { int.class });
regQueryInfoKey.setAccessible(true);
regEnumKeyEx = userClass.getDeclaredMethod(
"WindowsRegEnumKeyEx", new Class[] { int.class, int.class,
int.class });
regEnumKeyEx.setAccessible(true);
regCreateKeyEx = userClass.getDeclaredMethod(
"WindowsRegCreateKeyEx", new Class[] { int.class,
byte[].class });
regCreateKeyEx.setAccessible(true);
regSetValueEx = userClass.getDeclaredMethod(
/**
* Read a value from key and value name
* @param hkey
HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
* @param key
* @param valueName
* @return the value
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static String readString(int hkey, String key, String valueName)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
if (hkey == HKEY_LOCAL_MACHINE) {
return readString(systemRoot, hkey, key, valueName);
}
else if (hkey == HKEY_CURRENT_USER) {
return readString(userRoot, hkey, key, valueName);
}
else {
throw new IllegalArgumentException("hkey=" + hkey);
}
}
/**
* Read value(s) and value name(s) form given key
* @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
* @param key
* @return the value name(s) plus the value(s)
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static Map<String, String> readStringValues(int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
if (hkey == HKEY_LOCAL_MACHINE) {
return readStringValues(systemRoot, hkey, key);
}
else if (hkey == HKEY_CURRENT_USER) {
return readStringValues(userRoot, hkey, key);
}
else {
throw new IllegalArgumentException("hkey=" + hkey);
}
}
/**
* Read the value name(s) from a given key
* @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
* @param key
* @return the value name(s)
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static List<String> readStringSubKeys(int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
if (hkey == HKEY_LOCAL_MACHINE) {
return readStringSubKeys(systemRoot, hkey, key);
}
else if (hkey == HKEY_CURRENT_USER) {
return readStringSubKeys(userRoot, hkey, key);
}
else {
throw new IllegalArgumentException("hkey=" + hkey);
}
}
/**
* Create a key
* @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
* @param key
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static void createKey(int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int [] ret;
if (hkey == HKEY_LOCAL_MACHINE) {
ret = createKey(systemRoot, hkey, key);
regCloseKey.invoke(systemRoot, new Object[] { new Integer(ret[0]) });
}
else if (hkey == HKEY_CURRENT_USER) {
ret = createKey(userRoot, hkey, key);
regCloseKey.invoke(userRoot, new Object[] { new Integer(ret[0]) });
}
else {
throw new IllegalArgumentException("hkey=" + hkey);
}
if (ret[1] != REG_SUCCESS) {
throw new IllegalArgumentException("rc=" + ret[1] + " key=" + key);
}
}
/**
* Write a value in a given key/value name
* @param hkey
* @param key
* @param valueName
* @param value
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static void writeStringValue
(int hkey, String key, String valueName, String value)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
if (hkey == HKEY_LOCAL_MACHINE) {
writeStringValue(systemRoot, hkey, key, valueName, value);
}
else if (hkey == HKEY_CURRENT_USER) {
writeStringValue(userRoot, hkey, key, valueName, value);
}
else {
throw new IllegalArgumentException("hkey=" + hkey);
}
}
/**
* Delete a given key
* @param hkey
* @param key
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static void deleteKey(int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int rc = 1;
if (hkey == HKEY_LOCAL_MACHINE) {
rc = deleteKey(systemRoot, hkey, key);
}
else if (hkey == HKEY_CURRENT_USER) {
rc = deleteKey(userRoot, hkey, key);
}
if (rc != REG_SUCCESS) {
throw new IllegalArgumentException("rc=" + rc + " key=" + key);
}
}
/**
* delete a value from a given key/value name
* @param hkey
* @param key
* @param value
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static void deleteValue(int hkey, String key, String value)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int rc = 1;
if (hkey == HKEY_LOCAL_MACHINE) {
rc = deleteValue(systemRoot, hkey, key, value);
}
else if (hkey == HKEY_CURRENT_USER) {
value=" + value);
}
// =====================
private static int deleteValue
(Preferences root, int hkey, String key, String value)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {
new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS) });
if (handles[1] != REG_SUCCESS) {
return handles[1]; // can be REG_NOTFOUND, REG_ACCESSDENIED
}
int rc =((Integer) regDeleteValue.invoke(root,
new Object[] {
new Integer(handles[0]), toCstr(value)
})).intValue();
regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });
return rc;
}
private static int deleteKey(Preferences root, int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int rc =((Integer) regDeleteKey.invoke(root,
new Object[] { new Integer(hkey), toCstr(key) })).intValue();
return rc; // can REG_NOTFOUND, REG_ACCESSDENIED, REG_SUCCESS
}
private static String readString(Preferences root, int hkey, String key, String value)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {
new Integer(hkey), toCstr(key), new Integer(KEY_READ) });
if (handles[1] != REG_SUCCESS) {
return null;
}
byte[] valb = (byte[]) regQueryValueEx.invoke(root, new Object[] {
new Integer(handles[0]), toCstr(value) });
regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });
return (valb != null ? new String(valb).trim() : null);
}
private static Map<String,String> readStringValues
(Preferences root, int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
HashMap<String, String> results = new HashMap<String,String>();
int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {
new Integer(hkey), toCstr(key), new Integer(KEY_READ) });
if (handles[1] != REG_SUCCESS) {
return null;
}
int[] info = (int[]) regQueryInfoKey.invoke(root,
How to use it :
package com.rgagnon.howto;
public class WinRegistryTest {
public static void main(String args[]) throws Exception {
String value = "";
// IE Download directory (HKEY_CURRENT_USER)
value = WinRegistry.readString(
WinRegistry.HKEY_CURRENT_USER,
"Software\\Microsoft\\Internet Explorer",
"Download Directory");
System.out.println("IE Download directory = " + value);
// Query for Acrobat Reader installation path (HKEY_LOCAL_MACHINE)
value = WinRegistry.readString(
WinRegistry.HKEY_LOCAL_MACHINE,
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\AcroRd32.exe",
"");
System.out.println("Acrobat Reader Path = " + value);
/*
this code is broken under win7 64 :(
20130112
"HowTo",
"java");
//
//
//
//
//
//
WinRegistry.deleteValue(
WinRegistry.HKEY_CURRENT_USER,
"SOFTWARE\\rgagnon.com", "HowTo");
WinRegistry.deleteKey(
WinRegistry.HKEY_CURRENT_USER,
"SOFTWARE\\rgagnon.com\\");
System.out.println("Done." );
}
The output :
IE Download directory = C:\Documents and Settings\Ral\Bureau
Acrobat Reader Path = C:\Program Files\Adobe\Acrobat 5.0\Reader\AcroRd32.exe
{SubVersionNumber=, CurrentBuild=1.511.1 () (snipped)...
[Accessibility, AeDebug, Asr, Classes, Compatibility, (snipped)...
Done.
"MicroVersion"="1"
"RuntimeLib"="C:\\Program Files\\Java\\j2re1.4.1_02\\bin\\client\\jvm.dll"
[HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.5]
"JavaHome"="C:\\Program Files\\Java\\jre1.5.0"
"RuntimeLib"="C:\\Program Files\\Java\\jre1.5.0\\bin\\client\\jvm.dll"
"MicroVersion"="0"
[HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.5.0]
"JavaHome"="C:\\Program Files\\Java\\jre1.5.0"
"MicroVersion"="0"
"RuntimeLib"="C:\\Program Files\\Java\\jre1.5.0\\bin\\client\\jvm.dll"
Output example :
C:\temp>findjava.cmd
Java Version = 1.6
Java home path (per registry) = C:\\applications\\dev\\jre6
Note :
The above script returns the default JVM if the PATH variable does not override it!
Oracle client installation is famous to force an outdated Java at the beginning of the PATH. This
oneliner displays the java.exe (if any) found in the PATH :
c:\> for %i in (java.exe) do @echo.
C:\WINDOWS\system32\java.exe
%~$PATH:i
The java.exe in the system32 relies on the CurrentVersion registry setting to determine which
registry key to use to look up the location of the Java RE.
java.io.BufferedReader;
java.io.File;
java.io.FileWriter;
java.io.InputStreamReader;
java.util.*;
fw.write(vbs);
fw.close();
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
BufferedReader input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
String line;
java.io.BufferedReader;
java.io.File;
java.io.FileWriter;
java.io.InputStreamReader;
fw.write(vbs);
fw.close();
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
BufferedReader input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
String line;
line = input.readLine();
if (line != null) {
if (line.equals(process)) {
found = true;
}
}
input.close();
}
catch(Exception e){
e.printStackTrace();
}
return found;
}
public static void main(String[] args){
boolean result = VBSUtils.isRunning("TextPad.exe");
msgBox("Is TextPad running ?
}
public static void msgBox(String msg) {
javax.swing.JOptionPane.showConfirmDialog((java.awt.Component)
null, msg, "VBSUtils", javax.swing.JOptionPane.DEFAULT_OPTION);
}
}
java.io.BufferedReader;
java.io.IOException;
java.io.InputStream;
java.io.InputStreamReader;
java.util.ArrayList;
java.util.List;
4.42 Detect if a process is running using WMIC Tag(s): Misc Prog HowTo Java Environment
}
public static void main(String[] args) throws IOException {
System.out.println(WindowsUtils2.isProcessRunning("excel.exe"));
}
}
and then get the path of the JRE from the corresponding key
[HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.5\JavaHome]
Beware that some software (eg. Oracle) installs themself at the beginning of the PATH definition, so
it's their Java installation that will be found first.
You can run the absolute path to the java.exe file, as in
"C:\Program Files\Java\jre1.5.0\bin\java.exe" MyClass
It will not use the registry, and it will be guaranteed to use jre1.5.0.
So for a regular Java SE program, it is safe to specify the complete path to the JRE to launch it.
But for the Applet/Plugin or WebStartbased programs, the registry is always used to determine the
current JRE.
::
:: get the javahome
::
FOR /F "usebackq skip=4 tokens=3,4" %%A IN (`REG QUERY %JAVA_CURRENT% /v %JAVA_HOME% 2^>nul`) D
set JAVA_PATH=%%A %%B
)
echo the path of the current Java JVM according to the registry is
echo %JAVA_PATH%
echo.
echo now if we try it :
"%JAVA_PATH%\bin\java.exe" version
:end
>j.cmd
the current Java runtime is 1.6
the path of the current Java JVM according to the registry is
C:\Program Files\Java\jre1.6.0_06
now if we try it :
java version "1.6.0_06"
Java(TM) SE Runtime Environment (build 1.6.0_06b02)
4.44 Get the current Java version from a BAT fileTag(s): Environment
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Desktop directory : "
+ getCurrentUserDesktopPath());
}
static class StreamReader extends Thread {
private InputStream is;
private StringWriter sw;
StreamReader(InputStream is) {
this.is = is;
sw = new StringWriter();
}
public void run() {
try {
int c;
while ((c = is.read()) != 1)
sw.write(c);
}
catch (IOException e) { ; }
}
String getResult() {
return sw.toString();
}
}
}
java.io.BufferedReader;
java.io.File;
java.io.FileWriter;
java.io.InputStreamReader;
static
static
static
static
static
static
static
static
static
static
static
static
String
String
String
String
String
String
String
String
String
String
String
String
private VBSUtils() {
SF_ALLUSERSDESKTOP
SF_ALLUSERSSTARTMENU
SF_ALLUSERSPROGRAMS
SF_ALLUSERSSTARTUP
SF_DESKTOP
SF_FAVORITES
SF_MYDOCUMENT
SF_PROGRAMS
SF_RECENT
SF_SENDTO
SF_STARTMENU
SF_STARTUP
=
=
=
=
=
=
=
=
=
=
=
=
"AllUsersDesktop";
"AllUsersStartMenu";
"AllUsersPrograms";
"AllUsersStartup";
"Desktop";
"Favorites";
"MyDocuments";
"Programs";
"Recent";
"SendTo";
"StartMenu";
"Startup";
See also :
Get Windows Desktop path using the registry
Get Windows "My Documents" path using FileSystemView.getDefaultDirectory()
See also Get Windows Special Folders (JNA)
// see note
private static final String WINDOWS_DESKTOP = "Desktop";
/**
* the current user desktop path
* @return the current user desktop path
*/
public static String getWindowsCurrentUserDesktopPath() {
return System.getenv("userprofile") + "/" + WINDOWS_DESKTOP ;
}
/**
* Create an Internet shortcut on User's Desktop no icon specified
* @param name
name of the shortcut
* @param target URL
* @throws IOException
*/
public static void createInternetShortcutOnDesktop(String name, String target)
throws IOException
{
String path = getWindowsCurrentUserDesktopPath() + "/"+ name + ".URL";
createInternetShortcut(name, path, target, "");
}
/**
* Create an Internet shortcut on User's Desktop, icon specified
* @param name
name of the shortcut
* @param target URL
* @param icon
URL (ex. http://www.server.com/favicon.ico)
* @throws IOException
*/
public static void createInternetShortcutOnDesktop
(String name, String target, String icon)
throws IOException
{
String path = getWindowsCurrentUserDesktopPath() + "/"+ name + ".URL";
NOTE:
Prior Vista, the desktop path for a localized Windows can be different. With an english version, it's
Desktop while for a french version, it's called Bureau.
The only way to get the right name is to ask the Registry, see this HowTo.
// remote session
private WindowsUtils() {}
public static boolean isRemote() throws SecurityException, UnsatisfiedLinkError,
UnsupportedOperationException, IOException
{
NativeCall.init();
IntCall ic = null;
try {
ic = new IntCall("user32", "GetSystemMetrics");
int rc = ic.executeCall(new Integer(SM_REMOTESESSION));
return (rc gt; 0);
}
finally {
if (ic != null) ic.destroy();
}
}
public static void main(String ... args) throws Exception {
System.out.println(WindowsUtils.isRemote());
}
}
An easy way is to check the Windows environment variable sessionname. The value of this
environment variable will be 'Console' for a normal, local session. For an Remote Desktop session it
will contain the phrase 'RDP'.
public static boolean isRemoteDesktopSession() {
System.getenv("sessionname").toLowerCase().startsWith("rdp");
}
Note that environment varialbe values are read at the JVM startup. So if the JVM process was
started by a console session, but then accessed by an RDP session, further calls to
System.getenv("sessionname") still return 'Console'
See this HowTo to detect a Citrix session.
will be documented as
4.51.1 newMethod
public java.lang.String newMethod()
Returns:
value
Table(s):
firstname
lastname
city
country
4.51.1 newMethod
/**
* Will return true since <code>@todo</code>
* can be used in method documentation.
* @return true since <code>@todo</code>
* can be used in method documentation and false
* otherwise.
*/
public boolean inMethod() {
return true;
}
/**
* Will return true since <code>@todo</code>
* can be used in method documentation.
* @return true since <code>@todo</code>
* can be used in overview documentation and false
* otherwise.
*/
public boolean inOverview() {
return true;
}
/**
* Will return true since <code>@todo</code>
* can be used in package documentation.
* @return true since <code>@todo</code>
* can be used in package documentation and false
* otherwise.
*/
public boolean inPackage() {
return true;
}
/**
* Will return true since <code>@todo</code>
* can be used in type documentation (classes or interfaces).
* @return true since <code>@todo</code>
* can be used in type documentation and false
* otherwise.
*/
public boolean inType() {
return true;
}
/**
* Will return false since <code>@todo</code>
* is not an inline tag.
* @return false since <code>@todo</code>
* is not an inline tag.
*/
public boolean isInlineTag() {
return false;
}
/**
* Register this Taglet.
* @param tagletMap the map to register this tag to.
*/
public static void register(Map tagletMap) {
Table tag = new Table();
Taglet t = (Taglet) tagletMap.get(tag.getName());
if (t != null) {
4.51.1 newMethod
tagletMap.remove(tag.getName());
}
tagletMap.put(tag.getName(), tag);
}
/**
* Given the <code>Tag</code> representation of this custom
* tag, return its string representation.
* @param tag
the <code>Tag</code> representation of this custom tag.
*/
public String toString(Tag tag) {
String output = "";
String tables [] = tag.text().split(";");
int j = tables.length;
if (j > 0) {
output = "<DT><B>" + HEADER
+ "</B><DD><TABLE><TR>";
for (int i=0; i < j ; i++){
// deals with the current table and its fields
String current[] = tables[i].split(":");
output +=
"<TD><TABLE style=\"borderstyle:solid;"
+ " borderwidth:thin\">";
output +=
"<TH ALIGN=\"center\" STYLE=\"borderstyle:solid;"
+ " borderwidth:thin\">"
+ current[0] + "</TH>";
if (current.length > 1) {
String fields[] = current[1].split(",");
int k = fields.length;
for (int n=0; n < k ; n++) {
output += "<TR><TD ALIGN=\"center\">"
+ fields[n] + "</TD></TR>";
}
}
output += "</TABLE>";
}
output += "</TR></TABLE>";
}
return output;
}
/**
* Given an array of Tags representing this custom
* tag, return its string representation.
* @param tags the array of Tags representing of this custom tag.
*/
public String toString(Tag[] tags) {
if (tags.length == 0) {
return null;
}
String result = "";
for (int i = 0; i < tags.length; i++) {
result += toString(tags[i]);
}
return result ;
}
}
Compile your taglet. Use javac compiler version 1.4.0 (or later) in the Java 2 SDK. The required
class files are in the lib\tools.jar file in the SDK. Assuming the SDK is installed at C:\Program
Files\j2sdk1.4.1 :
4.51.1 newMethod
Run the javadoc tool using the taglet and tagletpath options. For example, if your taglet class file
is defined to be in package com.rgagnon.taglet and is stored in
C:\taglets\com\rgagnon\taglet\Table.class, then you should set tagletpath to C:\taglets. This
example calls javadoc on package com.package1, including Table taglet tags:
C:\dev\Work\java\taglet>javadoc taglet com.rgagnon.taglet.Table
tagletpath c:\dev\work\java\taglet com.package1
[standard_fr.properties (extract)]
doclet.Window_Split_Index={0}\: {1}Index
doclet.Packages=Paquetages
doclet.SerialData=Donn\u00E9e s\u00E9rialis\u00E9e\:
doclet.Since=Depuis\:
doclet.Warn_inline_taglet=Inline tag {0} should only be used with a {1}.
doclet.ClassUse_Subinterface=Sousinterfaces de {0} dans {1}
doclet.Frame_Version=Version avec cadres
doclet.Generated_Docs_Untitled=Documentation g\u00E9n\u00E9r\u00E9e
Once everything translated, put your standard_fr.properties into the tools.jar making sure that the
file is located in the right package (along standard.properties in
com.sun.tools.doclets.standard.resources).
To generate in french, use the locale switch on the command line
javadoc locale fr ....
Now execute the javadoc utility located in [JDK]\bin directory from the root of the com.rgagnon
package.
4.53 Document a package using Javadoc Tag(s): Environment
You can represent any character with a numerical identity, the syntax is &#nnn; where nnn is the
Unicode code (decimal value) of the character.
The XML will not be visible since it will embedded in the HTML as tag and not as text.
With Javadoc 1.5, you can use the {@code ... } command. :
/**
* To use this class use this XML
* <pre>
* {@code
* <xml>
*
<parameter>foo</parameter>
*
<value>bar</value>
* </xml>
* }
* </pre>
*/
With the previous versions, one way was to add a space after the <.
/**
* To use this class use this XML
* <pre>
* < xml>
*
< parameter>foo< /parameter>
*
< value>bar< /value>
* < /xml>
* }
* </pre>
*/
buf.append(new java.util.Date());
buf.append(' ');
buf.append(rec.getLevel());
buf.append(' ');
buf.append(formatMessage(rec));
buf.append('\n');
return buf.toString();
}
});
logger = Logger.getLogger("TestLog");
logger.addHandler(fh);
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
logger.severe("my severe message");
logger.warning("my warning message");
logger.info("my info message");
}
}
See this HowTo to format a duration in ms into a string as "Days , Hours , minutes and seconds".
While you can set the level in your code with something like
logger.setLevel(Level.WARN);
You put the properties file in the classpath and then from your code
URL url = ClassLoader.getSystemResource("log4j.props");
PropertyConfigurator.configure(url);
Logging activities have a cost. Even if you set the level at DEBUG level, the logger.debug(...) is
interpreted. Consider this line :
logger.setLevel(Level.DEBUG);
logger.debug("something wrong with the value of " + myValue.toString());
the toString() method will be called and the result concatened to a String even if the DEBUG level is
disabled.
The best practice is to check if the level is enabled or not.
logger.setLevel(Level.DEBUG);
if (logger.isDebugEnabled()) {
logger.debug("something wrong with the value of " + myValue.toString());
}
This way you will not incur the cost of parameter construction if debugging is disabled for logger.
You can even remove the unwanted logging operation from the bytecode! See this HowTo.
Finally it's a good idea to design a robust toString() method for your class like this one :
public String toString(){
StringBuffer sb = new StringBuffer();
sb.append(getClass().getName())
sb.append(" myValue=[").append(this.myValue).append("]");
sb.append(" anotherValue=[").append(this.anotherProperty).append("]");
return sb.toString();
}
even if myValue is null, this toString() method will display "null" as the value and not throw a
NullPointerExeception.
See also this HowTo and this one
It may be useful to change it onthefly for debugging purpose. You need to get the Log4J "root"
Logger and then change its "level".
...
setLogLevel("DEBUG");
...
setLogLevel("INFO");
...
private void setLogLevel(String level) {
Logger root = Logger.getRootLogger();
if ("DEBUG".equals(level)) {
root.setLevel(org.apache.log4j.Level.DEBUG);
}
else {
root.setLevel(org.apache.log4j.Level.INFO);
}
}
will launch the program and output to stdout the debugging information.
HTTPSender
HTTPSender
HTTPSender
HTTPSender
HTTPSender
...
4.62 Enable debug log level on OpenSource package(Apache Commons Logging)Tag(s): Environment
2009/08/21
2009/08/21
2009/08/21
2009/08/21
12:15:56:109
12:15:56:109
12:15:56:109
12:15:56:109
EDT
EDT
EDT
EDT
[DEBUG]
[DEBUG]
[DEBUG]
[DEBUG]
header
header
header
header
>>
>>
>>
>>
"Host: api.sandbox.ebay.com[\r][\n]"
"ContentLength: 1546[\r][\n]"
"ContentType: text/xml; charset=UTF8[\r][\n]"
"[\r][\n]"
In theory, you can specify many JARs in one ARCHIVE tag. But the current version of Netscape will
only load the first JAR and ignore the others.
Microsoft IEv4 can handle multiple JAR files.
In an application, simply include the JAR in the CLASSPATH :
4.63 Use a JAR/ZIP/CAB file with an AppletTag(s): Environment
To create a JAR file (compressed), use the JAR utility included with JDK1.1
jar cvf abc.jar a.class b.class c.class
According to some JAVA developers, JAR in CLASSPATH needs to be uncompressed (JDK1.1). To create uncompressed JAR:
[ZIP format]
JDK1.0.2 introduces the ZIP "uncompressed" format. To create an archive, simply use a ZIP tool
that supports the long filename format and specify the ZERO compression mode. You can use
Sun's JAR utility (included with JDK1.1) to create a JDK1.0.2 compatible ZIP file:
jar cvfO myArchive.zip *.class
[CAB format]
CAB (for CABINET) is used only by Microsoft Internet Explorer. It offers compression (like the JAR
but the ZIP format is uncompressed). To create a CAB file, use the CABARC utility from Microsoft :
CABARC n myArchive.cab *.*
to create myArchive.cab.
It is possible sign a CAB file using the Authenticode mechanism, check the Microsoft Web site for
more infos.
To associate a CAB file with an Applet, simply use the HTML :
<APPLET CODE="a.class"
WIDTH=100
HEIGHT=100>
<PARAM
NAME="cabbase"
VALUE="abc.cab">
</APPLET>
the cabbase parameter will be interpreted only by MSIE, nonMS browsers browser will simply
ignore it.
An Applet can support ZIP and CAB format by using the following HTML:
<APPLET
CODEBASE="."
ARCHIVE=abc.zip
CODE=a.class
width=610
height=600 >
<PARAM NAME="cabbase" VALUE="abc.cab">
</APPLET>
while Netscape will use the ZIP file and ignore de CAB parameter, MSIE will use CAB and ignore
the ZIP file.
Then create this manifest file (manifest.mft) with any text editor.
ManifestVersion: 1.0
MainClass: MyClass
Classpath: .
MainClass specifies the entry point with the main(String args[]) method.
The Classpath is used to specify the dependency of this jar (if any). You add the directories and
jars separated by a space. It is important because when running a jar , the CLASSPATH definition
(as defined by the environnement variable) is overridden.
Next, you include the manifest file in the JAR (MyJar.jar) with the MyClass class.
jar cvfm myjar.jar manifest.mft *.class
Then you are able to start the MyClass.class by doubleclicking on the MyJar.jar file (if the JRE is
correctly installed) or by typing
java jar myjar.jar
If you need to pass parameters, use the D switch before the jar switch and use the getProperty()
method to get the value.
The file association mechanism is made during the installation of the JRE.
You can verify that everything is ok with the following command from a DOS Shell
>assoc .jar
.jar=jarfile
>ftype jarfile
jarfile="C:\Program Files\Java\jre1.5.0_10\bin\javaw.exe" jar "%1" %*
If the association is broken or you need to change the JRE used then by using the assoc/ftype
utilities, you can modify the association easily (use /? to display the syntax of the assoc and ftype
utilities).
NOTE: On WinXp (or better), your user account needs to be at the Admin level.
On Windows (NT or better), you can also make JARs run from the commandline by setting the
PATHEXT environment variable, for example
SET PATHEXT=.EXE;.BAT;.CMD;.JAR
Then if you have the jar file MyJar.jar accessible via the PATH environment variable, typing "MyJar"
on the DOS command line will invoke "javaw jar MyJar.jar" .
The value of the ClassPath attribute specifies the relative URLs of the extensions or libraries that
this application or extension needs. URLs are separated by one or more spaces. The application or
extension class loader uses the value of this attribute to construct its internal search path.
You can use the i option to speed up your application's class loading time:
jar i main.jar
This will build an an INDEX.LIST file in the METAINF directory which will enable the application
class loader to download the right jar files when it is searching for classes or resources.
new File("C:/xtras/xercesImpl.jar").toURL();
URL urlB =
new File("C:/xtras/xmlParserAPIs.jar").toURL();
URL[] urls = { urlA,urlB };
URLClassLoader ulc = new URLClassLoader(urls);
//
Class c = Class.forName
("org.apache.xerces.dom.ChildNode", true, ulc);
//
System.out.println(c.getName());
}
catch(Exception e) {
e.printStackTrace();
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args []){
new ExtractFromJAR().extractMyMDBFromJAR(".");
}
}
Run it ... and the mydb.mdb file should appear in the current directory.
java jar mydb.jar
I got a problem when the jar file was located in C:\Program Files\xyz due to the embedded space.
So I modified the code to
String home = getClass().getProtectionDomain()
.getCodeSource().getLocation()
.getPath().replaceAll("%20", " ");
The output
>jar cvfm Hello.jar manifest.mft com\rgagnon\HelloClass.class
added manifest
adding: com/rgagnon/HelloClass.class (in=1059) (out=601) (deflated 43%)
>java com.rgagnon.HelloClass
file:/C:/DEV/WORK/JAVA/com/rgagnon/HelloClass.class
>java jar Hello.jar
*** running from jar!
jar:file:/C:/DEV/WORK/JAVA/Hello.jar!/com/rgagnon/HelloClass.class
Here a variation on this subject, a method to return the name of the current running jar.
package com.rgagnon.howto;
public class RunningJar {
public static void main(String[] args) {
String runningJarName = new RunningJar().getRunningJarName();
if (runningJarName != null) {
System.out.println("Running from " + runningJarName);
}
else {
System.out.println("Not running from a jar");
}
}
public String getRunningJarName() {
String className = this.getClass().getName().replace('.', '/');
String classJar =
this.getClass().getResource("/" + className + ".class").toString();
if (classJar.startsWith("jar:")) {
String vals[] = classJar.split("/");
for (String val: vals) {
if (val.contains("!")) {
return val.substring(0, val.length() 1);
}
}
}
return null;
}
}
/*
output :
>java jar yop.jar
Running from yop.jar
>ren yop.jar yip.jar
*
*/
public static void main (String[] args){
List list = PackageUtils.getClasseNamesInPackage
("C:/j2sdk1.4.1_02/lib/mail.jar", "com.sun.mail.handlers");
System.out.println(list);
/*
output :
Jar C:/j2sdk1.4.1_02/lib/mail.jar looking for com/sun/mail/handlers
Found com.sun.mail.handlers.text_html.class
Found com.sun.mail.handlers.text_plain.class
Found com.sun.mail.handlers.text_xml.class
Found com.sun.mail.handlers.image_gif.class
Found com.sun.mail.handlers.image_jpeg.class
Found com.sun.mail.handlers.multipart_mixed.class
Found com.sun.mail.handlers.message_rfc822.class
[com.sun.mail.handlers.text_html.class,
com.sun.mail.handlers.text_xml.class, com
.sun.mail.handlers.image_jpeg.class,
, com.sun.mail.handlers.message_rfc822.class]
*/
}
}
Create a simple Hello class as shown below (you need have a package).
package howto;
public class Hello {
public static void main( String[] args ){
System.out.println( "Hello World" );
}
}
... and load it into your favorite editor. Type the following ant script and save it.
<project default="buildHello">
<target name="compile">
<javac srcdir="." />
</target>
<target name="buildHello" depends="compile" />
</project>
Go back to the editor and add the jar building command. The target compile is also executed
since the target jar depends on it.
<project default="buildHello">
<target name="compile">
<javac srcdir="." />
</target>
<target name="jar" depends="compile">
<jar destfile="hello.jar"
basedir="."
includes="**/*.class"
/>
</target>
<target name="buildHello" depends="compile,jar" />
</project>
EST
EST
EST
EST
2006
2006
2006
2006
METAINF/
METAINF/MANIFEST.MF
howto/
howto/Hello.class
Make your Jar autoexecutable by specifying the Main class into a MANIFEST.MF file to be
included in the Jar. Add the following lines to build.xml
<project default="buildHello">
<target name="compile">
<javac srcdir="." />
</target>
<target name="jar" depends="compile">
<delete file="hello.jar"/>
<delete file="MANIFEST.MF"/>
<manifest file="MANIFEST.MF">
<attribute name="BuiltBy" value="${user.name}"/>
<attribute name="MainClass" value="howto.Hello"/>
</manifest>
<jar destfile="hello.jar"
basedir="."
includes="**/*.class"
manifest="MANIFEST.MF"
/>
</target>
<target name="buildHello" depends="compile,jar" />
</project>
Add a build number with the Ant task buildnumber . Ant will create (if necessary) and increment a
property in a file called build.num (so you need to keep it!). Then a property, build.number, is
available in your Ant script. The version number is also a property. Here it is hardcoded in the
script but you can read it from a file.
<project default="buildHello">
<target name="compile">
<javac srcdir="." />
</target>
<target name="jar" depends="compile">
<delete file="hello.jar"/>
<delete file="MANIFEST.MF"/>
<property name="version.num" value="1.00"/>
<buildnumber file="build.num"/>
<manifest file="MANIFEST.MF">
<attribute name="BuiltBy" value="${user.name}"/>
<attribute name="MainClass" value="howto.Hello"/>
<attribute name="ImplementationVersion"
value="${version.num}b${build.number}"/>
</manifest>
<jar destfile="hello.jar"
basedir="."
includes="**/*.class"
manifest="MANIFEST.MF"
/>
</target>
<target name="buildHello" depends="compile,jar" />
</project>
Modify the Hello class to read the ImplementationVersion information and display it.
package howto;
public class Hello {
public static void main( String[] args ){
System.out.println( "Hello World ");
System.out.println("version : " +
Hello.class.getPackage().getImplementationVersion() );
}
}
Finally we add a target to cleanup and the main target to build everything to the build.xml file.
<project default="buildHello">
<target name="compile">
<javac srcdir="." />
</target>
<target name="jar">
<delete file="hello.jar"/>
<property name="version.num" value="1.00"/>
<buildnumber file="build.num"/>
<manifest file="MANIFEST.MF">
<attribute name="BuiltBy" value="${user.name}"/>
<attribute name="MainClass" value="howto.Hello"/>
<attribute name="ImplementationVersion"
value="${version.num}b${build.number}"/>
</manifest>
<jar destfile="hello.jar"
basedir="."
includes="**/*.class"
manifest="MANIFEST.MF"
/>
</target>
<target name="cleanup">
<delete>
<fileset dir="." includes="**/*.class"/>
<fileset file="MANIFEST.MF"/>
</delete>
</target>
<target name="buildHello" depends="compile,jar,cleanup" />
</project>
buildclasspath.cmd
set _CLASSPATH=%CLASSPATH%
set CLASSPATH=%1
for %%i in ( %1\*.jar ) do call buildclasspath_append.cmd %%~fsi
if "%_CLASSPATH%" == "" goto END
set CLASSPATH=%_CLASSPATH%;%CLASSPATH%
:END
buildclasspath_append.cmd
set CLASSPATH=%CLASSPATH%;%1
With XP (or better), it's simpler ... a single batch file can do the job.
@echo off
setlocal ENABLEDELAYEDEXPANSION
if defined CLASSPATH (set CLASSPATH=%CLASSPATH%;.) else (set CLASSPATH=.)
FOR /R .\lib %%G IN (*.jar) DO set CLASSPATH=!CLASSPATH!;%%G
Echo The Classpath definition is %CLASSPATH%
...
java MyClass
4.75 JDK6
According to http://java.sun.com/javase/6/docs/technotes/tools/windows/java.html, there is a new
way to include jars in a given directory without explicitly to specify each one of them.
As a special convenience, a class path element containing a
basename of * is considered equivalent to specifying a list
of all the files in the directory with the extension .jar
or .JAR (a java program cannot tell the difference between
the two invocations).
For example, if directory foo contains a.jar and b.JAR, then
the class path element foo/* is expanded to a A.jar:b.JAR,
except that the order of jar files is unspecified. All jar files
in the specified directory, even hidden ones, are included in
the list. A classpath entry consisting simply of * expands to a
list of all the jar files in the current directory. The CLASSPATH
environment variable, where defined, will be similarly expanded.
Note : There is a bug when using this feature with JAVAW, see
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6510337
Note : Use quote to avoid problem during the wildcard expansion, ex. javac cp "C:\mylib\*"
HelloWorld.java
The manifest file format restrictions mandated by the JDK requires the use of a space ' ' character
as the line continuation character, so ensure that your editor is not set up to trim trailing spaces
on saves and exits.
The line with the ClassPath: header must end with a space character and each of the lines
referencing the client jar's should start and end with a space ' ' character and the manifest file as
a whole must end with a blank line.
Remember that when you launch an application with
4.75 JDK6
the CLASSPATH definition (as defined by the environment variable) is overriden by the
"classpath" defined the jar's manifest.
See http://java.sun.com/docs/books/tutorial/deployment/jar/downman.html
Ant can be used to build your Jar and built the manifest classpath definition.
<target name="MyJar" depends="dist, compile" description="generate jar" >
<jar destfile="${dist}/${jar}">
<manifest>
<attribute name="MainClass" value="${Main_Class}"/>
<attribute name="ClassPath" value=". lib/utils.jar lib/client.jar" />
</manifest>
</jar>
</target>
It's possible (but not so simple) to do it automatically without specifying each jar one by one :
<path id="build.classpath">
<fileset dir="${basedir}"/>
<include name="lib/*.jar"/>
</fileset>
</path>
<pathconvert property="manifest.classpath" pathsep=" ">
<path refid="build.classpath"/>
<mapper>
<chainedmapper>
<flattenmapper/>
<globmapper from="*.jar" to="lib/*.jar"/>
</chainedmapper>
</mapper>
</pathconvert>
<target depends="compile" name="buildjar">
<jar jarfile="${basedir}/${test.jar}">
<fileset dir="${build}" />
<manifest>
<attribute name="MainClass" value="com.mycompany.TestMain"/>
<attribute name="ClassPath" value="${manifest.classpath}"/>
</manifest>
</jar>
</target>
Latest Ant version (1.7) includes a task called ManifestClassPath which converts a classpath into
a spaceseparated list of items used to set the Manifest ClassPath attribute. See
http://ant.apache.org/manual/CoreTasks/manifestclasspath.html
<path id="buildclasspath">
<fileset dir="${build.dir}">
<include name="*.jar"/>
</fileset>
</path>
<manifestclasspath property="lib.list" jarfile="${build.dir}/${jar.file}">
<classpath refid="buildclasspath" />
</manifestclasspath>
4.75 JDK6
<jar>
...
<manifest>
<attribute name="MainClass" value="com.mycompany.TestMain"/>
<attribute name="ClassPath" value=". ${lib.list}"/>
</manifest>
...
</jar>
java.applet.*;
java.awt.event.*;
java.awt.*;
netscape.javascript.*;
4.77 Detect browser type from an AppletTag(s): Applet Environment Javascript interaction
Don't forget the MAYSCRIPT parameter in the APPLET tag, it's required since the Applet is using
the JSObject to interact with the Javascript.
<html>
<head>
<script>
function getUserAgent() {
return navigator.userAgent;
}
</script>
</head><body>
<applet code="GetUserAgent.class" MAYSCRIPT height=100 width=500></Applet>
</body>
</html>
Try it here
You need to parse the returned value to detect browser type. Look at this utility,
http://code.google.com/p/useragentutils/ or at this code :
http://nerds.palmdrive.net/useragent/code.html to get the idea.
<HTML><HEAD></HEAD><BODY>
<APPLET CODE="MyApplet.class"
NAME="myApplet"
HEIGHT=400 WIDTH=400 ALT="Oups! You don't have JAVA enabled">
<A HREF="nojava.html">Oups! You don't have JAVA enabled, click here.</A>
</APPLET>
</BODY></HTML>
4.81 See the Java Console Window Log (Java plugin)Tag(s): Applet Environment
5 Internationalization
5.1 javainter
javax.swing.*;
java.awt.*;
java.awt.event.*;
java.util.*;
java.text.*;
5 Internationalization
add(aButton);
// Number format output
double dn = 3.1416;
nf = (NumberFormat)
(MyResources.rb.getObject("aNumber"));
aTextField = new JTextField(6);
add(aTextField);
aTextField.setText(nf.format(dn));
// Number input validation
vButton =
(JButton)MyResources.rb.getObject("vButton");
add(vButton);
vButton.addActionListener(this);
vLabel = new JLabel("validation message ...");
add(vLabel);
setSize(400,400);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == vButton) {
try {
nf.parse(aTextField.getText());
vLabel.setText(MyResources.rb.getString("numOK"));
vLabel.invalidate();
this.validate();
}
catch (ParseException pe) {
pe.printStackTrace();
vLabel.setText(MyResources.rb.getString("numERR"));
vLabel.invalidate();
this.validate();
}
}
}
public static void main(String args[]) {
System.out.println("Current Local : " + Locale.getDefault());
Thread t = new Thread () {
public void run() {
International frame = new International();
frame.initGUI();
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(t);
}
}
5 Internationalization
import java.util.*;
public class MyResources_en extends ListResourceBundle {
public Object [][] getContents() {
return contents;
}
static final Object[][] contents = {
{ "aLabel"
, "a Label (en)" }
};
}
5 Internationalization
This example uses ListResourceBundle classes to store the required resources. It is possible to
substitute them for Properties files without any change to the code. The properties files must have
the .properties extension.
See this Howto.
java.util.*;
java.text.*;
java.awt.*;
java.awt.event.*;
javax.swing.*;
}
public void initText() {
setTitle (rb.getString("title"));
r0.setText(rb.getString("r0"));
r1.setText(rb.getString("r1"));
r2.setText(rb.getString("r2"));
btnQuit.setText(rb.getString("btnQuit"));
Date d = new Date();
MessageFormat mf = new MessageFormat
(rb.getString("today"), localeCurrent);
today.setText(mf.format(new Object [] { d }));
}
public void initGUI(){
setLayout(new FlowLayout());
// RADIO buttons
bg = new ButtonGroup();
r0 = new JRadioButton();
r1 = new JRadioButton();
r2 = new JRadioButton();
bg.add(r0);
bg.add(r1);
bg.add(r2);
add(r0);
add(r1);
add(r2);
// default RADIO button
if (!defaultDone) {
String rDef = rb.getString("rDefault");
if (rDef.equals("r0"))
r0.setSelected(true);
else if (rDef.equals("r1"))
r1.setSelected(true);
else
r2.setSelected(true);
defaultDone = true;
}
else {
if (localeChoosen == 0)
r0.setSelected(true);
else if (localeChoosen == 1)
r1.setSelected(true);
else
r2.setSelected(true);
}
// QUIT button
btnQuit = new JButton();
add(btnQuit);
// today label
today = new JLabel();
add(today);
//
r0.addActionListener(this);
r1.addActionListener(this);
r2.addActionListener(this);
btnQuit.addActionListener(this);
setSize(400,100);
setVisible(true);
}
public void actionPerformed(ActionEvent ae){
if (ae.getSource() == btnQuit) {
System.exit(0);
}
else if (ae.getSource() == r0) localeChoosen = 0;
else if (ae.getSource() == r1) localeChoosen = 1;
else if (ae.getSource() == r2) localeChoosen = 2;
initLocale();
initText();
pack();
}
public static void main(String args[]) {
System.out.println("Current Locale : " + Locale.getDefault());
Thread t = new Thread () {
public void run() {
InternationalDynamic i = new InternationalDynamic();
i.initLocale();
i.initGUI();
i.initText();
i.pack();
}
};
SwingUtilities.invokeLater(t);
}
}
{
{
{
{
{
{
};
With the previous JAVA Howto, the resources were stored in classes. The drawback is when there
is a modification, we must recompile the class. With a resources file, we simply add or modify the
resource in a special file with a regular text editor. The JDK provides a class,
PropertyResourceBundle, to use properties file very easily. In fact, from the programmer's point of
view, there is no difference if the resources are stored in classes or properties files.
The ResourceBundle will look first for classes and if not found, it will look for properties files. We
don't have to specify filenames, the ResourceBundle will construct the filename using the same
mechanism used for classes. The file must have the extension .properties.
The ResourceBundle try to load the properties file from the current classpath.
If the properties are stored in subdirectory , use "." instead of "/".
For example, let's say that the properties file is in a subdirectory called "subdir" (from the current
directory). Then you can load the ResourcesDynamic resources file with
ResourceBundle.getBundle("subdir.ResourcesDynamic", localeCurrent);
[InternationalDynamic.java]
import
import
import
import
import
java.util.*;
java.text.*;
java.awt.*;
java.awt.event.*;
javax.swing.*;
// QUIT button
btnQuit = new JButton();
add(btnQuit);
// today label
today = new JLabel();
add(today);
//
r0.addActionListener(this);
r1.addActionListener(this);
r2.addActionListener(this);
btnQuit.addActionListener(this);
setSize(400,100);
setVisible(true);
}
public void actionPerformed(ActionEvent ae){
if (ae.getSource() == btnQuit) {
System.exit(0);
}
[RresourcesDynamic.properties]
title=Example
r0=United States
r1=France
r2=Germany
rDefault=r0
btnQuit=Quit
today=(def) {0,date,long}
[RresourcesDynamic_en.properties]
title=Example
r0=United States
r1=France
r2=Germany
rDefault=r0
btnQuit=Quit
today=(en) {0,date,long}
[ResourcesDynamic_fr.properties]
title=Exemple
r0=EtatsUnis
r1=France
r2=Allemagne
rDefault=r1
btnQuit=Quitte
today=(fr) {0,date, dd/MM/yyyy}
[ResourcesDynamic_de.properties]
title=Beispiel
r0=Vereinigte Staaten
r1=Frankreich
r2=Deutschland
rDefault=r2
btnQuit=Verlassen
today=(de) {0,date,dd.MM.yyyy}
For example :
import java.awt.*;
public class TestUnicode extends java.applet.Applet {
public static final String COPYRIGHT = "\u00a9";
public static final String REGISTERED = "\u00ae";
public static final String EURO = "\u20ac";
public void init () {
setLayout(new FlowLayout());
Label a = new Label(COPYRIGHT + " R\u00e9al Gagnon");
Label b = new Label(REGISTERED + " R\u00e9al's Software "
+ " price : 100 " + EURO);
add(a);
add(b);
}
}
Output :
Java not enabled!
A list of Unicode characters is available at the Unicode organization Web site.
Here a quick list for accented letters :
\u00e0 \u00c0
\u00e1 \u00c1
\u00e2
\u00e9
\u00e8
\u00ea
\u00ee
\u00e7
\u00c2
\u00c9
\u00c8
\u00ca
\u00ce
\u00c7
Then
import
import
import
import
javax.swing.*;
java.awt.event.*;
java.awt.*;
java.util.*;
System.out.println(result);
}
}
public Dimension getPreferredSize(){
return new Dimension(200, 200);
}
public static void main(String s[]) {
JFrame frame = new JFrame("");
MessageBoxExample panel = new MessageBoxExample();
frame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
frame.getContentPane().add(panel,"Center");
frame.setSize(panel.getPreferredSize());
frame.setVisible(true);
}
}
{
// use the default locale
return convertStringAsStringNumberUnLocalized(Locale.getDefault(), value);
}
public static String convertStringAsStringNumberUnLocalized
(Locale loc, String value)
throws ParseException
{
double d = NumberUtils.getDoubleValue(loc, value);
return NumberFormat.getInstance(new Locale("us")).format(d);
}
[JFileChooser_fr.properties]
Title=JFileChooser de R\u00e9al
lookInLabelText=Courant
filesOfTypeLabelText=Type de fichier
upFolderToolTipText=Remonte
Then
[LocalizeJFileChooser.java]
import
import
import
import
javax.swing.*;
java.awt.event.*;
java.awt.*;
java.util.*;
locale = Locale.US;
}
public void setUILanguage() {
ResourceBundle rb;
rb = ResourceBundle.getBundle("JFileChooser", locale);
z_choosertitle = rb.getString("Title");
UIManager.put
("FileChooser.lookInLabelText",
rb.getString("lookInLabelText"));
UIManager.put
("FileChooser.filesOfTypeLabelText",
rb.getString("filesOfTypeLabelText"));
UIManager.put
("FileChooser.upFolderToolTipText",
rb.getString("upFolderToolTipText"));
/*
do the same with :
FileChooser.fileNameLabelText
FileChooser.homeFolderToolTipText
FileChooser.newFolderToolTipText
FileChooser.listViewButtonToolTipTextlist
FileChooser.detailsViewButtonToolTipText
FileChooser.saveButtonText=Save
FileChooser.openButtonText=Open
FileChooser.cancelButtonText=Cancel
FileChooser.updateButtonText=Update
FileChooser.helpButtonText=Help
FileChooser.saveButtonToolTipText=Save
FileChooser.openButtonToolTipText=Open
FileChooser.cancelButtonToolTipText=Cancel
FileChooser.updateButtonToolTipText=Update
FileChooser.helpButtonToolTipText=Help
Almost all Swing widgets can be customize this way. You can
examine the Swing sources to get these values or check
http://www.gargoylesoftware.com/papers/plafdiff.html for
a list of them.
*/
}
public void actionPerformed(ActionEvent e) {
int result;
if (e.getSource() instanceof JRadioButton) {
if (e.getActionCommand().equals("en"))
locale = Locale.US;
else
locale = Locale.FRANCE;
setUILanguage();
}
else {
z_chooser = new JFileChooser();
z_chooser.setCurrentDirectory(new java.io.File("."));
z_chooser.setDialogTitle(z_choosertitle);
if (z_chooser.showOpenDialog(this) !=
JFileChooser.APPROVE_OPTION)
return;
}
}
public Dimension getPreferredSize(){
return new Dimension(200, 200);
}
public static void main(String s[]) {
JFrame frame = new JFrame("");
LocalizeJFileChooser panel = new LocalizeJFileChooser();
frame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
frame.getContentPane().add(panel,"Center");
frame.setSize(panel.getPreferredSize());
frame.setVisible(true);
}
}
[standard_fr.properties (extract)]
doclet.Window_Split_Index={0}\: {1}Index
doclet.Packages=Paquetages
doclet.SerialData=Donn\u00E9e s\u00E9rialis\u00E9e\:
doclet.Since=Depuis\:
doclet.Warn_inline_taglet=Inline tag {0} should only be used with a {1}.
doclet.ClassUse_Subinterface=Sousinterfaces de {0} dans {1}
doclet.Frame_Version=Version avec cadres
doclet.Generated_Docs_Untitled=Documentation g\u00E9n\u00E9r\u00E9e
Once everything translated, put your standard_fr.properties into the tools.jar making sure that the
file is located in the right package (along standard.properties in
com.sun.tools.doclets.standard.resources).
To generate in french, use the locale switch on the command line
javadoc locale fr ....
Case insensitive
java.util.Arrays.sort(myArray, String.CASE_INSENSITIVE_ORDER);
else {
return System.console().writer();
}
}
}
The output is :
Before :
Ral Real Raoul Rico
After :
Raoul Real Rico Ral
by
java.util.Arrays.sort(words, java.text.Collator.getInstance(java.util.Locale.FRENCH));
// or
// java.util.Arrays.sort(words, java.text.Collator.getInstance());
In this code, we have 2 strings, "tat" and "famille". We expect that "tat" is before "famille". But
String.compareTo() will return that "famille" is before "tat".
class Test {
public static void main(String args[]) {
String s1 = "tat";
String s2 = "famille";
// here we are expecting "" < "f"
if (s1.compareTo(s2) > 0) {
if (s1.compareTo(s2) > 0) {
// s1 lexicographically follows s2 which is not true!
Equality
To compare without taking into account the presence of accentued so that "" == "e", we use a
Collator.
import java.text.Collator;
// import java.util.Locale;
public class TextTest {
public static void main(String ... args) {
String a = "Real";
String b = "Ral";
System.out.println(a + " and " + b + " equals? " +
check(a,b));
/*
* output :
* Real and Ral equals? true
*/
}
}
}
=
=
=
=
=
s.replaceAll("[]","e");
s.replaceAll("[]","u");
s.replaceAll("[]","i");
s.replaceAll("[]","a");
s.replaceAll("","o");
s
s
s
s
s
=
=
=
=
=
s.replaceAll("[]","E");
s.replaceAll("[]","U");
s.replaceAll("[]","I");
s.replaceAll("[]","A");
s.replaceAll("","O");
System.out.println(s);
// output : E,E,E,E,U,U,I,I,A,A,O,e,e,e,e,u,u,i,i,a,a,o
}
}
As a bonus, here a method to convert a given string to uppercase with no accent. This can be
useful in a database field to simplify name searching with accent or not.
C:\temp>java Test
caractres franais :
caractres franais :
}
}
See also java encoding table for the encoding sets supported.
r.close();
System.exit(0);
}
}
java.nio.ByteBuffer;
java.nio.CharBuffer;
java.nio.charset.Charset;
java.nio.charset.CharsetDecoder;
java.nio.charset.CharacterCodingException;
A different (and simpler) approach is to take a given string and check if it's possible to encode it into
ASCII.
5.21 Detect nonASCII character in a StringTag(s): Internationalization String/Number
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
public class StringUtils {
static CharsetEncoder asciiEncoder =
Charset.forName("USASCII").newEncoder(); // or "ISO88591" for ISO Latin 1
public static boolean isPureAscii(String v) {
return asciiEncoder.canEncode(v);
}
public static void main (String args[])
throws Exception {
String test = "Ral";
System.out.println(test + " isPureAscii() : " + StringUtils.isPureAscii(test));
test = "Real";
System.out.println(test + " isPureAscii() : " + StringUtils.isPureAscii(test));
/*
* output :
*
Ral isPureAscii() : false
*
Real isPureAscii() : true
*/
}
}
Another way is to use a regular expression, see this Javascript HowTo for a hint!
To simply strip any nonascii characters form a string
public class Test {
public static void main(String args[]){
String input = "ea";
String output = input.replaceAll("[^\\p{ASCII}]", "");
System.out.println(output);
/*
* output : ea
*/
}
}
5.22 Get the month (or day) name (localized)Tag(s): Date and
Time Internationalization
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java0650.html
import java.text.DateFormatSymbols;
import java.util.Locale;
5.22 Get the month (or day) name (localized)Tag(s): Date and Time Internationalization
5.22 Get the month (or day) name (localized)Tag(s): Date and Time Internationalization
6 IO
6.1 javaio
6 IO
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
return "\r\n" + sw.toString() + "\r\n";
}
catch(Exception e2) {
return "bad stack2string";
}
}
}
You may want to suppress output done with the regular System.out but maintain the ability to write
to the original streams directly when necessary.
// Keep a copy of the original out stream.
PrintStream original = new PrintStream(System.out);
// replace the System.out, here I redirect to NUL (for demonstration)
System.setOut(new PrintStream(new FileOutputStream("NUL:")));
System.out.println("bar"); // no output
// The original stream is still available
original.println("foo"); // output to stdout
java.io.ByteArrayInputStream;
java.io.IOException;
java.io.InputStream;
java.io.File;
java.io.FileInputStream;
import
import
import
import
import
import
import
javax.print.Doc;
javax.print.DocFlavor;
javax.print.DocPrintJob;
javax.print.PrintException;
javax.print.PrintService;
javax.print.PrintServiceLookup;
javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.event.PrintJobAdapter;
import javax.print.event.PrintJobEvent;
public class PrintTextFile {
public static void main(String[] args) throws PrintException, IOException {
String defaultPrinter =
PrintServiceLookup.lookupDefaultPrintService().getName();
System.out.println("Default printer: " + defaultPrinter);
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
FileInputStream in = new FileInputStream(new File("c:/temp/foo.txt"));
PrintRequestAttributeSet
pras.add(new Copies(1));
javax.print.Doc;
javax.print.DocFlavor;
javax.print.DocPrintJob;
javax.print.PrintException;
javax.print.PrintService;
javax.print.PrintServiceLookup;
javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.event.PrintJobAdapter;
import javax.print.event.PrintJobEvent;
public class PrintText {
public static void main(String[] args) throws PrintException, IOException {
String defaultPrinter =
PrintServiceLookup.lookupDefaultPrintService().getName();
System.out.println("Default printer: " + defaultPrinter);
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
// prints the famous hello world! plus a form feed
InputStream is = new ByteArrayInputStream("hello world!\f".getBytes("UTF8"));
PrintRequestAttributeSet
pras.add(new Copies(1));
allDone();
}
public void printJobNoMoreEvents(PrintJobEvent pje) {
allDone();
}
void allDone() {
synchronized (PrintJobWatcher.this) {
done = true;
System.out.println("Printing done ...");
PrintJobWatcher.this.notify();
}
}
});
}
public synchronized void waitForDone() {
try {
while (!done) {
wait();
}
} catch (InterruptedException e) {
}
}
}
try {
p = rt.exec( cmd );
if( p.waitFor() != 0 ) {
System.out.println("Error executing command: " + cmd );
System.exit( 1 );
}
byte data[] =
"Writing a byte stream out of a serial port.".getBytes();
FileOutputStream fos = new FileOutputStream( portname );
BufferedOutputStream bos = new BufferedOutputStream( fos );
fos.write( data, 0, data.length );
fos.close();
}
catch( Exception e ) {
e.printStackTrace();
}
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
public static void close(String drive) {
try {
File file = File.createTempFile("realhowto",".vbs");
file.deleteOnExit();
FileWriter fw = new FileWriter(file);
// to close a CD, we need eject two times!
String vbs = "Set wmp = CreateObject(\"WMPlayer.OCX\") \n"
+ "Set cd = wmp.cdromCollection.getByDriveSpecifier(\""
+ drive + "\") \n"
+ "cd.Eject \n "
+ "cd.Eject ";
fw.write(vbs);
fw.close();
Runtime.getRuntime().exec("wscript " + file.getPath()).waitFor();
// thanks to TrueJavaProgammer for the waitFor() tip!
// Runtime.getRuntime().exec("wscript "+ file.getPath());
// Thread.sleep(2000);
}
catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args){
javax.swing.JOptionPane.showConfirmDialog((java.awt.Component)
null, "Press OK to open CD", "CDUtils",
javax.swing.JOptionPane.DEFAULT_OPTION);
CDUtils.open("D:\\");
javax.swing.JOptionPane.showConfirmDialog((java.awt.Component)
null, "Press OK to close CD", "CDUtils",
javax.swing.JOptionPane.DEFAULT_OPTION);
CDUtils.close("D:\\");
}
}
NOTE : Windows Media Player version 7 or later is required
private VolumeLabel() { }
public static void main(String[] args) {
System.out.println("\"" + get(args[0]) + "\"");
}
public static String get(String path) {
FileSystemView view = FileSystemView.getFileSystemView();
File dir = new File(path);
String name = view.getSystemDisplayName(dir);
if (name == null) { return null; }
name = name.trim();
if (name == null || name.length() < 1) {
return null;
}
int index = name.lastIndexOf(" (");
if (index > 0) {
name = name.substring(0, index);
}
return name;
}
}
The output
Running from c:\temp
>java VolumeLabel c:
"temp"
>java VolumeLabel c:\
"HARDDISK1"
java.io.File;
java.util.Arrays;
java.util.List;
javax.swing.filechooser.FileSystemView;
java.io.File;
java.util.Arrays;
java.util.List;
javax.swing.filechooser.FileSystemView;
java.io.BufferedWriter;
java.io.FileDescriptor;
java.io.FileOutputStream;
java.io.OutputStreamWriter;
The result is
>java Test >NUL
Loop time: 7000
Now, rewrite this program to use a 512bytes buffer and specify the ASCII as
characterencoding to be used.
6.14 Get faster console output (System.out.println() replacement)Tag(s): IO
import
import
import
import
java.io.BufferedWriter;
java.io.FileDescriptor;
java.io.FileOutputStream;
java.io.OutputStreamWriter;
The result is
>java Test >NUL
Loop time: 672
Note that your result will vary depending on your machine/java version but the performance gain
should in the same magnitude.
NOTE: JDK 1.5 provides the Scanner class to do this, see this HowTo.
6.20 Jansi
Jansi is a small java library that allows you to use ANSI escape sequences to format your console
output which works even on Windows.
import org.fusesource.jansi.AnsiConsole;
public class Test {
public static final
public static final
public static final
public static final
public static final
public static final
public static final
String
String
String
String
String
String
String
ANSI_CLS = "\u001b[2J";
ANSI_HOME = "\u001b[H";
ANSI_BOLD = "\u001b[1m";
ANSI_AT55 = "\u001b[10;10H";
ANSI_REVERSEON = "\u001b[7m";
ANSI_NORMAL = "\u001b[0m";
ANSI_WHITEONBLUE = "\u001b[37;44m";
}
}
NOTE: Check this "old" text file to have an overview of ANSI Escape Sequences.
The above example shows that it's possible to use ANSI codes directly but Jansi provides a neat
mechanism to help building the required ANSI sequence.
import static org.fusesource.jansi.Ansi.*;
import static org.fusesource.jansi.Ansi.Color.*;
...
System.out.println( ansi().eraseScreen().fg(RED).a("Hello").fg.(GREEN).a(" World").reset()
6.21 JCurses
The Java Curses Library (JCurses) is a library for developing text terminal based applications
using Java programming language. It is implemented as a Windowing toolkit similar to AWT, but
built upon the UNIX "curses" windowing system.
JCurses works on Unix and Windows (32 bit only, on a 64bit OS you need to use JCurses with a
32bit JVM).
This example will display a characterbased window with a label, a textfield and a button (don't
click with you mouse, use the keyboard!).
import
import
import
import
jcurses.system.*;
jcurses.widgets.*;
jcurses.util.*;
jcurses.event.*;
6.21 JCurses
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches
whitespace. The resulting tokens may then be converted into values of different types using the
various next methods.
6.22 Easy keyboard input (JDK1.5)Tag(s): IO
import java.util.Scanner;
class TestScanner {
public static void main(String args[]) {
// if input is
//
10,12
// then the output is
// 10
// 12
//
// we use a regex as delimiter to combine "," and
// whitespace (in this case the ENTER key)
Scanner sc = new Scanner(System.in).useDelimiter("[,\\s]");
while (sc.hasNextInt()) {
int i = sc.nextInt();
System.out.println(i);
}
System.out.println("Done");
}
}
Scanner can be used with String or Stream. For exemple, the above HowTo can be written like
this :
import java.util.Scanner;
class TestScanner {
public static void main(String args[]) {
String input = "10,12"
Scanner sc = new Scanner(System.in).useDelimiter(",");
while (sc.hasNextInt()) {
int i = sc.nextInt();
System.out.println(i);
}
System.out.println("Done");
}
}
NOTE : This technique changes the keyboard state so the effect is also seen outside the Java
program.
See also this related Howto.
super.println(s.toUpperCase());
}
});
System.out.println("hello world"); // output :
HELLO WORLD
}
}
Replace the regular output stream of System.out to do useful thing like implementing a Tee
mechanism to output to the console and to file.
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
public class TeeOutputStream extends OutputStream {
private OutputStream os1;
private OutputStream os2;
public TeeOutputStream(OutputStream os1, OutputStream os2) {
this.os1 = os1;
this.os2 = os2;
}
public void write(int i) throws IOException {
os1.write(i);
os2.write(i);
}
public void flush() throws IOException {
os1.flush();
os2.flush();
}
public void close() throws IOException {
os1.close();
os2.close();
}
public static void main(String[] args) throws IOException {
System.out.println("Starting...");
// keep the original
PrintStream originalOutStream = System.out;
System.setOut(
new PrintStream(
new TeeOutputStream(
System.out,
new PrintStream("C:/temp/howto.out"))));
// restore the original
System.out.println("*");
for (int i = 1; i<= 10; i++) {
System.out.println(i);
}
System.out.println("*");
System.setOut(originalOutStream);
System.out.println("Done. Check the log");
}
}
The next example, launch CMD.EXE, grab stdin/stdout and push to stdin command to be
interpreted by the shell.
String line;
OutputStream stdin = null;
InputStream stderr = null;
InputStream stdout = null;
// launch EXE and grab stdin/stdout and stderr
Process process = Runtime.getRuntime ().exec ("/folder/exec.exe");
stdin = process.getOutputStream ();
stderr = process.getErrorStream ();
stdout = process.getInputStream ();
6.27 Launch a Windows CMD (or BAT) file and retrieve the
errorlevel or exitcode
// win xp
import java.io.*;
public class CmdExec {
public static void main(String argv[]) {
try {
String line;
Process p = Runtime.getRuntime().exec("test.cmd");
p.waitFor();
System.out.println(p.exitValue());
}
catch (Exception err) {
err.printStackTrace();
}
}
}
6.27 Launch a Windows CMD (or BAT) file and retrieve the errorlevel or exitcode
See also this HowTo about the new Desktop API, the recommended solution (but you need
JDK1.6).
See also this one to open the default browser.
6.28 Launch a Unix script
If you need to pass arguments, it's safer to a String array especially if they contain spaces.
String[] cmd = { "myProgram.exe", "o=This is an option" };
Runtime.getRuntime().exec(cmd);
If using the start command and the path of the file to be started contains a space then you must
specified a title to the start command.
String fileName = "c:\\Applications\\My Documents\\test.doc";
String[] commands = {"cmd", "/c", "start", "\"DummyTitle\"",fileName};
Runtime.getRuntime().exec(commands);
6.34 VBSCRIPT
// Win9x
Runtime.getRuntime().exec("start myscript.vbs");
// WinNT
Runtime.getRuntime().exec("cmd /c start myscript.vbs");
or
// with a visible console
Runtime.getRuntime().exec("cscript myscript.vbs");
// with no visible console
Runtime.getRuntime().exec("wscript myscript.vbs");
To load a worksheet
import java.io.IOException;
class StartExcel {
public static void main(String args[])
throws IOException
{
String fileName = "c:\\temp\\xls\\test2.xls";
String[] commands = {"cmd", "/c", "start", "\"DummyTitle\"",fileName};
Runtime.getRuntime().exec(commands);
}
}
6.34 VBSCRIPT
It's important to pass a dummy title to the Windows start command where there is a possibility
that the filename contains a space. It's a feature.
/SaveCred option allows you to save a password for that account and then reuse it later. For
example, The command runas /savecred /user:administrator regedit.exe prompts
for the password, and then Regedit runs. Next time you use the same command, there is no
password prompt.
One potential problem is that when /SaveCred saves the credentials it saves it for whenever
RUNAS invokes that user account. This can be a huge security risk so be careful using it!
RUNAS capability can be disabled by editing the Registry or by disabling the RUNAS or
Secondary Logon Services. The appropriate registry key is
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explorer, create a
new DWORD value named HideRunAsVerb and assign it a value of 1 to disable Run as.
RUNAS doesn't work when used from a Windows service.
+ FILE_SEPARATOR + "textpad.exe"};
Runtime.getRuntime().exec(commands);
}
}
NOTE : Prior Vista, System folders were localized on disk like C:\Program Files > C:\Archivos de
programa on the Windows with the Spanish localization. Since Vista, System Folders always
exists with the english name BUT when viewed through Explorer, the localized name is shown.
See
http://msmvps.com/blogs/carlosq/archive/2007/02/12/windowsvistajunctionspointsmuiandlocalized
Launch many programs using Thread and use join() to wait for the completion.
[Program2.java]
public class Program2 {
public static void main(String arg[]) {
System.out.println("Hello from Program2");
System.out.println("Hello from Program2");
System.out.println("Hello from Program2");
System.out.println("Hello from Program2");
}
}
[Program1a.java]
public class Program1a {
public static void main(String a