Real's HowTo PDF version.

This is the PDF version of the Real's HowTo Web site ( http://www.rgagnon.com/howto.html ). For up−to−date 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 How−to'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 real@rgagnon.com 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 ( real@rgagnon.com ) 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 HowTo@www.rgagnon.com
1 Applet..............................................................................................................................................1 . 1.1 java−applet........................................................................................................................1 1.2 Goto to a new URL from an Applet....................................................................................1 1.3 Determine the host from where the Applet is loaded.........................................................3 1.4 Have a scrolling status line................................................................................................3 1.5 Use a search engine..........................................................................................................5 1.6 Have an on−screen clock..................................................................................................6 1.7 Have Applets on the same page communicate with each other........................................8 1.8 Have Applets on different frames communicates with each other.....................................9 1.9 Send a message from an Applet to another Applet on a different page..........................10 1.10 Have an applet launch an other applet..........................................................................12 1.11 Get the user name.........................................................................................................14 1.12 Access parameters passed in the URL ..........................................................................14 1.13 Convert an Applet to Application ....................................................................................16 1.14 Change the mouse cursor in Applet..............................................................................17 . 1.15 Use an Image as the Applet background.......................................................................17 1.16 Handle the new Control Activation mechanism in IE.....................................................18 1.16.1 Solution #1............................................................................................................19 1.16.2 Solution #2............................................................................................................19 1.16.3 Solution #3............................................................................................................20 1.17 Pass parameters to the Applet JVM (WIN)....................................................................21 1.18 See the Java Console Window Log (Java plugin).........................................................22 1.19 Display debugging infos for an Applet...........................................................................23 2 Date and Time...............................................................................................................................24 2.1 java−date.........................................................................................................................24 2.2 Have year on 4 digits from a Date object.........................................................................24 2.3 Get the current Date and Time........................................................................................24 2.4 Compute days between 2 dates......................................................................................25 2.5 Get the number of days in a month ..................................................................................26 2.6 Validate a date.................................................................................................................26 2.6.1 Using DateFormat...................................................................................................26 2.6.2 Using GregorianCalendar.......................................................................................28 2.7 Determine to day of the week..........................................................................................28 2.8 Add/Substract Day/Month/Year to a Date........................................................................28 2.9 Get the correct TimeZone on DateFormat.......................................................................29 2.10 Simply format a date as "YYYYMMDD".........................................................................30 2.11 Compare 2 dates...........................................................................................................30 2.12 Parse a String to obtain a Date/GregorianCalendar object ...........................................31 . 2.13 Use System time to generate unique ID........................................................................32 2.14 Get the day name..........................................................................................................32 2.15 Find the current date format..........................................................................................33 . 2.16 Get a julian date.............................................................................................................33 2.17 Calculate the age...........................................................................................................35 2.18 Format a duration in ms into a string as "Days,Hours,minutes and seconds"...............36 2.19 Get the atomic time........................................................................................................38 3 AWT ................................................................................................................................................40 3.1 java−awt ..........................................................................................................................40 . 3.2 Use The CardLayout manager........................................................................................40 .

3.3 Detect which card is visible with a CardLayout

Real's HowTo@www.rgagnon.com
3 AWT 3.3 Detect which card is visible with a CardLayout................................................................42 3.4 Use Popups.....................................................................................................................42 3.5 Use a File Dialog ..............................................................................................................44 3.6 Use TrueType font...........................................................................................................45 3.7 Display available fonts.....................................................................................................46 3.8 Font with 3D effect...........................................................................................................47 3.9 Use the System Clipboard...............................................................................................47 3.10 Maximize a Frame.........................................................................................................48 3.11 Center a Frame/Dialog ...................................................................................................49 3.12 Close a Frame...............................................................................................................50 3.13 Call events on a Frame from a Panel............................................................................51 3.14 Set the small top−left icon on a Frame..........................................................................53 3.15 Prevent a Frame to be resized .......................................................................................54 3.16 Embed an image into a Frame .......................................................................................55 3.17 Display a message box..................................................................................................57 3.18 Display a Splash screen................................................................................................58 3.19 Limit TextField input to numeric value...........................................................................60 3.20 Limit TextField input to a maximum length....................................................................62 3.21 React to the ENTER key in a Textfield..........................................................................62 3.22 Make the ENTER key act like the TAB key ....................................................................63 3.23 Reset all textfields in one shot.......................................................................................64 3.24 Limit a TextField to Uppercase......................................................................................65 3.25 Have an ImageButton....................................................................................................66 3.26 Reset a checkbox group................................................................................................69 3.27 Set the listbox width.......................................................................................................69 3.28 Align the column in a List...............................................................................................70 3.29 Have a srolling text display............................................................................................70 3.30 Label dynamic resizing..................................................................................................71 3.31 Make a TextArea "word−wrap"......................................................................................73 3.32 Synchronize a TextArea vs a Choice.............................................................................73 3.33 Display underlined text..................................................................................................73 . 3.34 Display vertical text........................................................................................................74 3.35 Have Label with many lines...........................................................................................75 3.36 Have a Label with underlined text..................................................................................79 3.37 Have a Label acting as HTML HREF (URLLabel).........................................................80 3.38 Display a GIF in a Canvas.............................................................................................81 3.39 Embed an image into a Frame .......................................................................................82 3.40 Load several images from a single GIF.........................................................................84 3.41 Load an Image from a JAR file......................................................................................85 3.42 Load an Icon from a jar (again)......................................................................................86 3.43 Scale an Image..............................................................................................................87 3.44 Fade an image...............................................................................................................88 3.45 Rotate an image .............................................................................................................90 3.46 Create a scrollable canvas .............................................................................................92 3.47 Use an Image as the Applet background.......................................................................96 3.48 Have a simple Image browser.......................................................................................97 3.49 Simulate a "mouse over" event to toggle an image.....................................................100 3.50 Hide the mouse cursor.................................................................................................101 3.51 Make a color transparent.............................................................................................102

Real's HowTo@www.rgagnon.com
3 AWT 3.52 Save an Image as a GIF or JPEG file..........................................................................103 3.53 Use the same background color as the browser .........................................................104 . 3.54 Do simple animation using Images..............................................................................105 3.55 Do simple animation to show "work in progress".........................................................106 3.56 Get the color of a specific pixel....................................................................................107 3.57 Do "rubber−band" drawing ...........................................................................................108 3.58 Convert RGB value to Hexadecimal (to be used in HTML for example) .....................110 . 3.59 Draw a line or set a pixel in my own image ..................................................................110 3.60 Draw a dashed line......................................................................................................111 3.61 Draw a line with a thickness .........................................................................................112 3.62 Draw a pie chart...........................................................................................................114 3.63 Draw faster rectangles.................................................................................................116 3.64 Get a screen capture and save it as a JPEG...............................................................117 3.65 Display a TIF................................................................................................................117 3.66 Convert a multi−page TIF into single−page TIF ...........................................................119 3.67 Convert an Image to a BufferedImage.........................................................................120 3.68 Detect a double click vs simple click............................................................................121 3.69 Detect the mouse button used when clicking ...............................................................122 3.70 Exit an application from a menu ...................................................................................123 3.71 Trigger a click on a Button...........................................................................................124 4 Environment ................................................................................................................................126 4.1 java−env........................................................................................................................126 4.2 Read environment variables from an application...........................................................126 4.3 Retrieve environment variables (JDK1.5)......................................................................130 4.4 Retrieve environment variable (JNI)..............................................................................130 4.5 Use a MAKE file.............................................................................................................131 4.6 Detect the browser/JVM type.........................................................................................132 4.7 Fix the "Wrong magic number" error message..............................................................134 4.8 Use a precompiler "à la C" with Java.............................................................................134 4.9 Determine what are the classes actually used in a Java Applet or application ..............134 4.10 Set the memory available to the JVM..........................................................................135 4.11 Generate the Javadoc "en français"............................................................................135 4.12 Use JDK1.5 new features............................................................................................136 4.13 Check the class version...............................................................................................137 4.14 Get the system properties or the JVM uptime ..............................................................138 4.15 Detect if running in a 64bit JVM...................................................................................139 4.16 Set the default JVM type..............................................................................................139 4.17 Capture the output of JAVAC .......................................................................................140 4.18 Freeze the JVIEW window in MS VJ++.......................................................................141 4.19 Know details about the JAVA at run−time...................................................................141 4.20 Detect the Microsoft JVM version installed..................................................................143 4.21 Run JAVA as a Windows service .................................................................................143 4.22 Execute a class from Windows Explorer .....................................................................143 . 4.23 Create an icon to launch java apps for Windows?.......................................................145 4.24 Fix the "out of environment" error when setting a new CLASSPATH..........................145 4.25 Query Windows registry...............................................................................................146 4.26 Quickly retrieve available Java JVM on a workstation (Windows)...............................148 4.27 Get the Windows "My Documents" path......................................................................149

4.28 Get a return code from a VBS

Real's HowTo@www.rgagnon.com
4 Environment 4.28 Get a return code from a VBS ......................................................................................150 4.29 List currently running processes (Windows)................................................................151 4.29.1 Using TASKLIST.EXE .........................................................................................151 4.29.2 Using a VBS ........................................................................................................152 4.30 Windows registry vs. Java JDK/JRE installation..........................................................153 4.31 Use a JAR/ZIP/CAB file with an Applet.......................................................................154 . 4.32 Make ZIP/JAR file always accessible from applet.......................................................156 4.33 Make a JAR executable...............................................................................................156 4.34 Accessing jars from within a jar...................................................................................157 4.35 Access a JAR outside the CLASSPATH ......................................................................158 4.36 Extract a file from a Jar................................................................................................158 4.37 Determine if running from JAR .....................................................................................160 4.38 Get list of classes in package (in a Jar).......................................................................160 4.39 Add version to Jar packaging .......................................................................................162 4.40 Use ANT to Build a JAR with version/build number.....................................................164 4.41 Include all jars in the classpath definition .....................................................................167 4.42 Windows batch file.......................................................................................................167 4.43 JDK6............................................................................................................................168 4.44 JAR (and ANT)............................................................................................................169 . 4.45 Detect the browser/JVM type.......................................................................................170 4.46 Detect if Java is enabled from HTML...........................................................................172 4.47 See the Java Console Window Log (Java plugin).......................................................172 5 Internationalization .....................................................................................................................174 5.1 java−inter.......................................................................................................................174 5.2 Load resources based upon client environment at startup............................................174 5.3 Load resources dynamically..........................................................................................177 5.4 Load resources via a resources file...............................................................................180 5.5 Display "special character" using Unicode .....................................................................184 5.6 Display chinese/japanese characters............................................................................185 5.7 Localize a JOptionPane dialog......................................................................................185 5.8 Validate/Convert a number using the current Locale()..................................................187 5.9 Localize a JFileChooser................................................................................................187 . 5.10 Disable localization......................................................................................................190 5.11 Generate the Javadoc "en français"............................................................................190 5.12 Sort a String array........................................................................................................191 5.13 Accentuated characters in Properties/ResourceBundle file.........................................193 5.14 Compare accentuated letters.......................................................................................193 5.15 Unaccent letters...........................................................................................................194 5.16 Output french characters to the console......................................................................197 5.17 Get the default character set of the JVM.....................................................................198 5.18 Convert OEM (DOS) file to Ansi (Windows)................................................................198 5.19 Detect non−ASCII character in a String.......................................................................199 6 IO..................................................................................................................................................201 6.1 java−io...........................................................................................................................201 6.2 Redirect output(stdout/stderr) to a frame.......................................................................201 6.3 Redirect printStackTrace() to a String ............................................................................202 6.4 Output french characters to the console........................................................................203

Real's HowTo@www.rgagnon.com
6 IO 6.5 Clear the console and control attributes........................................................................204 6.6 Print text to a printer easily............................................................................................205 6.7 Print without a Dialog.....................................................................................................205 6.8 Simple input from the keyboard.....................................................................................206 6.9 Initialize and write to a serial port..................................................................................207 . 6.10 Redirect to a NULL device...........................................................................................208 6.11 Get the volume label....................................................................................................208 6.12 Easy keyboard input (JDK1.5).....................................................................................209 6.13 Open or close a CD/DVD drive....................................................................................209 6.14 Get faster console output (System.out.println() replacement).....................................211 6.15 Execute an external program.......................................................................................212 6.16 Using Runtime.exec()..................................................................................................212 6.17 Windows CMD (or BAT) file and retrieve the errorlevel or exitcode............................213 6.18 Launch a Unix script....................................................................................................213 6.19 Using the ProcessBuilder............................................................................................213 . 6.20 Windows rundll32 utility...............................................................................................214 6.21 PDF (Windows only)....................................................................................................214 6.22 PDF (Mac only)............................................................................................................215 6.23 Path to executable with spaces in them .......................................................................215 6.24 VBSCRIPT...................................................................................................................215 6.25 HTML Help (Windows only).........................................................................................216 6.26 Start Excel...................................................................................................................216 . 6.27 Launch the application associated with a file extension..............................................216 6.28 Launch an application from another application..........................................................217 6.29 Start the default browser from an application..............................................................219 6.30 Execute a Windows Shortcut (.lnk)..............................................................................221 6.31 Create a file association with a Java program.............................................................221 6.32 Capture the output from a VBS....................................................................................223 6.33 Get a return code from a VBS ......................................................................................224 6.34 Execute a CMD file stored in a JAR .............................................................................225 6.35 Read the content of a file.............................................................................................226 6.36 Read a text file from a jar.............................................................................................228 6.37 Extract a file from a Jar................................................................................................231 6.38 Read a data file with floats...........................................................................................232 6.39 Write to the end of a file...............................................................................................233 6.40 Write "real" ascii file.....................................................................................................234 6.41 Copy a file....................................................................................................................235 6.42 Use a "log file" ..............................................................................................................237 6.43 Delete files with a certain extension .............................................................................238 6.44 Insert a line in a file......................................................................................................239 6.45 Read a file into a variable in one shot..........................................................................240 6.46 Serialize an object to a file...........................................................................................240 6.47 Redirect stdout to a file................................................................................................242 6.48 Get the "last modified" date from a file .........................................................................242 6.49 Check if a file exists.....................................................................................................242 6.50 Get the current directory..............................................................................................243 6.51 Get the "root" of an application....................................................................................243 6.52 Get the content of a directory with a Filter...................................................................244 6.53 Get the content of a directory with subdirectories........................................................246

6.54 Make a directory

Real's HowTo@www.rgagnon.com
6 IO 6.54 Make a directory..........................................................................................................247 6.55 Create a fixed−length file.............................................................................................247 6.56 Delete a non−empty directory......................................................................................247 6.57 Create a temporary file................................................................................................248 6.58 Detect file modification.................................................................................................249 6.59 Get the default character set of the JVM.....................................................................252 6.60 Parse a pathname ........................................................................................................252 6.61 Handle Excel files........................................................................................................253 6.62 JDBC−ODBC Excel driver...........................................................................................253 6.63 JExcel..........................................................................................................................253 6.64 POI...............................................................................................................................254 6.65 JXLS............................................................................................................................255 6.66 xlSQL...........................................................................................................................255 6.67 JCOM...........................................................................................................................256 6.68 OpenXLS Java Spreadsheet SDK...............................................................................257 6.69 Handle CSV file ............................................................................................................259 6.70 com.Ostermiller.util CSV Utils......................................................................................259 6.71 opencsv ........................................................................................................................259 6.72 ServingXML.................................................................................................................259 6.73 Super CSV...................................................................................................................259 6.74 csvreader.....................................................................................................................259 6.75 CSVFile........................................................................................................................259 6.76 FlatPack.......................................................................................................................260 6.77 Create an Excel file......................................................................................................260 6.78 Create or process a PDF file ........................................................................................260 6.79 Convert OEM (DOS) file to Ansi (Windows)................................................................262 6.80 Close a stream in a try/catch block..............................................................................263 6.81 Rename a file extension..............................................................................................264 6.82 Remove HTML tags from a file to extract only the TEXT .............................................264 6.83 Get the Mime Type from a File....................................................................................265 6.83.1 Using javax.activation.MimetypesFileTypeMap..................................................265 6.83.2 Using java.net.URL.............................................................................................266 6.83.3 Using JMimeMagic ..............................................................................................266 6.83.4 Using mime−util..................................................................................................267 6.83.5 Using Droid.........................................................................................................267 6.83.6 Aperture framework .............................................................................................267 6.84 Create a compressed (ZIP) file....................................................................................268 6.85 Display compressed (ZIP) file content.........................................................................269 6.86 Expand the compressed (ZIP) file ................................................................................270 6.87 Emit a beep..................................................................................................................270 6.88 Emit a Tone ..................................................................................................................271 6.89 Play an audio file from an application..........................................................................272 7 JDBC............................................................................................................................................274 7.1 java−jdbc ........................................................................................................................274 7.2 Connect to a database via JDBC−ODBC......................................................................274 7.3 SELECT data from a table.............................................................................................275 7.4 INSERT data into a table...............................................................................................276 7.5 MODIFY data in a table.................................................................................................277

Real's HowTo@www.rgagnon.com
7 JDBC 7.6 DELETE data in a table.................................................................................................278 7.7 Test for an empty ResultSet..........................................................................................278 7.8 Store and retrieve an object from a table.......................................................................279 7.9 Retrieve an Image ..........................................................................................................281 7.10 Insert an Image............................................................................................................281 7.11 Connect to an Oracle database with JDBC.................................................................281 7.12 Connect to Oracle using a connection pool.................................................................282 7.13 Get JDBC driver for major database vendors..............................................................285 7.14 Handle dates................................................................................................................285 7.15 Call a stored procedure ................................................................................................286 7.16 Stored procedure with Input/Output parms and a ResultSet.......................................287 7.17 Fix incomplete field returned by the ResultSet............................................................288 7.18 Get a record count with the SQL Statement................................................................288 7.19 Transfer a ResultSet to a JTable.................................................................................288 7.20 List tables in a database..............................................................................................289 7.21 Display ResultSet data in an HTML Table in Servlet...................................................290 7.22 Detect SQL errors or warnings....................................................................................291 7.23 Using DSN−less connection........................................................................................292 7.24 Read data from Excel worksheet.................................................................................293 7.25 Handle Excel files........................................................................................................294 7.26 JDBC−ODBC Excel driver...........................................................................................295 7.27 JExcel..........................................................................................................................295 7.28 POI...............................................................................................................................296 7.29 JXLS............................................................................................................................296 7.30 xlSQL...........................................................................................................................297 7.31 JCOM...........................................................................................................................297 7.32 OpenXLS Java Spreadsheet SDK...............................................................................298 7.33 Specify a CharSet when connecting to a DBMS ..........................................................300 7.34 Get current date using JDBC.......................................................................................300 7.35 Enable JDBC logging...................................................................................................301 7.36 Detect if a table exists..................................................................................................303 7.37 Convert a ResultSet to XML........................................................................................303 7.38 Escape special character in a LIKE clause..................................................................305 7.39 Insert the current date..................................................................................................306 7.40 Log the SQL Statements ..............................................................................................306 7.41 Plain JDBC Logging.....................................................................................................306 7.42 P6Spy..........................................................................................................................306 7.43 Proxool.........................................................................................................................306 8 JNI................................................................................................................................................307 8.1 java−jni ..........................................................................................................................307 . 8.2 Use native code through JNI.........................................................................................307 . 8.3 Pass a string to/from Java to/from C ..............................................................................307 8.4 Set the computer clock..................................................................................................309 8.5 Determine the signature of a method .............................................................................309 8.6 Use arrays ......................................................................................................................311 8.7 Load a DLL....................................................................................................................312 8.8 Use the MouseWheel....................................................................................................312 . 8.9 Throw an Exception (from JNI code).............................................................................312

8.10 Throw my own Exception (from JNI code)

Real's HowTo@www.rgagnon.com
8 JNI 8.10 Throw my own Exception (from JNI code)...................................................................313 8.11 JNI from a package......................................................................................................314 8.12 Make a Window "stay on top"......................................................................................314 8.13 Start a JVM from C......................................................................................................315 8.14 Retrieve environment variable (JNI)............................................................................316 8.15 Get the PID..................................................................................................................316 8.16 Clear the console, set color and cursor position (JNI).................................................317 8.17 Call Windows API (Open source solution)...................................................................320 9 Javascript interaction .................................................................................................................321 9.1 java−js ............................................................................................................................321 9.2 * Read me * ....................................................................................................................321 9.3 Wake−up a Java applet.................................................................................................321 9.4 Call a Java method from Javascript...............................................................................323 9.5 Calling Java applets methods using DOM and JavaScript............................................325 9.6 Access Java variables from Javascript..........................................................................325 9.7 Call Javascript from a Java applet.................................................................................326 9.8 Create dynamic HTML from a Java applet....................................................................329 9.9 Have Applets on different frames communicates with each other.................................330 9.10 Send a message from an Applet to another Applet on a different page......................331 9.11 Retrieve values from a Java applet for HTML form (CGI) ...........................................333 . 9.12 Detect if an Applet is ready..........................................................................................334 9.13 Read/Write HTML field values from JAVA...................................................................335 9.14 Detect if Java is enabled..............................................................................................337 9.15 Detect if Java 1.1 (with event delegation) is available.................................................337 9.16 Access Cookies from a Java Applet............................................................................337 9.17 Set Applet PARAM VALUE from javascript.................................................................340 9.18 Pass an Array between Java and Javascript...............................................................341 9.19 Interaction without LiveConnect...................................................................................343 9.20 Directory listing on the Web server in a Java Applet...................................................347 9.21 Have a Java button close the browser window............................................................349 9.22 Detect if cookies are enabled .......................................................................................350 9.23 Display a page after all applets are loaded..................................................................351 10 Servlet/JSP................................................................................................................................352 10.1 java−jsp ........................................................................................................................352 10.2 Read me......................................................................................................................352 10.3 Get parameters passed to a servlet.............................................................................352 10.4 Detect no argument condition in a Servlet...................................................................353 10.5 Set a Cookie from a servlet.........................................................................................354 . 10.6 Read a Cookie from a servlet......................................................................................354 10.7 Delete (or expire) a Cookie from a servlet...................................................................355 10.8 Ask for a password from a Servlet...............................................................................355 10.9 Talk to a CGI/Servlet...................................................................................................356 . 10.10 Test for Cookies.........................................................................................................357 10.11 Display ResultSet data in an HTML Table in Servlet.................................................357 10.12 Specify the filename to be used for a file sent by a Servlet.......................................358 10.13 Pass information to another servlet/jsp......................................................................358 10.14 Handle PDF output....................................................................................................359

Real's HowTo@www.rgagnon.com
10 Servlet/JSP 10.15 Detect if the connection is via a secure channel........................................................359 10.16 In a Servlet, check if Form Field is present................................................................359 10.17 Get the root dir of a web app.....................................................................................360 10.18 Get client IP address from JSP..................................................................................360 10.19 Output a binary stream from a JSP ............................................................................360 10.20 Use a connection cache from JSP.............................................................................361 10.21 Read a Web Application property..............................................................................362 10.22 Use EJB from JSP.....................................................................................................363 10.23 Define a method in a JSP page.................................................................................363 10.24 Precompile JSP pages ...............................................................................................363 10.25 Get a list of directories for JSP..................................................................................365 10.26 Use and share a class in JSP pages.........................................................................365 10.27 Get the root dir of a web app.....................................................................................367 10.28 Launch an applet from a JSP .....................................................................................367 10.29 Prevent caching of a JSP output...............................................................................367 . 10.30 Call another EJB........................................................................................................368 10.31 Keep java files generated from JSP (BEA WLS).......................................................368 10.32 Get the server version (BEA WLS)............................................................................369 10.33 Quickly create a Web application with BEA WLS......................................................369 10.34 Nicely display WEB.XML informations.......................................................................370 10.35 Reverse the CLASSLOADER order (BEA)................................................................371 10.36 Detect change in JSP and recompile (BEA)..............................................................372 11 Language ...................................................................................................................................373 11.1 java−language.............................................................................................................373 11.2 * Read me * ..................................................................................................................373 11.3 Use a Hashtable..........................................................................................................374 11.4 Scan the content of a hashtable..................................................................................374 11.5 Call a method dynamically (Reflection) .......................................................................374 . 11.6 Create an object from a string ......................................................................................376 11.7 Get a variable value from the variable name...............................................................377 11.8 Launch an application from another application..........................................................378 11.9 Create a java source dynamically, compile and call....................................................379 11.10 Access the enclosing class from an inner class .........................................................380 11.11 Access inner class from outside................................................................................381 11.12 Use globally defined constants..................................................................................382 11.13 Serialize an Object.....................................................................................................383 11.14 Serialize an Object over a socket..............................................................................385 11.15 Easily remove my debugging code............................................................................385 11.16 Obtain from where a Class is loaded.........................................................................386 11.17 Get the class name in a static method.......................................................................387 11.18 Get the current method name....................................................................................387 11.19 Detect if a package is available.................................................................................388 11.20 Have a singleton........................................................................................................389 11.21 Make methods that have unspecified number of parameters....................................390 11.22 Multiple expressions in for loops................................................................................391 11.23 Handle the List conflict...............................................................................................391 11.24 Use a generic toString().............................................................................................391 11.25 Use Object.clone().....................................................................................................393

11.26 Static field, constructor and exception

Real's HowTo@www.rgagnon.com
11 Language 11.26 Static field, constructor and exception.......................................................................394 11.27 Use a Label break......................................................................................................395 11.28 Put printStackTrace() into a String.............................................................................396 11.29 Sort an array..............................................................................................................397 11.30 Initialize multidimensional array.................................................................................398 11.31 Get array upperbound................................................................................................399 11.32 Convert a String to an array.......................................................................................399 11.33 Sort in reverse order..................................................................................................400 11.34 Resize an array..........................................................................................................401 11.35 Dump array content...................................................................................................402 11.36 Initialize a static array................................................................................................403 11.37 Sort an Hashtable......................................................................................................404 11.38 Eliminate "[unchecked] unchecked call ..." compiler warning....................................405 11.39 Sort on many fields....................................................................................................406 11.40 Optimize Collection usage.........................................................................................408 11.41 Sort an HashMap.......................................................................................................410 11.42 Get a key from value with an HashMap.....................................................................411 11.43 Use an INI file (properties).........................................................................................411 11.44 Load a properties file.................................................................................................413 11.45 Accentuated characters in Properties/ResourceBundle file.......................................413 11.46 Have a multi−line value in a properties file................................................................414 11.47 Use XML with Properties...........................................................................................415 11.48 Use the Registry to store informations (Preferences API).........................................415 12 Networking................................................................................................................................417 12.1 java−net.......................................................................................................................417 12.2 Extract network card address......................................................................................417 12.3 Get the workstation name/ip........................................................................................419 12.4 Find port number not in use.........................................................................................421 12.5 Disable DNS caching...................................................................................................421 12.6 Encode/Decode to/from Base64..................................................................................422 12.7 Using javax.mail.internet.MimeUtility...........................................................................422 12.8 Using Apache Commons Codec..................................................................................423 12.9 MiGBase64..................................................................................................................424 12.10 Lookup using MX record to validate mail server........................................................424 12.11 Send an email using the SMTP protocol...................................................................431 . 12.12 Check if there is mail waiting.....................................................................................432 12.13 Receive email............................................................................................................434 12.14 Send email with an attachment..................................................................................436 12.15 Send email with JavaMail..........................................................................................441 12.16 Send email with authentication..................................................................................443 12.17 Handle EML file with JavaMail...................................................................................444 12.18 Send HTML mail with images (Javamail) ..................................................................446 . 12.19 Debug a Javamail Program.......................................................................................448 12.20 Send email with SMTPS (eg. Google GMail) (Javamail)...........................................449 12.20.1 Settings for well known mail providers..............................................................450 12.21 Mix plain text and HTML content in a mail.................................................................450 12.22 Check if a file was modified on the server.................................................................451 12.23 Check if a page exists................................................................................................451

Real's HowTo@www.rgagnon.com
12 Networking 12.24 Connect through a Proxy...........................................................................................453 12.25 Identify yourself using HTTP Authentification............................................................455 12.26 Talk to a CGI/Servlet.................................................................................................457 . 12.27 Write/Read cookies using HTTP................................................................................458 12.28 Read a GIF or CLASS from an URL save it locally ....................................................460 12.29 Resolve a relative URL..............................................................................................462 12.30 File size from URL.....................................................................................................462 12.31 Use the HTTPS protocol............................................................................................463 12.32 Fetch a page from Google.........................................................................................463 12.33 Upload a file to a server.............................................................................................464 12.34 Connect through a Proxy...........................................................................................465 12.35 Have timeout on socket connection...........................................................................467 12.36 Ping a server..............................................................................................................467 12.37 Get the Date from server...........................................................................................468 12.38 Get the client IP address ............................................................................................469 12.39 Use the java.net.Socket.setSoLinger method............................................................470 12.40 Use the java.net.Socket.setTcpNoDelay method......................................................470 12.41 Find out who is accessing my ServerSocket.............................................................471 12.42 Transfer a file via Socket...........................................................................................471 13 Security ......................................................................................................................................473 13.1 java−security................................................................................................................473 13.2 Encrypt a password.....................................................................................................473 13.3 Create a checksum......................................................................................................475 13.4 Get the user name.......................................................................................................478 13.5 Get username using NT Challenge (NTLM)................................................................478 13.6 Check if the current user belongs a specific Windows group/role...............................480 13.7 Prompt for password from the console........................................................................480 13.8 Display a simple username/password Dialog from an Applet......................................481 14 Swing.........................................................................................................................................485 14.1 java−swing...................................................................................................................485 14.2 * Read me * ..................................................................................................................485 14.3 Change component default font...................................................................................485 14.4 Repaint problem under the mouse cursor (JDK1.2)....................................................486 14.5 Set the LookAndFeel...................................................................................................486 14.6 Use any LookAndFeel on any plateform......................................................................486 14.7 Use a Timer.................................................................................................................487 14.8 Share ActionEvent handler..........................................................................................487 14.9 Trigger a click on a Button...........................................................................................489 14.10 Get default values for Swing−based user interface...................................................491 14.11 Close a JFrame under condition................................................................................492 14.12 Maximize a JFrame ....................................................................................................492 14.13 Capture System.out into a JFrame............................................................................493 14.14 Remove the titlebar of JInternalFrame .......................................................................495 14.15 Have borders on a JWindow/JFrame .........................................................................496 14.16 Display HTML in a JScrollPane.................................................................................496 14.17 Use a JOptionPane....................................................................................................497 14.18 Localize a JOptionPane dialog..................................................................................498

14.19 Customize JOptionPane buttons

Real's HowTo@www.rgagnon.com
14 Swing 14.19 Customize JOptionPane buttons...............................................................................500 14.20 Localize a JFileChooser............................................................................................500 . 14.21 Select a directory with a JFileChooser ......................................................................503 . 14.22 Disable the JFileChooser's "New folder" button .........................................................504 14.23 Validate a filename from a JFileChooser...................................................................505 14.24 Make a JFrame looks like a JDialog..........................................................................507 14.25 Based on JTextField content, enable or disable a JButton........................................508 14.26 Apply special filter to a JtextField ...............................................................................509 14.27 Limit JTextField input to a maximum length ...............................................................511 14.28 Validate a value on the lostFocus event....................................................................512 14.29 Make sure that my jTextfield has the focus when a JFrame is created.....................514 14.30 Stop the beep on JFormattedTextField ......................................................................515 14.31 Right justified JTextfield content................................................................................516 14.32 Set the focus on a particuliar JTextField....................................................................516 14.33 Make JTextField unselectable...................................................................................516 14.34 Use a JTree to navigate in a site...............................................................................517 14.35 Expand or collapse a JTree.......................................................................................523 14.36 Have a popup attached to a JTree .............................................................................525 14.37 Traverse a JTree ........................................................................................................527 14.38 Show dotted lines in a JTree ......................................................................................529 14.39 Explore directories with a JTree .................................................................................529 14.40 Prevent JTree collapsing...........................................................................................531 14.41 Single selection in a JTree.........................................................................................531 14.42 Reduce JTree children indentation............................................................................531 14.43 Use + or − for JTree Icons.........................................................................................532 14.44 Change the JTable header color...............................................................................533 . 14.45 Double click on a JTable............................................................................................534 14.46 Read a data file into a JTable....................................................................................535 14.47 Disable row selection in a JTable..............................................................................538 14.48 Read a data file into a JTable and reload if data file have changed..........................538 14.49 Hide a column in JTable............................................................................................540 14.50 Scroll a JTable to the last row....................................................................................542 14.51 Transfer a ResultSet to a JTable...............................................................................542 14.52 Have on a JScrollPane/JTable an horizontal JScrollbar............................................543 14.53 Make a JList select an item on doubleclick or the ENTER key..................................543 14.54 Make a JList like a scrolling text display....................................................................544 14.55 Have images in a JList...............................................................................................545 14.56 Add a row and clear a JList.......................................................................................547 . 14.57 Sort a JList.................................................................................................................548 14.58 Double click on a JList...............................................................................................550 14.59 Have a PopUp on a JList...........................................................................................551 14.60 Set the cursor position in a JTextArea.......................................................................552 14.61 Make a JLabel selectable with the mouse.................................................................552 14.62 Change JLabel background color..............................................................................553 14.63 Bold / Unbold a JLabel...............................................................................................553 14.64 Multi−line JLabel........................................................................................................554 14.65 Underline a string.......................................................................................................554 14.66 Update a JLabel.........................................................................................................555 14.67 Have Multi−line string in a JToolTip...........................................................................555

Real's HowTo@www.rgagnon.com
14 Swing 14.68 Change Tooltip color..................................................................................................555 14.69 Change a JTooltip font...............................................................................................555 14.70 Keep a JTooltip visible...............................................................................................556 14.71 Display icon associated with an executable ...............................................................557 14.72 Have items in JMenubar at rightmost position...........................................................559 14.73 Have an JButton with an Image.................................................................................560 15 Thread ........................................................................................................................................562 15.1 java−thread..................................................................................................................562 15.2 Pipe the output of a thread to the input of another one ................................................562 15.3 Pipe the output of a thread to the input of other threads ..............................................564 15.4 Wait the for the completion of a thread........................................................................566 15.5 Control a thread from outside......................................................................................567 15.6 Create a Timer object..................................................................................................568 15.7 Pause the execution....................................................................................................569 15.8 Execute a method at a specified time interval.............................................................569 15.9 Execute a process at regular interval..........................................................................571 . 15.10 Handle concurrent read/write.....................................................................................572 15.11 Communicate between threads using a Queue.........................................................573 16 Varia...........................................................................................................................................579 16.1 java−varia....................................................................................................................579 16.2 Create a Taglet to document database access (Javadoc) ..........................................579 . 16.2.1 newMethod .........................................................................................................579 16.3 Generate the Javadoc "en français"............................................................................582 16.4 Document a package using Javadoc...........................................................................584 16.5 Use a Log file...............................................................................................................585 16.6 Trace the execution.....................................................................................................587 16.7 Time the execution .......................................................................................................589 16.8 Log information efficiently (with Log4J).......................................................................590 . 16.9 Call Windows API (Open source solution)...................................................................591 16.10 Call COM object (Open source solution)...................................................................592 16.11 Run JAVA as a Windows service ...............................................................................592 16.12 Create entity−relation diagram ...................................................................................593 16.13 Java Remote desktop tool.........................................................................................593 16.14 Create entity−relation diagram ...................................................................................594 16.15 Launch a java program as a Windows EXE file.........................................................594 16.16 Handle CSV file ..........................................................................................................594 16.17 com.Ostermiller.util CSV Utils....................................................................................594 16.18 opencsv ......................................................................................................................594 16.19 ServingXML...............................................................................................................595 16.20 Super CSV.................................................................................................................595 16.21 csvreader...................................................................................................................595 16.22 CSVFile......................................................................................................................595 16.23 FlatPack.....................................................................................................................595 16.24 Handle Excel files......................................................................................................595 16.25 JDBC−ODBC Excel driver.........................................................................................595 16.26 JExcel........................................................................................................................596 16.27 POI.............................................................................................................................596

16.28 JXLS

Real's HowTo@www.rgagnon.com
16 Varia 16.28 JXLS..........................................................................................................................597 16.29 xlSQL.........................................................................................................................598 16.30 JCOM.........................................................................................................................598 16.31 OpenXLS Java Spreadsheet SDK.............................................................................599 16.32 Use System time to generate unique ID....................................................................601 16.33 Get a unique identifier................................................................................................601 16.34 Get the hard disk serial number or Motherboard serial number................................602 16.35 Motherboard serial number........................................................................................603 16.36 Hard disk serial number.............................................................................................603 16.37 Sort an array..............................................................................................................604 16.38 Sort a String array......................................................................................................606 16.39 Do a selection sort.....................................................................................................608 16.40 Obtain from where a Class is loaded.........................................................................608 16.41 Get the class name with or without the package.......................................................609 16.42 Convert a .class to .java file.......................................................................................610 16.43 See the generated bytecode......................................................................................611 16.44 Self replicating programs...........................................................................................613 16.45 A curiosity (strange Java code).................................................................................614 . 16.46 Classic bugs ...............................................................................................................615 16.47 Number of the beast!.................................................................................................616 16.48 Convert wildcard to a regex expression.....................................................................616 16.49 Count distinct elements in a Vector...........................................................................618 16.50 Justify a string with wordwrap....................................................................................619 16.51 Validate a Social Security Number (canadian)..........................................................620 16.52 Validate a Credit Card Number..................................................................................621 16.53 Preventing multiple instances of an application.........................................................624 16.54 Trap JVM shutdown...................................................................................................627 16.55 Browse a Queue (JMS/MQ).......................................................................................628 16.56 Wrap a Java beans in a COM object.........................................................................628 17 XML............................................................................................................................................631 17.1 java−xml ......................................................................................................................631 . 17.2 Read me......................................................................................................................631 17.3 Display XML using plain HTML....................................................................................632 17.4 Transform XML into HTML using XSLT.......................................................................633 17.5 Parse using SAX or DOM............................................................................................634 17.6 Parse an XML string....................................................................................................636 17.7 Create an XML document with DOM...........................................................................637 17.8 Attach a stylesheet to an XML file ................................................................................639 17.9 Create an XML file and attach an XSL .........................................................................640 17.10 Nicely display WEB.XML informations.......................................................................643 17.11 Serialize an object using XML ....................................................................................644 17.12 Convert a flat file to XML (SAX).................................................................................645 17.13 Convert a flat file to XML (DOM)................................................................................647 17.14 Convert a ResultSet to XML......................................................................................650 17.15 Parse with XPath.......................................................................................................652 17.16 Strip extra spaces in a XML string.............................................................................653 17.17 Create an XML file and attach an XSL .......................................................................654 17.18 Use XML with Properties...........................................................................................657

...........................................................14 Start an executable on the client................................................................................677 18..............................................................24 Get a list of headers from a newsgroup.0 ......................................................680 18.......................10 Uninstalling the MS JVM.......................680 18......26 Detect if Swing is installed...................671 18................................................................665 17.......................................................................665 17.................682 18........25 Get a list of all available newsgroup from a newsserver......................1 java−stringnumber....679 18........................................................................2 Atom ........677 18...............................................................686 ........................................................................20......................679 18............................................20................................................19....19..672 18............................................................................................................................2 * Read me * ....................684 19 String/Number ..17 Write "other−browser−friendly" code when using the Netscape Capabilities package................................20 Use Netscape Java Console hidden commands...678 18....................................Real's HowTo@www..............................................................665 17...663 ...............668 18..................................1 Parsing a feed with Apache Commons Digester.............................................................................................................................683 18.......22 Validate a RSS feed .........674 18...................................................................................................................................................1 java−deprecated.......................................................668 18........15 Get rid of the message "Warning − unsigned applet window".........................................19 Start automatically JAVA when opening Netscape..................668 18........................................................................12 Sign an applet......660 17..................................................................................................................685 19.......2 * Read me * ..........675 18.................................23 Read messages from a newsserver.....................................23 Attach a CSS to RSS feed................3 Creating a feed ..........................685 19..........................661 17............................................................................................................................................................11 Wrap a Java class in a COM object...19................................664 17......................672 18....671 18...................................18 Disable the JIT compiler in Netscape or IE.....com 17 XML 17.............................672 18...........663 17....658 17...............................................................19...............................................680 .............21 Avoid the Netscape "Couldn't connect to '' with origin from 'local−classpath−classes'" message........................................................................................................................................................................673 18..............................................................................................................................20 Parse a RSS XML file...................658 17.....19 Create a RSS feed..........................................................5 Creating a feed with Rome .........669 18................................................................................ 17............659 17...................................................................21 Add a Live bookmark..................................4 Read the Registry..........660 17............7 Play a WAV audio file.................................................................................3 RSS−UTIL......................22 Post a message on a newsserver using NNTP protocol ..................................5 Call a Win API.........................................................................................................................6 Display a BMP image .........................8 Detect if the MS JVM is used.................................665 18 DEPRECATED......2 Parsing a feed with ROME .............16 Read/write a local file from an Applet......3 Keep the console open after execution ...................................................... 18..681 18........ 18...........................19..............682 18..............27 Make Swing always available from Netscape.....668 18...................................................................................................................................................................685 19....................20.................................................................................................13 Bypass the need for a certificate ...................................1 RSS 2................676 ........TLD.................668 18.............3 Convert from type X to type Y................rgagnon................................9 Get the latest MS JVM........................................4 Creating a feed with Apache Commons Digester...............................................................

.............726 19.................................................47 Convert number into words.........................................................................................................................................................35 Convert from type X to type Y..........................................................699 19............................723 19.......................24 Unescape HTML special characters from a String......................................725 19..........43 Deal with big−endian and little−endian order................21 Create a String with fixed length and filled with a specific character.710 19...........9 Optimize String operations .......................................................45 Pass floats as string literals to a method....... 19...25 Using HashMap....................42 Convert an UNSIGNED byte to a JAVA type........................5).........................716 19......................22 Unquote a String..................................................................................................39 Display numbers in scientific notation.....................11 Test if a String starts with a digit or uppercase letter......................................702 19.......718 19....................................................mail............46 Get random numbers.....rgagnon....................................................12 Get InputStream from a String........................................................................................701 19........18 Replace a "\" by "\\"...................722 19...........................718 19....48 Arithmetic with double....................707 19.......689 19............................................................36 Type conversion (JDK1..........................................736 19..........26 Using Array...............................729 19...............8 Split a string using String......................................7 "Tokenize" a string.................721 19........................................................................41 Get a random number........................................................................................................................706 19......................................................................................717 19.31 Encode/Decode to/from Base64......................................................................................................................724 19........................................................................................split()............................................................714 19..................707 19........................28 Remove HTML tags from a file to extract only the TEXT .................50 Convert bytes to megabytes.............738 ..719 19...............14 Replace \r\n with the <br> tag.....10 Remove spaces from a string...................20 Compare accentuated letters..........726 19....................................................................................................................38 Display numbers with commas................................15 Unaccent letters.705 19...........................................................................................................13 Easy String padding....719 19.................................49 Detect even/odd number..........................................................................32 Using javax...........................................701 19..............................................737 19.....51 Validate a number.............................................................................709 19............................................................................................................727 19.4 Strip certain characters from a String Real's HowTo@www....................................................727 19.5 Replace/remove character in a String ................com 19 String/Number 19..........................................................701 19....................713 19..........................................................................................719 19.......................................737 ...................................695 19....................17 Format a String (JDK1...................728 19...............702 19......29 Convert a byte array to a Hex string........23 Escape HTML special characters from a String ...707 19.................................4 Strip certain characters from a String......40 Display numbers with leading zeroes..........................................................................19........................37 Round a double .............33 Using Apache Commons Codec..................................698 19........................................................................................44 Pass an integer by reference.......................................................................................5)............................715 19..........34 MiGBase64.......................................................................688 19..........................................712 19..........................30 Apply proper uppercase and lowercase on a String...............................................19 Substitute tokens in a String.................................................................................................................internet...690 19................712 19..................6 Replace every occurences of a string within a string..........................................................691 19...................................728 19................................................................................................................MimeUtility......16 Apply a mask to String.709 19.....................27 Detect non−ASCII character in a String.............................................................................

public class whatres extends Applet { public void init() { Dimension dim = Toolkit.width==640 &dim..whatever.height==480) { try { getAppletContext(). If "HTML frame ID" do not exists then a new browser window will be opened. or getAppletContext().net.1 java−applet 1. import java. The following "HTML frame ID" have special meanings : "_self" "_parent" "_top" "_blank" current frame parent frame base frame new window For example. } catch (Exception ex) {} } 1 Applet .2 Goto to a new URL from an Applet Current version of this HowTo : http://www.html").html is used."_top").showDocument (new URL(getCodeBase()+"hires.*.showDocument (new URL(getCodeBase()+"lowres.whatever.html page if resolution is 640x480 else the hires.showDocument (new URL("http://www.getScreenSize()./javadetails/java−0002.com/javadetails/.awt.com")). import java.*. if (dim.html You have to use getAppletContext().showDocument (new URL("http://www. } catch (Exception ex) {} } else { try { getAppletContext().com")."_top").rgagnon.applet. we want to display lowres.getDefaultToolkit()."HTML FRAME ID"). import java.html").*.1 Applet 1.

if (docString.showDocument (new URL(getDocumentBase()+"/. public void init() { t = new TextField(20).net. add(t).endsWith("/")) { getAppletContext().getText()))./lowres. public class GotoURLButton extends Applet implements ActionListener { Button b.google. import import import import java.printStackTrace(). If the document name was specified. since getDocumentBase() returns the full URL including the name of the document.*. java.*..getSource() == b) { try { getAppletContext(). } public void actionPerformed(ActionEvent ae) { if (ae.*. "_top"). } } catch (Exception e) {} Another example.} } NOTE: The previous example works only so long as the document was retrieved without specifying an actual document name.toString(). t.com").awt. you should try something like this or specify the complete URL (thanks to Rob Judd): : try { String docString = getDocumentBase(). b = new Button("Go to this URL").event. b. } else { getAppletContext(). TextField t. "_top"). add(b).setText("http://www.*.html").showDocument(new URL(t.applet.showDocument (new URL(getDocumentBase()+"lowres. type a new URL in a textfield. java. } } } } Try it here. and press a button to go to that page. 1 Applet . } catch (Exception e) { e.html"). java.awt.addActionListener(this).

com/javadetails/.rgagnon. if(message == null) message = " Isn't scrolling text in the status line annoying? ".*. String message. // NOTE : This is not a very strong protection! // } } Try it here 1.*.3 Determine the host from where the Applet is loaded Current version of this HowTo : http://www.java Optional parameters: message. If it's not equals to your // URL then quit. public void init(){ message = getParameter("message").class" width=0 height=0> <param name="message" value="Hello World!"> <param name="width" value="24"> </applet> */ import java.html import java. int at. public class ScrollStatus extends Applet implements Runnable { Thread thread.rgagnon.Applet./javadetails/java−0003. StringBuffer buffer.applet.. public class FromWhere extends Applet { public void init() { Label label = new Label(getCodeBase().html /* ScrollStatus.3 Determine the host from where the Applet is loaded ./javadetails/java−0010.util.com/javadetails/. add(label).applet. // // you can check the value of getCodeBase() // to implements a simple copy protection // scheme.1. 1. int width. import java.awt.toString())..4 Have a scrolling status line Current version of this HowTo : http://www. width Default values: message = "Isn't scrolling text in the status line annoying? " width = 36 Example usage: <applet code="ScrollStatus. import java.*.

i < width.3 Determine the host from where the Applet is loaded . } if(width < 5 || width > 180) { width = 36. } message.sleep(25). i < width. message. } public void scroll(){ int ml = message. ++k){ if(k >= ml) { k = 0. ++i) { buf[i] = ' '. if(at >= ml) { at = 0. } buffer = new StringBuffer(width). } buffer. ++i. message = new String(buf).String ws = getParameter("width").length() < width) { char buf[] = new char[width]. } } } } 1.charAt(k)). } } public void start(){ thread = new Thread(this).length().intValue(). at++. for(int i = 0. if(message.length().getChars (0. } else{ width = Integer.stop(). int k = at.showStatus(buffer.valueOf(ws).toString()). at = 0. buf. thread. } } public void run(){ while(true){ scroll(). message. for(int i = 0. buffer. try{ Thread.setLength(width). (width − message. } public void stop(){ thread.setCharAt(i.length()) / 2).start(). } getAppletContext(). // wait 25 ms } catch(InterruptedException e){ break. if(ws == null) { width = 36.

wbcrwl/search/web/".white).html import java.getText(). break. } public void sendSearch() throws Exception { String url. String searchString = searchParameter. searchEngine.addItem("AltaVista").02 style event handling public boolean action(Event e.target.Try it here.*. searchEngine.. } // JDK1. Choice searchEngine.Applet.getSelectedIndex()) { case 0: url = "http://www.equals(searchButton)) { try { sendSearch().toString()).altavista. public void init() { setBackground(Color.webcrawler. case 1: url = "http://msxml. add(searchParameter).com/web/results?q=". 1.*. searchEngine. import java. } catch (Exception e1) { showStatus("Exception caught:" + e1. searchButton = new Button("Search"). Button searchButton.5 Use a search engine .applet.addItem("WebCrawler"). 1. add(searchButton)./javadetails/java−0011.addItem("Yahoo"). searchParameter = new TextField(20).select(0).5 Use a search engine Current version of this HowTo : http://www. break. Object o) { if (e. searchEngine. if (searchString. add(searchEngine).awt. public class SearchApplet extends Applet { TextField searchParameter.net.equals("")) { showStatus("Must enter a search string"). } switch (searchEngine.com/info. } } return true. import java.com/javadetails/.rgagnon. return. searchEngine = new Choice().

getAppletContext(). f.start().6 Have an on−screen clock . mct = new MyClockThread(this).encode(searchString). } // encode the search data url += URLEncoder.showDocument(new URL(url). formatter = new SimpleDateFormat(df).util. } } Try it here. b = this.*. "_top").6 Have an on−screen clock Current version of this HowTo : http://www. java.awt.yellow). // launch the search engine showStatus("Connecting to search location " + url). It's not easy to call Google from an Applet but you can do it in application as seen in this HowTo.com/bin/search?p=".*. String dateText. } } class MyPanel extends Panel { MyClockThread mct. MyPanel(String df) { super().html import import import import java. mct. SimpleDateFormat formatter.text. validate().getForeground(). setBackground(new Color(0). return. public class MyClock extends Applet { MyPanel mp. java.com/javadetails/.*. } public Dimension getPreferredSize() { return new Dimension 1. Color b. String previousDateText = "". default: showStatus("Invalid search engine selected./javadetails/java−0012.").yahoo. java.rgagnon.black). add(mp).getBackground(). 1. public void init() { mp = new MyPanel(getParameter("format")).applet. break.case 2: url = "http://search.*. setForeground(new Color(0). f = this..

} public void paint(Graphics g) { if (g != null) { g.class" HEIGHT=25 WIDTH=200> <PARAM NAME="format" VALUE="H:mm:ss:SSS"> </APPLET><P> /BODY/HTML Try it here. dateText = getNow(). g.(this.10. g. } catch(InterruptedException e) { } } } } <HTML><HEAD></HEAD><BODY> <APPLET CODE="MyClock. 1. public MyClockThread(MyPanel a) { mp = a.15). previousDateText = dateText.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.setColor(b).setColor(f).getFontMetrics(this.drawString(previousDateText.format(new Date()).10. } public void run() { while (true) { try { mp.getFont()).repaint().drawString(dateText.sleep(1000). } } public String getNow() { return formatter. this.15). 30). g.6 Have an on−screen clock .stringWidth(getNow()) + 25.dd GGG hh:mm aaa"> </APPLET><P> <APPLET CODE="MyClock.class" HEIGHT=25 WIDTH=200> <PARAM NAME="format" VALUE="yyyy−MM−dd hh:mm:ss"> </APPLET><P> <APPLET CODE="MyClock. } } class MyClockThread extends Thread { MyPanel mp.MMMMM.

trim(). } else { System.com/javadetails/.rgagnon. textBox = new TextArea( 5. if ( applet2 != null ) { applet2. } } 1. public class Applet2_0022 extends java. Object arg) { if (ev. 15 ).append( "\n" ).out. } public void append( String msg ) { textBox.*. public void init() { setLayout(new FlowLayout()). b = new Button("Send to Applet 2"). add(b).Applet { TextField inputText.append( msg )..*. return true. Applet2_0022 applet2 = (Applet2_0022)getAppletContext()./javadetails/java−0022.awt.getApplet("applet2").applet.html [Applet1_0022.7 Have Applets on the same page communicate with each other Current version of this HowTo : http://www. } // JDK 1.append( textMsg ).Applet { TextArea textBox. 40 ). public void init() { setLayout(new FlowLayout()). Button b.02 style evant handling public boolean action(Event ev.awt.target instanceof Button) { String textMsg = inputText.7 Have Applets on the same page communicate with each other . return false.java] import java. } } [Applet2_0022.java] import java. add(inputText). textBox.1. } } return false.applet.getText().println("Applet2 not found?"). public class Applet1_0022 extends java. add( textBox ). inputText = new TextField( "".

[HTML] <HTML><HEAD></HEAD><BODY> <APPLET CODE="Applet1_0022.rgagnon.*.java)] import java. a = new Button("Send to Message").class" NAME="applet2" HEIGHT=200 WIDTH=400> </APPLET> </BODY></HEAD> Try it here. 1./javadetails/java−0023.applet.*.class" NAME="applet1" HEIGHT=200 WIDTH=150> </APPLET> <APPLET CODE="Applet2_0022.com/javadetails/. public class Java0023 extends Applet { TextField tf. 1.8 Have Applets on different frames communicates with each other .html It is possible to share data between different applets via static variables [HTML (java−0023. add(a).awt.*"> <FRAME SRC="java−0023−f1..html)] <HTML><HEAD></HEAD> <FRAMESET COLS="50%.html" NAME="f1"> <FRAME SRC="java−0023−f2. b = new Button("Receive from Message"). public void init() { setLayout(new FlowLayout()).b.html" NAME="f2"> </FRAMESET> </HEAD> [HTML (java−0023−f1.class" HEIGHT=200 WIDTH=200> </APPLET> </BODY></HTML> [JAVA source (Java0023.8 Have Applets on different frames communicates with each other Current version of this HowTo : http://www.html AND java−0023−f2. import java. Button a.html)] <HTML><HEAD></HEAD> <BODY> <APPLET CODE="Java0023.

applet. } } class StaticMessage { public static String message = "".html FirstApplet encodes the message for SecondApplet in the search (or query) section of SecondApplet. tf = new TextField(20).net. java.event. take a look at this How−to.*.9 Send a message from an Applet to another Applet on a different page Current version of this HowTo : http://www.add(b).setText(StaticMessage.html <HTML><HEAD></HEAD><BODY> <APPLET CODE="FirstAppletJ. add(tf). } Try it here.java import import import import java. 1.message = tf. java.*.*.9 Send a message from an Applet to another Applet on a different page . Object o) { if (e.target == a) { StaticMessage./javadetails/java−0041. } if (e.rgagnon.html URL. } // JDK 1. } return false. FirstAppletJ. } return true.message).com/javadetails/.target instanceof Button) { if (e.getText(). Then SecondApplet decodes the search section of its URL and extract the message coming from FirstApplet.02 style evant handling public boolean action(Event e.. java.awt. Check this DDJ article for a more elaborate way to implement this principle.class" HEIGHT=100 WIDTH=300> /APPLET/BODY/HTML FirstAppletJ. 1.*.awt.target == b) { tf. There is one way to do it by using a Javascript function as a bridge.

awt.getText()))). import java. SecondAppletJ extends Applet { init() { new Label("Message from 1st Applet"). "SecondAppletJ.html <HTML><HEAD></HEAD><BODY> <APPLET CODE="SecondAppletJ.decode(theMessage). import java.java import java. add(t= new TextField(20)).html?" + "message=" + URLEncoder.replace('+'.URLDecoder.*. } catch (Exception e) { e.class" HEIGHT=100 WIDTH=400> /APPLET/BODY/HTML SecondApplet.substring("message=". } } } } SecondAppletJ. /* with JDK1. tf = new TextField( 50 ). // remove message header theMessage = theMessage.length()). public class public void Label l = add (l). TextField add(tf).public class FirstAppletJ extends Applet implements ActionListener { Button b.net. public void init() { add(new Label("Message to 2nd applet :")). // decode the string (incomplete) theMessage = theMessage.substring(s. b. } public void actionPerformed(ActionEvent ae) { if (ae.' '). // complete current URL String s = getDocumentBase(). TextField t.applet.encode(t.getSource() == b) { try { getAppletContext().net.addActionListener(this).printStackTrace(). add(b = new Button("Load 2nd applet")).9 Send a message from an Applet to another Applet on a different page . the decoding can be done with java.2.indexOf('?') + 1). 1.toString().showDocument (new URL(getCodeBase().*.*. // extract the search (or query) section String theMessage = s.

} } You can try it here! NOTE : On IE.awt. where xy is the two−digit hexadecimal representation of the lower 8−bits of the character.rgagnon. import java. */ tf.you to convert from a MIME format called "x−www−form−urlencoded" to a String To convert to a String. Thread appletThread.applet.class" NAME="AppletLoader" HEIGHT=200 WIDTH=200> <PARAM NAME="appletToLoad" VALUE="SecondApplet0025"> <PARAM NAME="SecondAppletParm" VALUE="Hello World"> </APPLET></BODY></HTML> [JAVA source (AppletLoader.Applet. "%xy". 1. The remaining characters are represented by 3−character strings which begin with the percent sign.java)] import java../javadetails/java−0025. [HTML (testappletloader.AppletStub.*.html The idea is to load first a small Applet with a quick loading time.com/javadetails/. each character is examined in turn: . The plus sign '+' is converted into a space character ' '. The ASCII characters 'a' through 'z'.10 Have an applet launch an other applet . 'A' through 'Z'.html) <HTML><HEAD></HEAD><BODY> <APPLET CODE="AppletLoader. public class AppletLoader extends Applet implements Runnable. import java. 1. . . and '0' through '9' remain the same. AppletStub { String appletToLoad. display a message to the user and then load a larger Applet.applet. you must be connected to the Internet The decoding is incomplete but should be Ok for simple need! If you need to pass the message via the PARAM tag of the SecondApplet then take a look at this How−to.10 Have an applet launch an other applet Current version of this HowTo : http://www.setText(theMessage).

setText(s)..white).applet.start().sleep(2000). public class SecondApplet0025 extends java. } public void appletResize( int width.drawString("Loading the Second Applet . } catch (Exception e) { System. appletThread. realApplet.Applet { TextField tf.newInstance(). setBackground(Color. } public void start(){ appletThread = new Thread(this).forName(appletToLoad). } public void paint(Graphics g) { g. appletThread = null.0)).java for demonstration] import java.10 Have an applet launch an other applet . String s = getParameter("SecondAppletParm").println("Starting Second applet"). add(tf = new TextField( 10 ) ).println( e ). setLayout( new GridLayout(1. height ). add(realApplet).. int height ){ resize( width. } validate().".stop(). tf. } } 1. public void init() { System.public void init() { appletToLoad = getParameter("appletToLoad"). add(new Label("Second Applet")).awt. realApplet.out.*. 30). // Class appletClass = Class. Applet realApplet = (Applet)appletClass. } } [SecondApplet0025. } public void run() { try { // // REMOVE THIS // for demo purpose only to see // the "loading message! // Thread. realApplet.out.init(). 30.start(). } public void stop() { appletThread.setStub(this).

/javadetails/java−0048.security. // ex.security.. or in JDK1.. If you have access to a server−side.applet. System. } public void doit() { int i.rgagnon.auth.html In application : String username.util. 1. the search and search values // the URL http://myserver.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 Hashtable for easy reference./javadetails/java−0049.com/mypage. public class AppletUrlParams extends Applet { Hashtable searchparms.getProperty("user.println(NTSystem. See this related HowTo for a JSP hack! 1.html import java.try it here.11 Get the user name Current version of this HowTo : http://www.11 Get the user name . 1. import java.sun. String completeURL = getDocumentBase(). something like an ASP page can be used to detect the current NT user name if the client is configured correcty.rgagnon.auth. } } In Applet there is no way unless you ask for it or use a signed applet.name").module.sun.com/javadetails/.12 Access parameters passed in the URL Current version of this HowTo : http://www.*.*. username = System.com/javadetails/. public void init() { // dump to the console the URL.toString().NTSystem NTSystem = new com.get("value2") doit().out. String name = searchparms.5 public class Test { public static void main(String args[]) { com.module.NTSystem().getName()).

decode(st2.put(st2.com/applets/ IE: www. while( keys.nextToken().html and parameters.11 Get the user name .out.hasMoreTokens()){ String searchValue=st.System.html?winner=Maurice getDocumentBase () will return: NS: www. StringTokenizer st1 = new StringTokenizer(search. } } Test it here.domain.hasMoreTokens()){ StringTokenizer st2 = new StringTokenizer(st1.hasMoreElements() ) { String s = (String) keys.html?winner=Maurice 1. searchparms.println("Complete URL: " + completeURL). " while(st.substring(completeURL.out.println("−−−−−−−−").println("−−−−−−−−"). if (i > −1) { String searchURL = completeURL.out. System.URLDecoder. i = completeURL.5) it's ok.println("Search URL: " + searchURL).domain. } initHashtable(searchURL). StringTokenizer st = new StringTokenizer(searchURL.out.out. So: if we have www. "=").com/applets/win.nextToken(). System. The resultat in the Java console should be : key : firsparam value : Hello key : secondparam value : World key : thirdparam value : Hello World A note from mm300 Access parameters passed in the URL in line String completeURL = getDocumentBase(). java. } } public void dumpHashtable() { Enumeration keys = searchparms. dumpHashtable(). In IE (5.get(s)). System.indexOf("?").out. but only domain name and directory but without .toString().nextToken().nextToken())).println("key : " + s + " value : " + searchparms. } System. " while(st1. } } public void initHashtable(String search) { searchparms = new Hashtable().net.keys().nextElement().println("value :" + searchValue).com/applets/win. System. is a trap: NS won't return the whole URL.domain.indexOf("?") + 1).

13 Convert an Applet to Application Current version of this HowTo : http://www.setSize(100.class WIDTH=100 HEIGHT=100> </APPLET> /HMTL To be able to use the same class as an application.*. public class UnderlineText extends Applet{ String s = "Java Howto". import java. put it in Frame and call the init() method.applet. int x=20.. public class UnderlineText extends Panel{ String s = "Java Howto".*. ut.y). int x=20. UnderlineText ut = new UnderlineText(). seems enough for the Frame title.awt.init(). int y=50.100).awt.awt./javadetails/java−0305.exit(0).stringWidth(s) .WindowAdapter() { public void windowClosing(java.13 Convert an Applet to Application .show().pack(). we simply extend a Panel instead of an Applet. public static void main(String[] args) { Frame f = new Frame().rgagnon.com/javadetails/. g.event. }.drawLine(x . // same size as defined in the HTML APPLET f. int y=50. y+2 ).awt.drawString(s. f.setSize(100.html Take this simple Applet import java. } public void paint(Graphics g) { g.event.*. }). y+2 . public void init() { add(new Button("Real's")). f. f. x+getFontMetrics(getFont()).addWindowListener(new java. } 1. // add 20. x.add(ut).1. } } You use it with the following HTML <HTML> <TABLE><TR><TD> <APPLET CODE=UnderlineText. f. import java.WindowEvent e) { System. ut.100 + 20).

rgagnon.14 Change the mouse cursor in Applet Current version of this HowTo : http://www.WAIT_CURSOR)).2] // loop until the browser frame Frame browserFrame.rgagnon.y).net.drawString(s. x+getFontMetrics(getFont())..public void init() { add(new Button("Real's")). TEXT_CURSOR. DEFAULT_CURSOR.applet.html [JDK1. Component parentComponent.Applet.0. WAIT_CURSOR [JDK1. while ( parentComponent != null && !(parentComponent instanceof Frame)) { parentComponent = parentComponent. g. } browserFrame = (Frame) parentComponent.com/javadetails/.14 Change the mouse cursor in Applet .jpg" in the APPLET tag public class Tile extends Applet { 1.com/javadetails/.SE_RESIZE_CURSOR./javadetails/java−0233.drawLine(x .setCursor(Frame. N_RESIZE_CURSOR.. NE_RESIZE_CURSOR. // // // // TILE BACKGROUND in the HTML use : PARAM NAME="bgImage" VALUE="images/myImage. import java. } } 1. y+2 .stringWidth(s) . y+2 ).15 Use an Image as the Applet background Current version of this HowTo : http://www. SW_RESIZE_CURSOR. W_RESIZE_CURSOR./javadetails/java−0228. E_RESIZE_CURSOR. parentComponent = getParent(). 1. NW_RESIZE_CURSOR.*.getPredefinedCursor(Cursor. } public void paint(Graphics g) { g. browserFrame.getParent().html import java. S_RESIZE_CURSOR.1] // setCursor is supported at the component level setCursor(Cursor.WAIT_CURSOR). x. HAND_CURSOR MOVE_CURSOR. // // // // // // // CROSSHAIR_CURSOR.

} setLayout(new FlowLayout()). 1. 0. } } else { g. y = 0. this).height) { x = 0. x. y. 0).16 Handle the new Control Activation mechanism in IE . while(y < size().addImage (bgImage. removing the click to activate requirement in Internet Explorer. More at IEBlog 1.getWidth(null).16 Handle the new Control Activation mechanism in IE Current version of this HowTo : http://www.getHeight(null). tracker. while(x<size(). public void init() { try { MediaTracker tracker = new MediaTracker (this).height)..drawImage(bgImage.Image bgImage = null. add(new TextField(10)).clearRect(0. size().html Microsoft has now licensed the technologies from Eolas. } y=y+bgImage. } public void update( Graphics g) { paint(g). } catch (Exception e) { e.gif"> </APPLET> /HMTL Try it here. size(). tracker.class WIDTH=150 HEIGHT=150> <PARAM NAME="bgImage" VALUE="images/jht. bgImage = getImage (new URL(getCodeBase()./javadetails/java−0526. } public void paint(Graphics g) { if(bgImage != null) { int x = 0. getParameter("bgImage"))).printStackTrace(). This change will be made part of the next pre−release versions of Windows Vista SP1 and Windows XP SP3. add(new Button("Ok")). x=x+bgImage.width.rgagnon.width) { g.waitForAll(). } } } <HTML> <TABLE><TR><TD> <APPLET CODE=Tile.com/javadetails/.

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.2 Solution #2 As seen in this article. each interactive control must be individually activated. 1. or OBJECT elements to load an ActiveX control.16. Interactive controls loaded from external script files immediately respond to user interaction and do not need to be activated.The latest IE patch introduces a new behavior with APPLETS or ActiveX controls on a page. If a page uses these elements to load multiple controls.class" height="2000" width="196"></applet>') NOTE If you uncheck the Disable Script Debugging (Internet Explorer) option in the Advanced Tab of the Internet Options Control Panel. either click it or use the TAB key to set focus on it and then press the SPACEBAR or the ENTER key. When a web page uses the APPLET. A tooltip "Click to activate and use this control" is shown. 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> 1. all you need is to change the content from an outside file.16. the control's user interface is blocked until the user activates it.js"></script> </body> </html> and the myapplet. Then to activate an interactive control. they do respond to script commands.js is document. And now the same APPLET but with an external JS file here. 1. Check out this Microsoft's white paper on the subject. Both on the same page (same Applet). Try a page with the regular APPLET tag here. controls will still require activation. 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.write ('<applet code="MyApplet.1 Solution #1 . This was done to resolve an issue concerning a patent problem with a company called Eolas. EMBED. NOTE: While inactive controls do not respond to direct user interaction.

.write ('<applet codebase="' + urlApplet + '" code="myApplet. this is an interesting generic solution.3 Solution #3 . • For simple applet with no param.ediy. 1."> <p>This example "rewrite" the applet tag from an external JS.i++){ var el=v[i]. The enclosed dynamic PARAM parameters are generated by the JSP (ASP page).nz/internet−explorer−flash−applet−activation−fix−xidc19237.co./rewriteapplet.js] function writeHeader(urlApplet) { document.html offers a really small JS script (only 292 bytes long) to handle the situation.2" src=".. This site http://www. 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.length. [rewriteapplet.i<v.class"') document. the PARAMS can be handled by the main page like before! The trick is to have 2 external JS function.getElementsByTagName("applet").js] function rewriteApplet() { var v=document. Pre−XP SP2 installation are not supposed to do that kind of substitution (not verified!).js"> </script> <APPLET CODE="TextFieldWithLimitApplet.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 server−side.outerHTML } } Try it here! The same principle can be used for the OBJECT tag. IMPORTANT NOTES : • AFAIK.16. It looks that this behaviour has something to do with the fact that the Java plugin is an ActiveX.write (' width="100%" height="98%" hspace="0" vspace="0" align="middle" >') document.<BODY onload="rewriteApplet(). [rewriteapplet.class" HEIGHT=100 WIDTH=300> </APPLET> </BODY></HTML> The generic JS routine to rewrite all APPLET tags. This way you can generate the Applet tag from a JSP like before. el. <P> <script language="Javascript1.write 1. for(i=0. one to write the <APPLET> tag (and the static PARAM if any) and a second function to write the </APPLET>.outerHTML=el. The requirement is to write only the APPLET tag from an outside JS file.16.

isObjectInResult(idObject)) { int i = 1. } } else { %> <PARAM NAME="page1" value="<%=fileUrlErr %>"> <% } %> <script> writeFooter().next(). Open the Java control panel (in Windows: Start > Control Panel > Java) and select the Java tab.js"> /script . Press View button of the Applet Runtime Settings.2" src="<%= CONTEXT_PATH %>/scripts/rewriteapplet..hasNext()) { String url = (String) itPages. /script If you find this article useful..17 Pass parameters to the Applet JVM (WIN) .rgagnon. <script language="Javascript1. and add the required parameters in the 4th 1. consider making a small donation to show your support for this Web site and its content. Written and compiled by Réal Gagnon ©1998−2007 [ home ] 1. %> <PARAM NAME="page<%=i%>" value="<%=url %>"> <% i++... </script> <% if(resultVB..html It's possible to pass some parameters to the JVM in Applet but these have to be set in the browser and cannot be controlled by your applet. while (itPages. <script> writeHeader('<%=urlApplet %>').iterator().com/javadetails/.write('</applet>') } The JSP or ASP .(' } <PARAM NAME="printdialog" VALUE="false">') function writeFooter() { document. Iterator itPages = pages.17 Pass parameters to the Applet JVM (WIN) Current version of this HowTo : http://www. Each user that loads your applet has to adjust the JVM args themselves./javadetails/java−0531.

On the Windows plateform. In java control panel − java tab. You have to make sure that that the parameter you supply are correct./javadetails/java−0533.column.com/javadetails/.html The Java Console Window Log is also stored on disk. consider making a small donation to show your support for this Web site and its content.do?bug_id=4839812.sun. • Specify −Duser.com/bugdatabase/view_bug. you set a parameter for JRE Applet runtime. it is editable event if it's grayed.language=en to override the default locale in java control panel −> java tab. you set a parameter for JRE Applet runtime.18 See the Java Console Window Log (Java plugin) Current version of this HowTo : http://www.. You can force the language used in the Java console.18 See the Java Console Window Log (Java plugin) .rgagnon. This can be useful to set a JVM property to resolve a compatibilty problem with graphic card like in this bug report : http://bugs. it's in the folder : C:\Documents and Settings\ <username>\ Application Data\ Sun\ Java\ Deployment\ log It's a file with the extension . Written and compiled by Réal Gagnon ©1998−2006 [ home ] 1. If you find this article useful.trace 1. otherwise your browser will die when it tries to open the first applet.

click to set the parameter for the applet runtime (plugin).rgagnon./javadetails/java−0597.log/trace Written and compiled Réal Gagnon ©2007 real@rgagnon. Now add the following parameters in the column parameters. consider making a small donation to show your support for this Web site and its content. select Java Console −> Display the console.option=basic|net|security|ext|liveconnect Next. Written and compiled by Réal Gagnon ©1998−2006 [ home ] 1. −Djavaplugin.com http://www.If you find this article useful. the file is C:\Documents and Settings\[YourAccount]\Application Data\Sun\Java\Deployment\log\plugin[version].trace=true −Djavaplugin. The log is stored in a file.. On the Java tab.trace.com/javadetails/. The next time when loading an applet.19 Display debugging infos for an Applet Current version of this HowTo : http://www. the java console will display with a full trace.exe. For Windows.rgagnon.html Make sure that all browsers and JRE are closed.com 1.19 Display debugging infos for an Applet . Start the Java Configuration Panel via Start−Parameters or you can launch C:\Program Files\Java\jre[version]\bin\javacpl. on the Advanced tab.

getYear() + 1900.getInstance().println("Now : " + DateUtils.com/javadetails/..util.Calendar.. import java.util.com/javadetails/. 2 Date and Time . import java. } public static void main(String arg[]) { System.2 Have year on 4 digits from a Date object Current version of this HowTo : http://www. public class DateUtils { public static final String DATE_FORMAT_NOW = "yyyy−MM−dd HH:mm:ss".text.getTime()). } } Here some formatting possibilities available through the SimpleDateFormat class.3 Get the current Date and Time Current version of this HowTo : http://www. return sdf. mydate.1 java−date 2.rgagnon.out.now()).rgagnon.getTime())./javadetails/java−0106. import java.getYear() will return 100.Calendar. public class DateUtils { public static String now(String dateFormat) { Calendar cal = Calendar. SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW). int year = myDate.format(cal. So 100 + 1900 = 2000. return sdf. The getYear() method returns the number of years elapsed after the year 1900. 2. public static String now() { Calendar cal = Calendar. SimpleDateFormat sdf = new SimpleDateFormat(dateFormat).html import java.text.SimpleDateFormat.2 Date and Time 2.getInstance().SimpleDateFormat.format(cal. So for year 2000./javadetails/java−0096.html You need to add 1900 to it to get the 4 digit year.

public class TestDate { public static void main(String args[]){ /* ex . Date d2){ return ( (d2.println(DateUtils.getTime().now("H:mm:ss:SSS")).parseInt(args[4]) . System.println(DateUtils.MM.4 Compute days between 2 dates Current version of this HowTo : http://www. MMM d. public long daysBetween(Date d1..println(DateUtils. 0.out. System. System.out. Guirado for the idea. 0).now("yyyyMMdd")).*.out.out.out. } } 2. System. System.set(Integer.MM..println(DateUtils.out..now("yyyy. c1./javadetails/java−0097. c2. Calendar c2 = new GregorianCalendar().set(Integer.println(DateUtils. // need more error checking here.dd GGG hh:mm aaa")).println(DateUtils. java TestDate 1999 0 1 1999 8 1 to get days between 1999−01−01 and 1999−09−01 (remember months are zero−based.html import java.println(DateUtils.parseInt(args[2]).getTime() + ONE_HOUR) / (ONE_HOUR * 24)).z")). 0.. Integer..rgagnon. } } Thanks to T.out. System. } static final long ONE_HOUR = 60 * 60 * 1000L. 0). System.MMMMM.out. 2.println(DateUtils.parseInt(args[5]). } TestDate(String args[]) { Calendar c1 = new GregorianCalendar().now("h:mm a")). System.now("MM/dd/yy")).getTime()) + " day(s) between " + args[0] + "−" + args[1] + "−" + args[2] + " and " + args[3] + "−" + args[4] + "−" + args[5]).getTime() − d1.println (daysBetween(c1.now("dd.out.parseInt(args[3]).dd G 'at' hh:mm:ss z")). ''yy")).out. Integer.4 Compute days between 2 dates .now("yyyy.c2.yy")).. 0. Integer.now("EEE.now("K:mm a.now("dd MMMMM yyyy")). 0. System.println(DateUtils. Integer.parseInt(args[1]) .) */ TestDate a = new TestDate(args).parseInt(args[0]).println(DateUtils..} public static void main(String arg[]) { System. System.util.com/javadetails/.out.

GregorianCalendar overrides this function with a more efficient implementation. Hill for the tip.html 2.MONTH)]./javadetails/java−0099. See this HowTo.6 Validate a date Current version of this HowTo : http://www.html public static int daysInMonth(GregorianCalendar c) { int [] daysInMonths = {31. daysInMonths[1] += c.6. you can simply return getMaximum()).com/javadetails/.isLeapYear(c. One hour (known as the "fudge" factor) is added to the 2 Dates passed as parameters to take in account the possible DLS (Day Light Saving) one hour missing.30.getDateInstance (DateFormat. } catch (ParseException e) { return false. the Calendar class provides a method to that very simply.rgagnon. (Thanks to P..30. The "right" way would be to compute the julian day number of both dates and then do the substraction.YEAR)) ? 1 : 0.30.get(GregorianCalendar.31. Thanks to P.NOTE: The daysBetween() method works only on Dates set at midnight.. So it looks like it's a lot more efficient to call getActualMaximum from a GregorianCalendar object than a Calendar object.SHORT).1 Using DateFormat import java. } catch (IllegalArgumentException e) { return false.get(GregorianCalendar.getActualMaximum(calobject.com/javadetails/.31./javadetails/java−0098.31.*. 2. } Actually. return daysInMonths[c.30.text. // this is important! df. public class DateUtils { public static boolean isValidDateStr(String date) { try { DateFormat df = DateFormat. Harris for the tip) gregCalObject.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.31.5 Get the number of days in a month .getActualMaximum(gregCalObject. There is almost always a more efficient way to accomplish this (in most cases.rgagnon. // YYYY−MM−DD df.DAY_OF_MONTH) 2.31.31}.28.parse(date).5 Get the number of days in a month Current version of this HowTo : http://www. For a given Calendar or GregorianCalendar object : calObject. 2.setLenient(false).

isValidDateStr("1900−12−13".howto.println(" 1900−12−13 valid ? " + DateUtils.*.println(" 1900−12−13 valid ? " + DateUtils.out."yyyy−MM−dd")). import java. } catch (ParseException e) { return false.isValidDateStr("1900−12−13")). // "1990−13−12" throws a IllegalArgumentException System. } catch (IllegalArgumentException e) { return false.isValidDateStr("1900−12/13".out.parse(date). } public static void main(String[] args) { System.println(" 1900−13−12 valid ? " + DateUtils. /* * output : * 1900−12−13 valid ? true * 1900−12/13 valid ? false * 1900−13−12 valid ? false */ } } Using SimpleDateFormat package com. /* * output : * 1900−12−13 valid ? true * 1900−12/13 valid ? false * 1900−13−12 valid ? false */ } } 2.5 Get the number of days in a month . sdf.out.isValidDateStr("1900−12/13")).out. // "1990−12/13" throws a ParseException System.out. sdf. // "1990−13−12" throws a IllegalArgumentException System."yyyy−MM−dd")).} return true. } public static void main(String[] args) { System.isValidDateStr("1900−13−12")). } return true.println(" 1900−12/13 valid ? " + DateUtils.println(" 1900−12/13 valid ? " + DateUtils.out.isValidDateStr("1900−13−12".println(" 1900−13−12 valid ? " + DateUtils."yyyy−MM−dd")). // "1990−12/13" throws a ParseException System.rgagnon. public class DateUtils { public static boolean isValidDateStr(String date.setLenient(false). String format) { try { SimpleDateFormat sdf = new SimpleDateFormat(format).text.

set(GregorianCalendar./javadetails/java−0100. 2.DATE. newCal. 2003). int day = newCal.get( Calendar.rgagnon.printStackTrace().set(GregorianCalendar.setLenient(false).util.YEAR. } } } 2.get(Calendar.6.DAY_OF_WEEK).*.7 Determine to day of the week Current version of this HowTo : http://www.2. 1.getTime()).DAY_OF_WEEK_IN_MONTH ) newCal.get( Calendar.2 Using GregorianCalendar import java..set(GregorianCalendar. gc.get( Calendar.DAY_OF_YEAR ) newCal. // must do this gc.set(1997.6. gc.getTime(). int day = newCal.DAY_OF_WEEK ).DAY_OF_MONTH ) newCal. 2.// invalid month gc.get( Calendar. // exception thrown here } catch (Exception e) { e.rgagnon. /* also available : newCal.html add() and roll() are used to add or substract values to a Calendar object.com/javadetails/./javadetails/java−0101. 0. 0.DATE ) */ 2. For the day of the week for any date : Calendar newCal = new GregorianCalendar(). // BUG fix in Calendar class! newCal.get( Calendar. 42). 1).com/javadetails/. gc..2 Using GregorianCalendar . public class jtest { public static void main(String args[]) { try { GregorianCalendar gc = new GregorianCalendar().8 Add/Substract Day/Month/Year to a Date Current version of this HowTo : http://www.MONTH.setTime(newCal.html For the day of the week for today : GregorianCalendar newCal = new GregorianCalendar( ). 0).

The operation only affects the specified field while add() adjusts other Calendar fields.MONTH.getTime())).out. roll() makes january rolls to december in the same year while add() substract the YEAR field for the correct result.SimpleDateFormat(DATE_FORMAT). // 1998 dec 20 Thanks to P./javadetails/java−0102..20).out. // 1999 jan 20 System. 20).getDateInstance(). String DATE_FORMAT = "yyyy−MM−dd". // roll down the month c1. 20).getTime())).getTime())). Rehley for the bug fix.println("Date is : " + sdf. c1.SimpleDateFormat(DATE_FORMAT).text.MONTH.format(c1. −1).println ("Date roll down 1 month : " + sdf. We must set the TimeZone manually.set(1999. DateFormat df = DateFormat. // roll down.format(c1.println("Good TimeZone from Calendar : " + Calendar. substract 1 month System.getTimeZone(). java. System.roll(Calendar.println("Date + 20 days is : " + sdf. System.format(c1. // 1999 jan 20 System. Calendar.text. false).out.DATE.text.html There is a bug in the DateFormat/SimpleDateFormat classes. // 1999 jan 20 System.com/javadetails/. c1.rgagnon.getTime())).out. Calendar c1 = Calendar. c1.getID()). 0 .SimpleDateFormat sdf = new java.getInstance().out. // 1999 jan 20 c1. Calendar c1 = Calendar.println("Bad TimeZone from DateFormat : " + df.format(c1. System.getInstance().getTime())).println("Date is : " + sdf.getTime())).9 Get the correct TimeZone on DateFormat Current version of this HowTo : http://www.You specify which Calendar field is to be affected by the operation (Calendar.out. 2.getInstance(). To substract.format(c1.add(Calendar.set(1999.format(c1.9 Get the correct TimeZone on DateFormat . 0 . java.getTimeZone(). Calendar.println ("Date minus 1 month : " + sdf. See the following example.DATE). simply use a negative argument. the next larger field is modified when the result makes the Calendar "rolls over".text.out.add(Calendar.MONTH.set(1999. add() adds or substracts values to the specified Calendar field.YEAR.println("Date is : " + sdf. 0 .SimpleDateFormat sdf = new java. 20).getID()). // fix the TimeZone 2. // substract 1 month System. roll() does the same thing except you specify if you want to roll up (add 1) or roll down (substract 1) to the specified Calendar field. c1.out. String DATE_FORMAT = "yyyy−MM−dd".

2. 11 .*..get(GregorianCalendar.get(GregorianCalendar. System.set(1999.toString(d).11 Compare 2 dates Current version of this HowTo : http://www. 31)./javadetails/java−0104. } Thanks to Vladimir Garmaev for the bug fix Or you can use the SimpleDateFormat from the java.. import java. 2.*.text. import java.SimpleDateFormat./javadetails/java−0103.util.println("Today is " + sdf. Calendar c1 = Calendar.format(c1..DATE).df. String dd = Integer.out.getID()).Calendar.text.com/javadetails/.text package. import java.com/javadetails/.getTimeZone.text.html import java. // today System.println("Good TimeZone from DateFormat : " + df.util.text. public class TestDate { public static void main(String args[]){ String DATE_FORMAT = "yyyy−MM−dd".10 Simply format a date as "YYYYMMDD" . // remember months are zero−based : 0 jan 1 feb .YEAR) + (m < 10 ? "0" + mm : mm) + (d < 10 ? "0" + dd : dd). c2.. c1. public class TestDate { public static void main(String args[]){ String DATE_FORMAT = "yyyyMMdd".SimpleDateFormat sdf = new java.util. Calendar c1 = Calendar. } } 2.set(1999.getInstance().10 Simply format a date as "YYYYMMDD" Current version of this HowTo : http://www. public static String getStrDate(GregorianCalendar c) { int m = c. return "" + c. java. String mm = Integer.getInstance().out.rgagnon.MONTH) + 1. 30).getInstance()).*.getInstance(). import java.html The format "YYYYMMDD" can be useful when sorting records or comparing 2 dates.getTime())).rgagnon. Calendar c2 = Calendar.toString(m).get(GregorianCalendar. int d = c.setCalendar(Calendar. 0 .SimpleDateFormat(DATE_FORMAT). SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT).

text.12 Parse a String to obtain a Date/GregorianCalendar object . } System.util.out.Locale. } if (c1.out.Calendar.format(c1. SimpleDateFormat sdf = new java.setTime(d). /* output : Timestamp : 24−Feb−1998 17:39:35 Calendar : 1998−02−24 17:39:35 */ } } 2. cal.getInstance(). Calendar cal = Calendar.println("Calendar : " + sdf.System.print(" same as "). public class DateUtils { public static Calendar parseTimestamp(String timestamp) throws Exception { /* ** we specify Locale. } } 2.after(c2)) { System.SimpleDateFormat.getTime())).getTime())).out.Date. return cal.util.format(parseTimestamp(timestampToParse).out.SimpleDateFormat("yyyy−MM−dd HH:mm:ss"). if (c1.before(c2)) { System.com/javadetails/.print(" is after ").print(sdf.println(sdf.println("Timestamp : " + timestampToParse). System. } if (c1.util. java. } public static void main (String a[]) throws Exception{ String timestampToParse = "24−Feb−1998 17:39:35".html import import import import java.out./javadetails/java−0105. Locale. Date d = sdf.text.rgagnon.print(" is before ").out.US since months are in english */ SimpleDateFormat sdf = new SimpleDateFormat ("dd−MMM−yyyy HH:mm:ss". java. System. java.US).out.format(c2.12 Parse a String to obtain a Date/GregorianCalendar object Current version of this HowTo : http://www.equals(c2)) { System..getTime())).parse(timestamp).

import java. } public static String sayDayName(Date d) { DateFormat f = new SimpleDateFormat("EEEE").14 Get the day name Current version of this HowTo : http://www. } } See also this HowTo 2.com/javadetails/. import java. Date date2 = new Date().DateFormat.13 Use System time to generate unique ID Current version of this HowTo : http://www.DateFormat.OCTOBER. } } } An alternate way : import java.util. This can be solved by using the following technique to make sure that the number returned is unique (in a single JVM). } catch(Exception e) { e.text. public class UniqueID { static long current= System../javadetails/java−0403.text. Calendar.format(d).SimpleDateFormat.text. return "".com/javadetails/.html Since the granulaty of a PC can be as high as 55ms (down to 10ms). System. 17)).13 Use System time to generate unique ID . import java.printStackTrace()./javadetails/java−0385.out.*. static public synchronized long get(){ return current++.text.out. import java.rgagnon.Calendar. public class GetDayName { public static void main(String[] args) { Date date1 = (new GregorianCalendar (1989.util..SimpleDateFormat.currentTimeMillis(). try { return f. System.2.html import java.println("Today is a " + sayDayName(date2)). you can't use the System time to generate a unique ID because of the risk of getting duplicated IDs.rgagnon. 2.getTime().println ("1989−10−17 was a " + sayDayName(date1)).

util. 3268 (3268−01−22 G). loc).DateFormatSymbols.println("Today is a " + dayNames[date2.C.15 Find the current date format .println("The short date format is " + df.text. System.*.toPattern()).out. } } If you find this article useful.rgagnon. df = (SimpleDateFormat) DateFormat.com/javadetails/. 4713 B. import java. The purpose of the system is to make it easy to compute an integer (whole number) difference between one calendar date and another calendar date.D.980 years invented by Joseph Scaliger in 1583. consider making a small donation to show your support for this Web site and its content.out.html import java.980 year cycle)./javadetails/java−0506. negative year B.getInstance(). System. System.toPattern()). import java.15 Find the current date format Current version of this HowTo : http://www.html A Julian date is the number of elapsed days since the beginning of a cycle of 7.rgagnon. Locale loc = Locale. public class Dtest { public static void main(String args[]) { SimpleDateFormat df = (SimpleDateFormat) DateFormat. } } 2. public class JulianDate { /** * Returns the Julian day number that begins at noon of * this day.out. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 2./javadetails/java−0413.Calendar.*.getWeekdays().SHORT. Calendar date2 = Calendar. Positive year signifies A. 2.SHORT).get(Calendar.println("The short date format is " + df.C.DAY_OF_WEEK)])... The following day will begin the first day of the second Julian date period (or 7. nd will end on January 22. The starting point for the first Julian cycle began on January 1.getDateInstance(DateFormat.ITALY.import java.16 Get a julian date Current version of this HowTo : http://www.text.. public class GetDayName { public static void main(String[] args) { String dayNames[] = new DateFormatSymbols().com/javadetails/.util.getDateInstance(DateFormat.

year. * * ref : * Numerical Recipes in C.floor(365. int day=ymd[2]. return new int[] {year.Math.D.25). int julianYear = year.0 + ((jb − 2439870) − 122. Cambridge University Press 1992 */ public static int[] fromJulian(double injulian) { int jalpha.6001 * je). int month=ymd[1]. day = jb − jd − (int) (30. 15. } double julian = (java.jc. je = (int) ((jb − jd) / 30.Math. } public static void main(String args[]) { 2.ja.6001).floor(30.floor(julian). jc = (int) (6680. feb=2.. } else { julianYear−−.0). } /** * Converts a Julian day to a calendar date * ref : * Numerical Recipes in C. public static double toJulian(int[] ymd) { int year=ymd[0]... ja = ja + 1 + jalpha − jalpha / 4. if (year <= 0) year−−.lang.Math..1) / 365. 2nd ed. if (month > 2) { julianMonth++. if (year < 0) julianYear++. if (day + 31 * (month + 12 * year) >= JGREG) { // change over to Gregorian calendar int ja = (int)(0. month.25) / 36524. if (month > 12) month = month − 12.C. int julianMonth = month. jd = 365 * jc + jc / 4.jb.lang.* Remember that the year after 1 B.0. julianMonth += 13. month = je − 1. was 1 A. } return java..month. day}.25 * julianYear) + java.lang. 2nd ed.15 Find the current date format .6001*julianMonth) + day + 1720995. double julian = injulian + HALFSECOND / 86400. 1582 (2299161) public static int JGREG= 15 + 31*(10+12*1582).jd. public static double HALFSECOND = 0. } jb = ja + 1524. julian += 2 − ja + (0.5. ja = (int) injulian. // jan=1. if (ja>= JGREG) { jalpha = (int) (((ja − 1867216) − 0.25 * ja).je.25). year = jc − 4715. if (month > 2) year−−.day.01 * julianYear). Cambridge University Press 1992 */ // Gregorian Calendar adopted Oct.

many applications (especially mainframe systems) were storing dates in a format called "the Julian format"./javadetails/java−0547.YEAR). // THIRD TEST double date1 = toJulian(new int[]{2005.out.1}).17 Calculate the age . import java. // SECOND TEST today Calendar today = Calendar.out. since 17−July is the 221th day of the year.getInstance(). 17−July−1998 is stored as 98221. The main difference is the starting for counting the days..println("Julian date for today : " + todayJulian). 2. This format is a 5 digit number. 23 } )).. System. back to calendar : " + results[0] + " " + results[1] + " " + results[2]). This format is not really useful since Y2K! The main reason for using the 5−digits Julian date was to save disk space and still have a format easy to use to handle dates. 1968 : 2440000. // output : 2440000 int results[] = fromJulian(toJulian(new int[] {1968.0 .html import java. double todayJulian = toJulian (new int[]{today.17 Calculate the age Current version of this HowTo : http://www. back to calendar 2005 4 26 Between 2005−01−01 and 2005−01−31 : 30. results = fromJulian(todayJulian)..util.Calendar.GregorianCalendar. 5.rgagnon.DATE)}). Before Y2K.1. System..out.. If you find this article useful. For example.com/javadetails/.31}). consisting of a 2 digit year and a 3 digit day−of−year number. 5.get(Calendar.. You can have the Modified Julian Date (JD) or the Truncated Julian Date (TJD).0 days */ } } There is a lot of variation around the idea of a "Julian date". back to calendar 1968 5 23 Julian date for today : 2453487. today. double date2 = toJulian(new int[]{2005. today.util.get(Calendar. System.println("Julian date for May 23. 23 })).MONTH)+1. /* expected output : Julian date for May 23.println (". Written and compiled by Réal Gagnon ©1998−2005 [ home ] 2.println("Between 2005−01−01 and 2005−01−31 : " + (date2 − date1) + " days").println (".. back to calendar : " + results[0] + " " + results[1] + " " + results[2]).// FIRST TEST reference point System.. consider making a small donation to show your support for this Web site and its content.1..0 .get(Calendar. 1968 : " + toJulian( new int[] {1968.out. System.out.

<x> hours. long temp = 0. Calendar now = new GregorianCalendar(). if((cal.get(Calendar.rgagnon.get(Calendar.11.YEAR). <y> minutes and (z) seconds" */ public static String millisecondToDHMS(long duration) { String res = "".MONTH) == now.YEAR) − cal. } private static int age(int y..get(Calendar.out. m. System.MONTH) > now. } 2.11)). ONE_SECOND * 60.MONTH)) || (cal.get(Calendar. if (duration >= ONE_MINUTE) { res += ".com/javadetails/.public class CalcAge { public static void main(String [] args) { // remember .println ("1962−11−11 : " + age(1962. months are 0−based : jan=0 feb=1 .DAY_OF_MONTH) > now.18 Format a duration in ms into a string as "Days. System.get(Calendar.MONTH) &cal. private TimeUtils() { } /** * converts time (in milliseconds) to * "<w> days.get(Calendar. if (temp > 1) { res += "s". int m... d).18 Format a duration in ms into a string as "Days.get(Calendar.. } duration −= temp * ONE_DAY.println ("1999−12−03 : " + age(1999. int res = now.Hours. ". int d) { Calendar cal = new GregorianCalendar(y.minutes and seconds" . ONE_MINUTE * 60.html public class TimeUtils { public public public public final final final final static static static static long long long long ONE_SECOND ONE_MINUTE ONE_HOUR ONE_DAY = = = = 1000. } return res. if (duration >= ONE_SECOND) { temp = duration / ONE_DAY. ONE_HOUR * 24./javadetails/java−0585..minutes and seconds" Current version of this HowTo : http://www.3)). } } 2.DAY_OF_MONTH))) { res−−. if (temp > 0) { res = temp + " day".10.out.get(Calendar.Hours.

println(millisecondToDHMS ((4*ONE_DAY) + (3*ONE_HOUR) + (2 * ONE_MINUTE) + ONE_SECOND)).println(millisecondToDHMS ((5*ONE_DAY) + (4*ONE_HOUR) + ONE_MINUTE + (2 * ONE_SECOND) + 123)). /* output : 0 second 5 seconds 1 day. } } public static void main (String args []) { System. if (duration >= ONE_MINUTE) { res += ".out.out. System. 2 minutes 4 days. } } return res.println(millisecondToDHMS(ONE_DAY + ONE_HOUR)). } } temp = duration / ONE_SECOND. } duration −= temp * ONE_MINUTE. ". } } temp = duration / ONE_MINUTE. if (temp > 1) { res += "s".} temp = duration / ONE_HOUR. 1 hour 1 day. if (temp > 1) { res += "s".18 Format a duration in ms into a string as "Days. System. if (temp > 1) { res += "s". } else { return "0 second". 3 hours.out.out. if (temp > 0) { res += temp + " second". System. 2 minutes and 1 second 5 days. if (temp > 0) { res += temp + " hour".println(millisecondToDHMS((5* ONE_SECOND) + 123)).println(millisecondToDHMS(123)). } duration −= temp * ONE_HOUR. 1 minute and 2 seconds */ } } 2.println(millisecondToDHMS (ONE_DAY + ONE_HOUR + (2 * ONE_MINUTE))).out.out. if (temp > 0) { res += temp + " minute". System.Hours.minutes and seconds" . 1 hour. if(duration >= ONE_SECOND) { res += " and ". System. 4 hours.

openConnection().nist. return calendar.getInputStream())). java.28:13".parseInt(date[0])).163.io. in = new BufferedReader (new InputStreamReader(conn. public final class DateUtils { // NIST.MINUTE. 2000 + Integer. List of available time servers : http://tf. System.split("−"). while (true) { if ( (atomicTime = in.util. } catch (IOException e){ throw e.2.bldrdoc.split(":"). } } System.HOUR_OF_DAY. String[] time = fields[2]. import import import import java.rgagnon.19 Get the atomic time Current version of this HowTo : http://www. java.out. Boulder. systems that exceed this limit may be considered as attempting a denial−of−service attack. Integer.gov/service/time−servers. java.*.set(Calendar.parseInt(time[0]) + gmt). Systems that exceed this rate will be refused service. GregorianCalendar calendar = new GregorianCalendar()./javadetails/java−0589.readLine()).html NOTE : All users should ensure that their software NEVER queries a server more frequently than once every 4 seconds.gov) public static final String ATOMICTIME_SERVER="http://132.parseInt(time[2])). int gmt = (tz. Maryland (time−a.set(Calendar.split(" ").indexOf("*") > −1) { break.set(Calendar. String[] date = fields[1]. calendar.set(Calendar. Integer. } 2.parseInt(date[1])−1).gov) // public static final String ATOMICTIME_SERVER="http://129.net.*. String[] fields = atomicTime. Integer. calendar. calendar.out.*.println("DEBUG : " + gmt).MONTH.6.parseInt(date[2])).text. Gaithersburg.set(Calendar.println("DEBUG : " + atomicTime).html We connect to a publicly accessible time server on the internet and parse the result. calendar.*. Colorado (time−a.15.timefreq.SECOND. // NIST.101:13". calendar. Integer. public final static GregorianCalendar getAtomicTime() throws IOException{ BufferedReader in = null.19 Get the atomic time .getDSTSavings()) / 3600000. try { URLConnection conn = new URL(ATOMICTIME_SERVER).getRawOffset() + tz.YEAR. // deals with the timezone and the daylight−saving−time TimeZone tz = TimeZone. calendar. String atomicTime.nist. In extreme cases. Integer.com/javadetails/..getDefault().4.parseInt(time[1])).set(Calendar.DATE.

close().com http://www.println("Atomic time : " + sdf.bldrdoc.out.finally { if (in != null) { in.getTime())). } /* ref : http://www.getAtomicTime(). System. } } } public static void main(String args[]) throws IOException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy−MM−dd HH:mm:ss"). Month and Day // thanks to TrueJavaProgrammer for the idea! | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Written and compiled Réal Gagnon ©2007 real@rgagnon.com 2.gov/doc−tour/atomic_clock.rgagnon.19 Get the atomic time .format(DateUtils.0 UTC(NIST) * | These are the last + five digits of the Modified Julian Date Year.html 49825 95−04−18 22:24:11 50 0 0 50.

addItem("Option C").p3.1 java−awt 3. setLayout(new FlowLayout()). new FlowLayout().add(c2).blue. // Add cards 3 AWT . 100). TextField t1. // Main card (receive the other) p0 = new myPanel(new Color(0).add(t1).100) .*.addItem("Option A").addItem("Option B").100). t2.awt. Button b1. t1 = new TextField(8). p1.white). import java. public class CardLayoutDemo extends Applet implements ActionListener{ Panel p1. // The second Card p2 = new myPanel(new Color(0). Choice c1./javadetails/java−0237.b2. new FlowLayout(). Choice c1 = new Choice().addItem("Option 1"). // the third Card p3 = new myPanel(new Color(0).applet.3 AWT 3. 100. 100. new FlowLayout().p2.addItem("Option 2").html import java.rgagnon. c1. p3.*.2 Use The CardLayout manager Current version of this HowTo : http://www. t1. 100.event.white.awt.black.0).add(c1). 100). p2.b3.red. b4. c2.setBackground(new Color(0). c1. 100.p0. public void init() { // The first Card p1 = new myPanel(new Color(0). c2.*. c2. c2 = new Choice(). import java. new CardLayout(0.. add(p0).com/javadetails/.c2.

setBackground(co).show(p0.getLayout()). "First card"). } else i ++.addActionListener(this).getLayout()).addActionListener(this).getSource() == b3) { //Show the third list ((CardLayout)p0. p0. add(t2 = new TextField(2)).getSource() == b4) { // get the current card Component c[] = p0. } public Dimension getPreferredSize() { 3 AWT . add(b2 = new Button("card 2")).show(p0. } else if (e.getSource() == b2) { //Show the second list ((CardLayout)p0.h). } public Dimension getMinimumSize() { return new Dimension(w. p3).show(p0.add("2nd card". add(b3 = new Button("card 3")).p0.getComponents(). p1). int width.setText("" + (i+1)). p0.addActionListener(this). b2. } public void actionPerformed(ActionEvent e) { if (e. p2). int j = c. } else if (e.getSource() == b1) { //Show the first list ((CardLayout)p0. myPanel(Color co. "3rd card"). } else if (e. add(b4 = new Button("Which card is selected ?")). int h. w = width. int height){ super(). LayoutManager la.getLayout()).length. setLayout(la). b3. b1.addActionListener(this). while (i < j) { if (c[i].isVisible()) { t2. h = height. b4.add("First card".add("3rd card". add(b1 = new Button("card 1")). } } } } class myPanel extends Panel{ int w. int i = 0. break. "2nd card").

com/javadetails/.3 Detect which card is visible with a CardLayout . public PopupTest() { /* ** regular menu */ Menu m = new Menu("file").*. } } <HTML> <TABLE><TR><TD> <APPLET CODE=CardLayoutDemo.util.html [JDK1. m.add(item)./javadetails/java−0423.. return (i == comps. MenuItem item = new MenuItem("file−1"). } If you find this article useful..class WIDTH=300 HEIGHT=300> </APPLET> /HMTL Try it here.com/javadetails/.addActionListener(this)./javadetails/java−0238.awt. item.event. import java. item = new MenuItem("file−2"). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 3. consider making a small donation to show your support for this Web site and its content.length) ? null : comps[i].1] import java. 3.rgagnon.3 Detect which card is visible with a CardLayout Current version of this HowTo : http://www.length &!comps[i].getComponents(). 3.*. MouseListener { Hashtable popupTable = new Hashtable(). public class PopupTest extends Frame implements ActionListener.rgagnon.return new Dimension(w. import java. int i = 0.awt.Hashtable.4 Use Popups Current version of this HowTo : http://www. while(i < comps.html Component getComponentShowing(Container c) { Component[] comps = c.h).isVisible()) ++i.

println(" command=" + e.exit(0).red). MenuBar mb = new MenuBar(). } public void mouseClicked (MouseEvent e) { } public void mouseEntered (MouseEvent e) { } public void mouseExited (MouseEvent e) { } public void mousePressed (MouseEvent e) { mouseAction(e). 100).println("actionPerformed. System. p.println(" param=" + e.setBackground(new Color(0). addPopup(p. addPopup(b. setVisible(true). "North"). mb. setSize(100. add(b.getActionCommand()).out.out.add(item). } } ).paramString()). add(p.println(" source=" + e. "button"). addPopup(l. setMenuBar(mb). } 3. "Center"). /* ** button with popup */ Button b = new Button("button"). addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { System. /* ** panel with popup */ Panel p = new Panel().3 Detect which card is visible with a CardLayout . System.out. } public void actionPerformed(ActionEvent e) { /* ** handle actions related to popup */ System.m. add(l. setLayout(new BorderLayout()).add(m). System. "Panel"). /* ** label with a popup */ Label l = new Label("label"). event=" + e ).getSource()). "label"). "South"). } public void mouseReleased (MouseEvent e) { mouseAction(e).out.

mi2.getSize().get(c)).getComponent().add(mi2). } } /* ** */ initialize a Popup for a particular Component void addPopup(Component c.isPopupTrigger()) { PopupMenu pm = getHash(c).add(mi1). if (e./javadetails/java−0247.addMouseListener(this).height/2).put(c. pm. } PopupMenu getHash(Component c) { /* ** return a Popup associated with a particular Component */ return (PopupMenu)(popupTable. c.addActionListener(this). p). } } 3.5 Use a File Dialog Current version of this HowTo : http://www.com/javadetails/.show(c. c.rgagnon.*. public class UseFileDialog { 3.width/2.addActionListener(this).5 Use a File Dialog . } public static void main (String argv[]) { new PopupTest(). mi1. } void setHash(Component c. We must use the setFile method instead to set a filter. c.. pm. pm).add(pm). String name) { PopupMenu pm = new PopupMenu(). import java.void mouseAction (MouseEvent e) { /* ** determine if we have to show a Popup */ Component c = e. c. PopupMenu p) { /* ** associate a Component with a particular Popup */ popupTable. MenuItem mi1 = new MenuItem(name + "−1").getSize().html On the Win platform. pm. MenuItem mi2 = new MenuItem(name + "−2").awt. the setFilenameFilter method don't work. setHash(c.

String name){ return (name.getProperty("file. String fileType) { FileDialog fd = new FileDialog(f.. String defDir.setFile(fileType). fd.getFile(). replace return fd. "Save.getFile(). fd.setFilenameFilter(new FilenameFilter(){ public boolean accept(File dir.show()./javadetails/java−0270. title. 50).setLocation(50. fd.getFile(). "Open. fd.6 Use TrueType font Current version of this HowTo : http://www. title.public String loadFile (Frame f. 50).".SAVE). 3.setDirectory(defDir). fd.4] The names of the most common fonts supported by Java are TimesRoman.setLocation(50. Courier.\\". System. } }). String title. fd.java")).exit(0).".com/javadetails/. String title..\\".setDirectory(defDir).html [JDK1..setFile(fileType).gif")).rgagnon. "*. 3. ". fd.getDirectory() + System. FileDialog.saveFile(new Frame(). "*.endsWith(". } public String saveFile (Frame f.6 Use TrueType font .out. System. fd.loadFile(new Frame().getFile(). and Helvetica.out. return fd. String fileType) { FileDialog fd = new FileDialog(f. FileDialog.jpg") || name. } public static void main(String s[]) { UseFileDialog ufd = new UseFileDialog(). String defDir. System. return fd.println ("Loading : " + ufd. then you simply do : fd.java")).separator") + fd. ". setFilenameFilter may do the job..LOAD).. } } to work with the full pathname. On other plateforms.show().println ("Saving : " + ufd.endsWith(". by return fd.

To be able to use other fonts. I have a font called Kaufmann. on my system.getDefaultToolkit().i++ ) { System.BOLD. to check what are the fonts available. i < j .length. public class FontList { public static void main(String args[]) { String[] fontNames = Toolkit.length. 20)).i++ ) { System. Choose a font and doubleclick on it./javadetails/java−0278.getFontList(). On a Windows system. NOTE: The three common fonts are the only ones guaranteed to be supported across all systems. i < j .font file located in the lib of your JDK installation.*.7 Display available fonts Current version of this HowTo : http://www. [JDK1. public class FontList { public static void main(String args[]) { GraphicsEnvironment ge = GraphicsEnvironment. go in the Font applet in the Parameters folder. for (int i = 0 .awt. Check the name of the font. String fontNames[] = ge.rgagnon.font file in the section called # for backword compatibility. I add the following line in the properties.1] import java. To be able to use this font. Font.out.*. in a java program : setFont(new Font("Kaufmann".println(fontNames[i]). int j = fontNames.font file and these new fonts are not cross−plateform compatibles. For example.out.println(fontNames[i]).2] import java. } } } [JDK1. ANSI_CHARSET To use it. simply edit the properties.getLocalGraphicsEnvironment().0=Kaufmann BT. } } } 3. you must modify the properties.5] @todo 3. Kaufmann. for (int i = 0 .To add fonts.com/javadetails/.getAvailableFontFamilyNames().7 Display available fonts . the real name is "Kaufmann BT".html [JDK1..awt. int j = fontNames.

toClipboard(). g.0. 102.PLAIN. g. g. g. 100).setSize(600. 202).drawString("Real's HowTo".drawString("Real's HowTo".. } } <HTML> <TABLE><TR><TD> <APPLET CODE=SimpleApplet. f.awt.drawString("Real's HowTo".8 Font with 3D effect .0)).com/javadetails/.*.3. 42)). 100)./javadetails/java−0382. f. public class SimpleApplet extends Applet { public void init() { setBackground(new Color(255.setColor(new Color(0.8 Font with 3D effect Current version of this HowTo : http://www. 201).drawString("Real's HowTo".*. // black g. import java. // black g.datatransfer. 101.255.setFont(new Font("Helvetica".setColor(new Color(0.html import java. 101).*. // white } public void paint(Graphics g) { g. jc.awt. Frame f = new Frame ("Open a text editor and paste the message from Java").show(). 100./javadetails/java−0312. 100. 200).255)). // blue g.drawString("Real's HowTo".rgagnon.*.0. g.rgagnon.setColor(getBackground()).applet.class WIDTH=410 HEIGHT=500> </APPLET> </HMTL> try it here 3. 101.html import java.. g.com/javadetails/.9 Use the System Clipboard Current version of this HowTo : http://www. } 3. public class Java2Clipboard implements ClipboardOwner { public static void main(String[] args) throws Exception { Java2Clipboard jc = new Java2Clipboard().drawString("Real's HowTo".setColor(getBackground()).10). import java.setColor(new Color(0. Font. g. 100. g.awt.0.0)).255)).

getSecurityManager(). // minimize the frame Latest JDK provides more ways to do that. Frame frame = new Frame().err. Transferable tr) { System.rgagnon. getLocalGraphicsEnvironment().public void toClipboard() { SecurityManager sm = System. 3. GraphicsDevice device.4 import java. resize(Toolkit.printStackTrace(). } else { System.com/javadetails/. if ( device. } public void lostOwnership(Clipboard clip.println("Full screen not supported").isFullScreenSupported() ) { device.setContents(st.getDefaultToolkit().checkSystemClipboardAccess(). JDK1.*. to minimize or maximize a Frame.10 Maximize a Frame Current version of this HowTo : http://www.html // place this in the Frame constructor. after the show() this.4).*.awt. 3.println("Lost Clipboard Ownership?!?"). device = GraphicsEnvironment.getSystemClipboard().. if (sm != null) { try { sm.} } Toolkit tk = Toolkit.. } catch (Exception e) {e.ICONIFIED).setState(Frame.getScreenSize()). frame. this).2 offers a new method.awt.move(0. setState(). . Clipboard cp = tk. In this mode you can change the resolution import java.10 Maximize a Frame ./javadetails/java−0222. } The "full−screen" Frame is in exclusive mode. cp.0). JDK1. } } NOTE: You can only use text (no graphic) with this functionality provided by the current JDK (1. getDefaultScreenDevice().setFullScreenWindow(frame). StringSelection st = new StringSelection("Hello world from Java").GetDefaultToolkit().out..

Rectangle abounds = getBounds().REFRESH_RATE_UNKNOWN )). if (device.println("Full screen not supported"). super. To remove (manually) the "exclusive mode" on the JFrame : device. (dim. 8.MAXIMIZED_BOTH). 3. the original resolution is restored.height) / 2). getLocalGraphicsEnvironment().11 Center a Frame/Dialog .err.setExtendedState(Frame../javadetails/java−0223. // can be // frame.setFullScreenWindow(null).setFullScreenWindow(frame).setExtendedState(Frame. device = GraphicsEnvironment. getDefaultScreenDevice().setExtendedState(Frame. GraphicsDevice device.isFullScreenSupported() ) { device.11 Center a Frame/Dialog Current version of this HowTo : http://www.html // centers the dialog within the screen [1. setLocation((dim.com/javadetails/. } } } When the JFrame is destroyed.width − abounds. frame.getScreenSize(). 3.rgagnon. } public void doit() { Frame frame = new Frame().3 JFrame frame = new JFrame(). if ( device.isDisplayChangeSupported()) { device. } } else { System.height − abounds.MAXIMIZED_VERT).setVsible(true).MAXIMIZED_HORIZ).width) / 2.err. SWING jdk1. // bitDepth − 8 bits 256 colors DisplayMode.doit(). // frame.1] // (put that in the Frame/Dialog class) public void centerScreen() { Dimension dim = getToolkit().class ScreenRes { public static void main(String args[]) { new ScreenRes(). 768. } else { System.setDisplayMode( new DisplayMode( 1024.println("Change display mode not supported").

1 Method 1] public aFrame extends Frame implements WindowListener { public aFrame(){ addWindowListener( this ). super. if (parentSize. int y.getSize().2] public boolean handleEvent(Event evt) { if (evt. } // centers the dialog within the parent container [1.. } 3.width > mySize.com/javadetails/. Dimension mySize = getSize(). 3. } New with JDK1.setSize(100. y). f.WINDOW_DESTROY) { System.1] // (put that in the Dialog class) public void centerParent () { int x.setVsible(true). else y = topLeft.width − mySize. JDialog has method to position a JDialog relative to a parent.100).12 Close a Frame Current version of this HowTo : http://www. Dimension parentSize = myParent. } return super.x. requestFocus().x. setLocation (x.height > mySize. For a JWindow or a JFrame with no parent. then f.height − mySize. } [JDK1.id == Event.y. // Find out our parent Container myParent = getParent().width) x = ((parentSize.height) y = ((parentSize.getLocationOnScreen(). else x = topLeft.0.height)/2) + topLeft.12 Close a Frame .width)/2) + topLeft.rgagnon.exit(0)./javadetails/java−0225.setLocationRelativeTo(NULL). return true.handleEvent(evt).y.requestFocus().4. Point topLeft = myParent.html [JDK1. if (parentSize.

call the dispose() method instead.exit(0) may not be appropriate. "simple popup")./javadetails/java−0268.13 Call events on a Frame from a Panel .. } } For a Dialog or a Window.1 Method 3] public class aFrame extends Frame { public aFrame() { addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { System.rgagnon.13 Call events on a Frame from a Panel Current version of this HowTo : http://www.1 Method 2] public class aFrame extends Frame { public aFrame(){ addWindowListener( new Terminate() ).getWindow(). } } class Terminate extends WindowAdapter{ public void windowClosing(WindowEvent e){ System.exit(0).html 3. } 3.exit(0). this. } windowClosed(WindowEvent e){} windowIconified(WindowEvent e) {} windowDeiconified(WindowEvent e) {} [JDK1. } } ).addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { e. a System.com/javadetails/. } } [JDK1.dispose().exit(0). class SimplePopUp extends Dialog { SimplePopUp() { super(new Frame().public public public public public public public } void void void void void void void windowActivated(WindowEvent e){} windowDeactivated(WindowEvent e){} windowOpened(WindowEvent e){} windowClosing(WindowEvent e){ System. } } ).

setLayout(new FlowLayout()).width/4.b2.d. createFrame(). public class TestEventPanel extends Panel { Button b1. Button b1.*. p1.*. setBackground(new Color(0). add(b2). p1. [TestEventFrame. import java. WindowListener { TestEventPanel p1. b2 = new Button("close the parent frame").addActionListener(this). } } The Frame after adding the Panel. TestEventPanel(){ super().100). b1 = new Button("call event on the frame").awt. TestEventFrame(String title){ super(title).getScreenSize().event.addActionListener(this).b1. will act as an ActionListener for events for the 2 Panel buttons. The first button on the Panel will generate an event for the button on the Frame while the second panel button will trigger a request to close the Frame and the application.A component on a Panel can easily call events on the parent Frame. This way. // add the actionlistener b1.addActionListener(this). add(b1). addWindowListener(this). // the Panel with 2 buttons on it add(p1). a Frame contains 1 button and a Panel with 2 buttons on it.*.height/3). setLocation(d. } void createFrame() { Dimension d = getToolkit(). [TestEventPanel.awt.awt.java] import java. we can put all the logic in one place.java] import java.black). b1 = new Button("A dummy button"). } 3. setLayout(new FlowLayout()). import java.*.b2.awt. add(b1). setSize(400.13 Call events on a Frame from a Panel . public class TestEventFrame extends Frame implements ActionListener. p1 = new TestEventPanel().event. setVisible(true). In this example.

} if (ae.exit(0).getActionCommand()). } public void windowActivated(WindowEvent e) { public void windowDeactivated(WindowEvent e) public void windowDeiconified(WindowEvent e) public void windowClosed(WindowEvent e) { } public void windowIconified(WindowEvent e) { public void windowOpened(WindowEvent e) { } } } { } { } } and finally [Java0268.WINDOW_CLOSING))./javadetails/java−0246.Applet { TestEventFrame myTestEventFrame.println(ae.getActionCommand()). 3.b1) { System. public class Java0268 extends java.*.com/javadetails/.dispatchEvent (new_ae).getSource()==b1) { System.applet. b1. } } public void windowClosing(WindowEvent e) { this.awt..public void actionPerformed(ActionEvent ae){ if (ae. "Panel b1 is calling the dummy button").out. } } Try it here.out. so you are stuck with the JAVA coffee cup. public void init() { myTestEventFrame = new TestEventFrame("TestEvent Frame").html There is a bug in JDK1. processEvent(new WindowEvent(this.println("dummy receive :" + ae.getSource()==p1.14 Set the small top−left icon on a Frame Current version of this HowTo : http://www.getActionCommand()).b2) { System.0. System.14 Set the small top−left icon on a Frame .java] import java. } if (ae.dispose(). WindowEvent. 3.out. ActionEvent.2 for Windows.println(ae. ActionEvent new_ae = new ActionEvent (b1.rgagnon.getSource()==p1.ACTION_PERFORMED.

awt.1. 3.drawString("try to resize me. t. t. The GIF dimension should be 16x16. import java.*..rgagnon.gif")).getDefaultToolkit() .In JDK1.getDefaultToolkit(). To get the image from a Jar instead.getImage("myIcon.setVisible(true).com/javadetails/. You set the icon (probably in the Frame constructor) with : setIconImage(Toolkit. public class TestNoMaximize { MyFrame theFrame. 50.setSize(200. } public void paint(Graphics g) { g.*.getImage(getClass().html import java..event./javadetails/java−0252.". 50).awt. do : setIconImage (Toolkit.15 Prevent a Frame to be resized Current version of this HowTo : http://www.awt. public static void main (String args[]){ TestNoMaximize t = new TestNoMaximize().theFrame.*. import java. } } 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. } } ). this is fixed.theFrame = new MyFrame("A Dummy Frame").setResizable(false).awt.exit(0). You have to use a GIF file (not ICO file!). // no minimize or maximize this. getResource("images/myIcon. import java.gif"))). } } class MyFrame extends Frame { public MyFrame(String title){ super(title).15 Prevent a Frame to be resized . 3.200). addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { System.event..*. this.

getSize(). 3.getImage("images/jht.. 0).addImage(image..html A given image is tiled as the frame background.exit(0).setSize(200.getDefaultToolkit(). mt. addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { System./javadetails/java−0302.200). } } NOTE: These How−to may not work with the Microsoft JVM. t.*.event.getHeight() != 200 &d. import java.. } } ).awt. try { MediaTracker mt = new MediaTracker (this).200). // for Applet. this.*.". The result is not too good with Label.. import java.drawString("try to maximize me..setVisible(true).16 Embed an image into a Frame Current version of this HowTo : http://www. g.16 Embed an image into a Frame . } } class MyFrame extends Frame { public MyFrame(String title){ super(title).public class TestNoMaximize { MyFrame theFrame. change the method to retrieve the image // and of course use your own image! image = Toolkit.theFrame = new MyFrame("A Dummy Frame"). It's a feature.awt. if (d.. public static void main (String args[]){ TestNoMaximize t = new TestNoMaximize(). t.theFrame.rgagnon. 50.waitForID(0)..gif"). ImageFrame() { super("").com/javadetails/.getWidth() != 200) this. public class ImageFrame extends Frame private Image image. } public void paint(Graphics g) { Dimension d = this. 50). } { 3. mt.setSize(200.

while(x< getSize(). } } ).exit(0). // Label may not look too good .20)). x= x + image.height) { x = 0.drawImage(image. } } else { g.printStackTrace(). add(new Button("hello")).. 0. iframe. 500). System. add(new TextArea(20. add(new TextField(10)). } public void update( Graphics g) { paint(g).out.height). } public void paint(Graphics g) { if(image != null) { int x = 0. getSize(). y. setSize(500. add(new Label("Hello")). getSize().").getWidth(null). x. } } static public void main(String[] args) { ImageFrame iframe = new ImageFrame().clearRect(0.width. add(new List(20)).setVisible(true).. addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { // change this for an Applet System. } } The result : 3. } setLayout(new FlowLayout()).16 Embed an image into a Frame . this).getHeight(null).width) { g. } y = y + image. y = 0.catch (Exception e) { e. while(y < getSize().println("Bye.

With plain AWT. false : ok button only */ MsgBox(Frame frame. 3.new Label(msg)). pack(). public boolean isOk = false. import java. false). "Message". msg.awt. addOKCancelPanel(okcan).17 Display a message box . boolean okcan){ super(frame. setLayout(new BorderLayout()).html If using Swing then look at the JOptionPane component..com/javadetails/.can.event. import java. /* * @param frame parent frame * @param msg message to be displayed * @param okcan true : ok cancel buttons. createFrame().rgagnon.awt. String msg.3. add("Center".*. this simple class can be used as a Message Box. true).17 Display a message box Current version of this HowTo : http://www. setVisible(true).*. String msg){ this(frame. } MsgBox(Frame frame. public class MsgBox extends Dialog implements ActionListener { private Button ok./javadetails/java−0242.

ok.setSize(200. f.setLayout(new FlowLayout()). createOKButton( p )..rgagnon.getScreenSize().add(can = new Button("Cancel")).isOk) System. } } 3.getSource() == can) { setVisible(false). } } public static void main(String args[]){ Frame f = new Frame(). } public void actionPerformed(ActionEvent ae){ if(ae. message. if (message.isOk) System. can.com/javadetails/.d. true).} void addOKCancelPanel( boolean okcan ) { Panel p = new Panel(). } void createFrame() { Dimension d = getToolkit().println("Cancel pressed"). "Hey you user.getSource() == ok) { isOk = true.println("Ok pressed")./javadetails/java−0267.height/3).setVisible(true).addActionListener(this). } else if(ae.p). f. setLocation(d. } void createOKButton(Panel p) { p.200). if (!message.out.18 Display a Splash screen . p.dispose(). MsgBox message = new MsgBox (f .add(ok = new Button("OK")). if (okcan == true) createCancelButton( p ).html This Splash class display a window containing a specified image while a parent Frame is doing its 3. add("South".18 Display a Splash screen Current version of this HowTo : http://www. are you sure ?". } void createCancelButton(Panel p) { p.addActionListener(this).width/3.out. setVisible(false).

awt. tracker.blue.18 Display a Splash screen . result = tk. int w = imgWidth + (BORDERSIZE * 2). } class WindowListener extends WindowAdapter { // was windowActivated. } catch (Exception e) { e.waitForAll(). thanks to H. public class Splash extends Window { private Image splashImage.printStackTrace(). [JDK1. try { tracker.event.*. private int imgWidth. int y = (screenSize. String imgName) { super(f). w. this).getScreenSize(). 0).Grippa for the fix! public void windowOpened(WindowEvent we) { setVisible(false). private static final Color BORDERCOLOR = Color.getImage(imgName).drawImage(splashImage. the Splash window is destroyed.getWidth(this). this. h). y.awt. private static final int BORDERSIZE = 5.height − h) /2.addWindowListener(new WindowListener()). } public void showSplashScreen() { Dimension screenSize = tk. BORDERSIZE.getDefaultToolkit().initialization. } public void paint(Graphics g) { g. import java. imgHeight. BORDERSIZE. } public Image loadSplashImage() { MediaTracker tracker = new MediaTracker(this). tk = Toolkit. imgWidth. imgHeight. f. setVisible(true).1] import java. int x = (screenSize. dispose(). return (result). Image result. } } } 3. When the parent is activated. Toolkit tk.imgName = imgName. private String imgName.width − w) /2. public Splash(Frame f.addImage(result. } imgWidth = result. imgHeight = result. setBackground(BORDERCOLOR).getHeight(this).*. splashImage = loadSplashImage(). setBounds(x. showSplashScreen(). int h = imgHeight + (BORDERSIZE * 2).

i++) { System.gif) as the splash image. public MyFrame(String title){ super(title). } } ). i < 3000.awt.applet. } } class MyFrame extends Frame { Splash mySplash.19 Limit TextField input to numeric value .The following example use this image import java.*. import java.exit(0). public class app extends java.19 Limit TextField input to numeric value Current version of this HowTo : http://www.*.rgagnon.awt. "jht.*. } setSize(200. t.2] // You still have to trap the InvalidNumberFormat // Exception when converting textfield content to numeric // bug fixed! 980211 thanks to JM Guerra Chapa import java.0. public static void main (String args[]){ TestSplash t = new TestSplash().Applet { TextField textField1.. public void init() { setLayout(new FlowLayout()).200). } } 3. public class TestSplash { MyFrame theFrame.println(i) .setVisible(true).gif").out. 3. mySplash = new Splash(this. // dummy delay so we can see the Splash! for(int i = 0. (jht.html [JDK1. theFrame./javadetails/java−0226.event.com/javadetails/. addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { System. textField1 = new TextField(10). } private void createMainFrame() { theFrame = new MyFrame("A Dummy Frame").createMainFrame().awt.

isISOControl(c)) { // keep control character (like del.handleEvent(event). bksp) return super.KEY_PRESS) { char c = (char)event.1] thanks to Lionel Giltay import java.awt. _col) .isDigit(c)))) { e. } public NumericTextField (int _col) { this ("".19 Limit TextField input to numeric value . consider making a small donation to show your support for this Web site and its content.id == Event.getKeyChar() .handleEvent(event).VK_TAB) || (Character.target==textfield1 &event.event.addKeyListener(new KeyAdapter() { public void keyTyped (KeyEvent e) { char c = e. import java. if (c >= '0' &c <= '9') { // keep digit return super.consume() .VK_ENTER) || (c == KeyEvent. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 3. if (! ((c==KeyEvent.event.key. this. public class NumericTextField extends TextField { public NumericTextField (String _initialStr.add(textField1).KeyEvent .awt. } else { // discard Character return true. } else if (Character.VK_DELETE) || (c== KeyEvent. import java. } public boolean handleEvent(Event event) { if (event.KeyAdapter . } } }). _col) .TextField .awt.handleEvent(event). } } return super. } } [JDK1. } } If you find this article useful.VK_BACK_SPACE) || (c==KeyEvent. int _col) { super (_initialStr.

length(). this.maxLength). import java. } public void keyPressed(KeyEvent e) { char c = e.VK_ENTER)|| (c==KeyEvent.20 Limit TextField input to a maximum length Current version of this HowTo : http://www.event.int col.col).*.int maxLength) { this("". import java. addKeyListener(this)./javadetails/java−0227. public TextFieldWithLimit (String initialStr. } else { if((c==KeyEvent.awt. public class testENTER extends Applet implements KeyListener { 3.VK_DELETE) || (c==KeyEvent.awt.*.VK_TAB)|| e.rgagnon.rgagnon.isActionKey()) return.awt. else { e.html [JDK11] import java. int len = getText().VK_BACK_SPACE)|| (c==KeyEvent.com/javadetails/. } public TextFieldWithLimit (int col. public class TextFieldWithLimit extends TextField implements KeyListener { private int maxLength. import java.col.*..getKeyChar().com/javadetails/.*.*..3.awt.21 React to the ENTER key in a Textfield Current version of this HowTo : http://www.consume().20 Limit TextField input to a maximum length .html import java./javadetails/java−0253.maxLength = maxLength. if (len <maxLength) { return.int maxLength) { super(initialStr.event. } } } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { } } 3.applet.

TextField t.rgagnon.event. public void init(){ TextField t = new TextField("press ENTER").22 Make the ENTER key act like the TAB key .getKeyCode(). t.getDefaultToolkit(). import java.VK_ENTER) { Toolkit. System. if (key == KeyEvent. add(t). import java. } } } ).getDefaultToolkit().out. } } } Or the short version using the KeyAdapter class.awt. } public void keyTyped(KeyEvent e) {} public void keyReleased(KeyEvent e) {} public void keyPressed(KeyEvent e) { int key = e. } } 3. public class MyTextField extends TextField { MyTextField(int len) { super(len).addKeyListener (new KeyAdapter() { public void keyPressed(KeyEvent e) { int key = e.event.com/javadetails/. import java.VK_ENTER) { Toolkit. import java.out.22 Make the ENTER key act like the TAB key Current version of this HowTo : http://www.getKeyCode(). addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evt) { int key = evt.awt.VK_ENTER) 3. if (key == KeyEvent.getKeyCode().println("ENTER pressed").println("ENTER pressed"). t.*.awt.html First create a TextField that listen to the Enter and react like a Tab key [JDK11] import java.. System.applet.awt. public class testENTER extends Applet{ TextField t.addKeyListener(this).*. add(t).beep(). if (key == KeyEvent.*.*.beep().*. public void init(){ TextField t = new TextField("press ENTER")./javadetails/java−0254.

public void init() { add(t1= new TextField(20)). } } 3.*.getComponents().}}). TextField t3. add(t3= new TextField(20)). add(t1). } public void actionPerformed(ActionEvent ae) { if (ae.event.*. i++ ) { if (components[i] instanceof Container) 3.*. t4onPanel = new TextField(20). public void init(){ MyTextField t1 = new MyTextField(10). try something like this import java.add(t2).transferFocus(). Button b. public class TestEnterAsTab extends Applet { MyTextField t1. p1.applet.*. import java.setBackground(new Color(0). MyTextField t2 = new MyTextField(10). b. } public static void resetTextFields(Container c) { Component [] components = c. TextField t4onPanel.com/javadetails/. p1.23 Reset all textfields in one shot Current version of this HowTo : http://www.event. Panel p1.awt.23 Reset all textfields in one shot .length.rgagnon.awt. p1 = new Panel().html import java.*. i <components. add(b = new Button("reset TextFields")).yellow). public class FirstApplet extends Applet implements ActionListener { TextField t1.. t2.addActionListener(this). import java. add(t2= new TextField(20)). import java.applet.*. for (int i = 0./javadetails/java−0274. import java. TextField t2. } } to use it.add(t4onPanel). add(p1).awt.getSource() == b) resetTextFields(this).awt.

rgagnon. else if (components[i] instanceof TextField) ((TextField) components[i]).addKeyListener( new KeyAdapter() { public void keyPressed(KeyEvent e) { if (Character. tf.setModifiers(Event.24 Limit a TextField to Uppercase Current version of this HowTo : http://www.awt. public class UpperTF extends Frame { public static void main(String argv[]) { new UpperTF(). } } } <HTML><HEAD></HEAD><BODY> <APPLET CODE="FirstApplet. pack().1] import java.html [JDK1.awt. } public Dimension getPreferredSize() { return new Dimension(200. } } 3. } public UpperTF() { setLayout(new FlowLayout()).setVisible(true).resetTextFields((Container) components[i]) .setText("") ./javadetails/java−0279.getKeyChar())) e. } }).event.200)..isLetter(e.SHIFT_MASK).com/javadetails/.exit(0).*. } } ). addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System. TextField tf = new TextField(10).*.24 Limit a TextField to Uppercase . add(tf). import java.class" NAME="myApplet" HEIGHT=200 WIDTH=200> </APPLET></BODY></HTML> 3.

addImage(UPimage. setSize(w.getImage(up). public ImageButton(URL up_b.1)./javadetails/java−0245.com/javadetails/. Image UPimage.printStackTrace().1 and is a good example of the new Event architecture. boolean clicked. tracker.getWidth(this). addMouseListener(new ImageButtonMouseListener()). public class ImageButton extends Canvas { protected ActionListener actionListener = null.new ImageButtonDisableFilter())).getSource(). Image disabledimage. This ImageButton needs 2 GIF images representing the normal and pressed state ( ).getHeight(this). enabled=true.3.*.this). [ImageButton. } public void paint(Graphics g) { if (down) { g. Image DOWNimage. } disabledimage=createImage(new FilteredImageSource (UPimage.event.awt. } catch (InterruptedException e) { e.awt. addMouseMotionListener(new ImageButtonMouseMotionListener()). int w.awt. h=UPimage. boolean down. URL down_b) { clicked=false.0). import java.rgagnon.h.*. import java. InitImage(up_b.h).*. Also a method to disable the button by using a special filter is given. tracker.waitForAll(). DOWNimage = getToolkit().0. tracker = new MediaTracker(this). } else { 3.java] import java.down_b). import java. } public void InitImage(URL up.drawImage(DOWNimage. w=UPimage.25 Have an ImageButton Current version of this HowTo : http://www.. down=false.image.getImage(down).html This implementation of an ImageButton requires JDK1.0.*.net. URL down) { MediaTracker tracker.25 Have an ImageButton . try { UPimage = getToolkit(). boolean enabled. tracker.addImage(DOWNimage.

} } else { 3.if (enabled) { g.l).add(actionListener. l). down=true. repaint(). } if ((p. } } clicked=false.getPoint().x > 0)&&(p.drawImage(disabledimage.drawImage(UPimage.0.0.y > 0)&&(clicked==true)) { if (down==false) { down=true. repaint().this). if ((p.x > 0)&&(p.y < h)&&(p. } public class ImageButtonMouseListener extends MouseAdapter { public void mousePressed(MouseEvent e) { Point p = e. } } } public void setEnabled(boolean b) { enabled=b.getComponent().0.x < w)&&(p.remove(actionListener. } else { g.0.this).x < w)&&(p.actionPerformed(ae). repaint(). } public boolean isEnabled() { return (enabled).getPoint(). repaint(). } } public class ImageButtonMouseMotionListener extends MouseMotionAdapter { public void mouseDragged(MouseEvent e) { Point p = e.getPoint().25 Have an ImageButton .y > 0)&&(enabled==true)) { clicked=true.x < w)&&(p. if (down) { down=false. if (actionListener != null) { actionListener.y < h)&&(p.y > 0)&&(clicked==true)) { ActionEvent ae = new ActionEvent(e. if ((p."click"). } public void removeActionListener(ActionListener l) { actionListener = AWTEventMulticaster.x > 0)&&(p.y < h)&&(p.0. } } public void mouseReleased(MouseEvent e) { Point p = e. } public void addActionListener(ActionListener l) { actionListener = AWTEventMulticaster.

*.awt. int y. c = new Checkbox("disable"). repaint(). add(c). java.getWidth(this). Checkbox c. } } } } public Dimension getPreferredSize() { return (new Dimension(UPimage.setEnabled(!ib.awt.printStackTrace(). c.*.25 Have an ImageButton . public void init() { setLayout(new FlowLayout()). "Gumbyblu.applet.net. } public Dimension getMinimumSize() { return getPreferredSize(). add(ib). } } public void actionPerformed(ActionEvent e) { if (e. 3. public class TestImageButton extends Applet implements ActionListener.event. int rgb) { return (rgb &~0xff000000) | 0x80000000.*.gif").getSource() == ib) System. ib.gif")).out.ItemListener { ImageButton ib.isEnabled()).addItemListener(this). } } } [TestImageButton.println("Click ImageButton"). try { ib = new ImageButton (new URL(getCodeBase(). UPimage. } public void itemStateChanged(ItemEvent ie) { ib. } catch (Exception e) { e. "Gumby.getHeight(this))).*. new URL(getCodeBase(). } public int filterRGB(int x. java. } class ImageButtonDisableFilter extends RGBImageFilter { public ImageButtonDisableFilter() { canFilterIndexColorModel=true. java.addActionListener(this).java] import import import import java.if (down==true) { down=false.

int n. current. } } 3. public myListbox(int r. add(new Checkbox("Cash".26 Reset a checkbox group . int height.. (n) width. add(new Button("clear radio")). } public boolean action(Event e.com/javadetails/.applet. public class radio extends Applet { CheckboxGroup cbg. Object o) { if (o. false)).27 Set the listbox width Current version of this HowTo : http://www. int n.*. return true. cbg.awt. m. } return false. 10)).*. } public myListbox(int r. boolean m){ // (r) line number. new Font("Courier".26 Reset a checkbox group Current version of this HowTo : http://www. class myListbox extends List { int width.rgagnon.} } 3. cbg = new CheckboxGroup(). cbg./javadetails/java−0221.com/javadetails/. add(new Checkbox("Visa". height = r. boolean m.html The width can be specified via the preferredSize method. cbg. n.. false)). import java. false)). true)). Font f){ super(r. add(new Checkbox("American Express". This class lets you specify a font (fixed pitch) and calculate the appropriate width in pixels.m).rgagnon. add(new Checkbox("Mastercard".html import java. cbg./javadetails/java−0231. width = n.setState( false ). 3. cbg.getCurrent().equals("clear radio")){ Checkbox current = cbg.setCurrent( null ). height = r. public void init() { add(new Label("Payment mode?")). (m) multiselect this(r. Font.BOLD. width = n.

rgagnon. When inserting a line. in fact we have no choice because the maximum capacity is about 32k (Win). my./javadetails/java−0244.com/javadetails/.rgagnon. public void insertItem(List lbx.28 Align the column in a List Current version of this HowTo : http://www. It's a good idea to limit the amount of data kept in the List .28 Align the column in a List . Here the first column is 20 characters wide..substring(0.html The trick is to use a FIXED width character set like "Courier". } } 3. "STATUS".20−col1. In this snippet.10−col2. insertItem(ml. we are using a List component to display the data.charWidth('W')*width.BOLD. 3. String spaces20 = spaces10 + spaces10.29 Have a srolling text display Current version of this HowTo : http://www. ml = new List(). 10)). the second 10 and the last one the remaining.. String spaces10 = " ". import java. } public Dimension preferredSize (){ FontMetrics fm=getFontMetrics(getFont()). } In real life.length()) + spaces2 + col2 + spaces10. String col3) { String spaces2 = " ". fm.html A srolling text display can be used to log informations or events.getHeight()*height). we simply pad spaces as needed.*.setFont(new Font("Courier". lbx. the preferred way would be to extend the java.length()) + col3).com/javadetails/./javadetails/java−0271.awt.substring(0.setFont(f). We are keeping only the last 10 events. "ARCHIVE".List and override the addItem method.awt. "PORT"). 3. // the character W used as reference return new Dimension (fm. String col1.addItem(col1 + spaces20. Font. String col2.

l. } i++.com/javadetails/.30 Label dynamic resizing .setText ("A very long label"). LINE_DISPLAYED).*.makeVisible(LINE_DISPLAYED).LEFT)). aLabel. aLabel. l.addActionListener(this). aLabel. this.setSize(100.setText ("A very long label"). static final int LINE_BUFFERED = 10. With a Layout Manager. aLabel. 3. int i = 0.rgagnon. List l. While this method works in Netscape or the Appletviewer. static final int LINE_DISPLAYED = LINE_BUFFERED − 1.30 Label dynamic resizing Current version of this HowTo : http://www.validate().add(newLine.remove(0).preferredSize()). Label aLabel = new Label("short label"). } public void actionPerformed(ActionEvent ae) { String newLine = "Line #" + i. b. if (i <LINE_BUFFERED) { l. add(l = new List(5)).makeVisible(i)./javadetails/java−0232.import java. you have to validate() the layout to redraw the components invalidated.100). l. l.setForeground(new Color(0). // make sure the component is marked as non−valid this. on IE4/5 there is no resizing.resize (aLabel.yellow). public void init() { setLayout(new FlowLayout(FlowLayout. You may want to try this instead (thanks to Dan for the tip): Label aLabel = new Label("short label"). try something like this: aLabel. l.invalidate().black).awt. public class TelnetLikeDisplay extends Applet implements ActionListener { Button b. l. } else { l.addItem(newLine)..validate().setText(""A very long label").html If there is no Layout Manager installed.event. } } 3. add(b = new Button("New Line")).setBackground(new Color(0).

add(b1). t2. l = new Label("label text"). TextField t1. b2.50).*.100). add(p). Label l. b2 = new Button("Change drawString").event. MyPanel() { super(). import java.This example how to change a Label or a String drawn with the drawString method by clicking on a button. t1 = new TextField(10). // a Panel with a drawString call p = new MyPanel(). import java. b1 = new Button("Change Label"). } public void actionPerformed(ActionEvent e) { if (e. l.drawString(someString. t2 = new TextField(10).getSource() == b1) { l. add(t1). } if (e.30 Label dynamic resizing .someString = t2. add(l). add(t2).setText(t1.*. } public void paint (Graphics g) { g. public void init() { setLayout(new FlowLayout()). b1. p.applet. public class TestPaint extends Applet implements ActionListener { MyPanel p.addActionListener(this).awt.repaint(). } } } class MyPanel extends Panel { String someString = "drawstring". validate().invalidate(). b2. Button b1.*.getText(). add(b2). 10. } public Dimension getPreferredSize() { return new Dimension (100. } } 3.getText()).getSource() == b2) { p. import java.addActionListener(this).awt.

i<10. ChoiceEx() { super(""). 100 ..rgagnon.html import java. BorderLayout. setVisible(true). import java.. } // Set listeners choice.*. } // When list or choice is updated public void itemStateChanged(ItemEvent evt) { textarea. class ChoiceEx extends Frame implements ItemListener { Choice choice = new Choice(). import java. public class underlineText extends Applet{ String s = "Underlined text".addItemListener(this). i++) { choice.*.rgagnon. } } 3. BorderLayout.awt.SOUTH).33 Display underlined text Current version of this HowTo : http://www. } static public void main(String[] args) { new ChoiceEx().setText("Item #" + choice.awt.com/javadetails/. 3.html Simply create the TextArea with no horizontal scrollbar.com/javadetails/../javadetails/java−0258./javadetails/java−0281.applet./javadetails/java−0241.31 Make a TextArea "word−wrap" . 3.SCROLLBARS_VERTICAL_ONLY).event.html import java.addItem("item "+i).NORTH).*.3.*.rgagnon. 3 .awt. add(choice. TextArea textarea = new TextArea(). add(textarea. pack().getSelectedIndex()).31 Make a TextArea "word−wrap" Current version of this HowTo : http://www.32 Synchronize a TextArea vs a Choice Current version of this HowTo : http://www. myTextArea = new TextArea ("text". TextArea. for (int i=0.com/javadetails/.

3. g2d.drawString(s. else g. x. x+getFontMetrics(getFont()).substring(j).geom. g.0). public void init() {} public void paint(Graphics g) { v=g.Graphics2D.drawString(s. public void paint(Graphics g){ Graphics2D g2d = (Graphics2D)g.drawLine(x .substring(j. j++. public void init() {} public void paint(Graphics g) { g. int k= s.x.getHeight()+1.int x=10.com/javadetails/. } } Check this How−to for underlined text with a Label component. y+(j*v)).0.setToRotation(−Math. int j =0.rgagnon.drawString("Vertical text". width/2.awt.applet. // thanks to M. // clockwise 90 degrees AffineTransform at = new AffineTransform().0. import java. int v.j+1). int x=10.getFontMetrics(getFont()). height/2. y+2 .*. y+(j*v)).AffineTransform. Check this How−to for underlined text in Swing.length().html import java.stringWidth(s) . g2d.drawString(s. int y=10.setTransform(at). import java. } } } [JDK1.34 Display vertical text Current version of this HowTo : http://www. y+2 ).awt. 3./javadetails/java−0259. public class verticalText extends Applet { String s = "Vertical text".out.*. while(j < k+1) { if (j == k) g.y). y). x..awt.println(v).x.C. Henle for the bug fix! at.PI/2.4] import java. System.34 Display vertical text . int y=10.

MultiLineLabel. private String lines[]. right or center justified. Lines are separated byt the token "\n". // MultiLineLabel. false)./javadetails/java−0269. there is a possibility to have a border around the label. private int leftRightMargin. public static final int RIGHT = 2. private int line_ascent. private int line_height. The following class implements a multi−line Label. private boolean border. private int alignment. 0).util.rgagnon. Lines can be left.LEFT // default MultiLineLabel. boolean b) { // s the label // i alignement MultiLineLabel. public MultiLineLabel(String s.*. private int num_lines. Plus.RIGHT. private int line_widths[].black. import java. Graphics offGraphics. public static final int CENTER = 1. i. setBorder(b). private int topBottomMargin.CENTER. } 3. int i.awt.com/javadetails/.. private int max_width. private int x = 0. private int y = 0.html The Label component included in the AWT do not support "\n" in its definition.35 Have Label with many lines Current version of this HowTo : http://www. int i) { this(string. } public MultiLineLabel(String string) { this(string. public class MultiLineLabel extends Canvas { public static final int LEFT = 0. Color borderColor = new Color(0).} 3.LEFT // b border present or not setAlignment(i). } public MultiLineLabel(String string. } public MultiLineLabel() { this("".35 Have Label with many lines .*. private String text. setText(s). Dimension offDimension. 0). Image offImage. import java.

repaint().LEFT! if (i >= 0) leftRightMargin = i . } public void setLeftRightMargin(int i) { // make sense only if alignment is MultiLineLabel. if (d. } public void setFont(Font font) { super. } repaint(). calc().width == 0) d. if (d. num_lines * line_height + topBottomMargin * 2). calc(). return d.35 Have Label with many lines .height == 0) d. } } public int getLeftRightMargin() { return leftRightMargin.public void addNotify() { super. } 3. } public void setX(int i) { x = i. default: throw new IllegalArgumentException().addNotify(). } public void setTopBottomMargin(int i) { if (i >= 0) topBottomMargin = i. } public Dimension getMinimumSize() { Dimension d = new Dimension (max_width + leftRightMargin * 2.setFont(font). break. } public void setAlignment(int i) { switch (alignment) { case 0: case 1: case 2: alignment = i. } public Dimension getPreferredSize() { return getMinimumSize().height = 10. } public int getAlignment() { return alignment.width = 10. } public int getTopBottomMargin() { return topBottomMargin. public void setY(int i) { y = i.

height). if (f != null) { FontMetrics fm = getFontMetrics(f). i < num_lines. } public Color getBorderColor() { return borderColor.getAscent().getGraphics(). Dimension d = getSize()."\n"). if (fm != null) { line_height = fm.stringWidth(lines[i]).paint(g). lines = new String[num_lines]. 3.public boolean getBorder() { return border. num_lines = st. i++) { line_widths[i] = fm. calc(). line_widths = new int[num_lines]. } public void setText(String s) { // parse the string .width. line_ascent = fm.height) ) { offDimension = d. if (line_widths[i] > max_width) max_width = line_widths[i]. text = new String(s). } public void setBorder(boolean flag) { border = flag.countTokens(). i++) lines[i] = st. offGraphics = offImage.width) || (d. for (int i = 0. offImage = createImage(d. "\n" is a the line separator StringTokenizer st = new StringTokenizer(s. } } } } public void update(Graphics g) { super.getHeight(). d. if ( (offGraphics == null) || (d.35 Have Label with many lines . } public String getText() { return text. } public void setBorderColor(Color c) { borderColor = c. } private void calc() { // calc dimension and extract maximum width Font f = getFont(). repaint(). max_width = 0.height != offDimension.nextToken(). for (int i = 0. i < num_lines.width != offDimension.

RIGHT. Button b = new Button("Dummy"). offGraphics. offGraphics.this).blue).height − 1). f. offGraphics. true). f.width − 1.width − line_widths[k]. getSize(). } i += leftRightMargin.black). if (border) { offGraphics.add(mll1). break. f.drawString(lines[k]. switch (alignment) { case 0: i = 0. for (int k = 0.width − 1.width − line_widths[k]) / 2. y.add(b). } int j = line_ascent + (d.setColor(getBackground()).drawRect (x. j + y).} offGraphics. // mll1. ) { int i. false). MultiLineLabel mll2 = new MultiLineLabel ("123\n4\n567". } 3. i + x. MultiLineLabel.height − 1). getSize(). f.setForeground(new Color(0).validate(). break.setBackground(new Color(0). j += line_height.LEFT. MultiLineLabel.drawImage(offImage.200).setLeftRightMargin(15). mll2.setLayout(new FlowLayout()).setTopBottomMargin(15). MultiLineLabel mll1 = new MultiLineLabel ("This a test!\nsecond line\nthird line".35 Have Label with many lines .setVisible(true).fillRect (x.0. mll1. break. } g.setBorderColor(new Color(0). k++.add(mll2). case 2: i = d.setColor(borderColor). } public static void main(String args[]){ Frame f = new Frame("Test MultiLineLabel"). k < num_lines. getSize(). f. f.height − num_lines * line_height) / 2.yellow). offGraphics. } public void paint(Graphics g) { update(g). mll2. f. getSize(). y.setColor(getForeground()). mll1.setSize(200. default: i = (d.0.

g.getFont()).getFontMetrics(this. } } { [TestUnderlinedLabel.applet. super.*.height − this.getFont()).36 Have a Label with underlined text Current version of this HowTo : http://www.awt. public class UnderlinedLabel extends Label public UnderlinedLabel(){ this("").getDescent().rgagnon. } public UnderlinedLabel(String text){ super(text). r = g.html] <HTML><HEAD></HEAD><BODY> <APPLET CODE="TestUnderlinedLabel.getFontMetrics(this.drawLine (0. r.getText()). 3.html [UnderlinedLabel.getDescent()).com/javadetails/.36 Have a Label with underlined text .} 3. } } [testapplet.getClipBounds().getFontMetrics(this.paint(g). this. public class TestUnderlinedLabel extends Applet { public void init() { UnderlinedLabel ul1 = new UnderlinedLabel ("Java How−to").getFont()).*./javadetails/java−0272.java] import java.height − this.stringWidth(this.class" NAME="myApplet" HEIGHT=200 WIDTH=200> /APPLET/BODY/HTML Check this How−to for underlined text in Swing.java] import java.*. add(ul1). import java.awt. r. } public void paint(Graphics g) { Rectangle r..

*.url = new URL(url).getClipBounds().getDescent().awt. } } public void paint(Graphics g) { Rectangle r. private Color unvisitedURL = Color. r.blue./javadetails/java−0273.37 Have a Label acting as HTML HREF (URLLabel) Current version of this HowTo : http://www.getText()). String text. } public void setUnvisitedURLColor(Color c) { unvisitedURL = c.getFontMetrics(this.target = target.getFont()).*.getFont()).awt. } public void setVisitedURLColor(Color c) { visitedURL = c.height − this. r = g. } public URLLabel (Applet applet .height − this. this. private URL url.green. r.java] import import import import java. java. setForeground(unvisitedURL).applet. java. this.getFontMetrics(this.stringWidth(this. g.3.drawLine(0.net. String text){ this(applet. } catch (Exception e) { e.applet.applet = applet.getAppletContext(). public class URLLabel extends Label { private java. super.html [URLLabel.com/javadetails/.paint(g). } 3. url. java. "_self"). text. } class Clicked extends MouseAdapter{ public void mouseClicked(MouseEvent me){ setForeground(visitedURL).*.rgagnon.getDescent())..printStackTrace().showDocument(url. addMouseListener( new Clicked() ). String url. String target){ super(text). this. private String target = "".37 Have a Label acting as HTML HREF (URLLabel) . target).getFontMetrics(this.*. private Color visitedURL = Color.event.getFont()). public URLLabel(Applet applet . applet. String url. try { this.Applet applet.

"http://www. add(ull3).html import java. "Java How−to BigIndex").com/javadetails/java−0001.*.rgagnon. } 3./javadetails/java−0229. "Java How−to").} } [TestURLLabel.getImage(name). add(ull4). add(ull1).com/javadetails/. validate(). URLLabel ull2 = new URLLabel(this.38 Display a GIF in a Canvas .applet. "Java How−to 0001").class" NAME="myApplet" HEIGHT=200 WIDTH=200> </APPLET></BODY></HTML> Try it here.html". } } [testapplet. URLLabel ull4 = new URLLabel(this. "http://www. "Java How−to 0002"). public ImageCanvas(String name) { MediaTracker media = new MediaTracker(this).html".awt. 0).html] <HTML><HEAD></HEAD><BODY> <APPLET CODE="TestURLLabel. public class TestURLLabel extends Applet { public void init() { URLLabel ull1 = new URLLabel(this.*. "http://www. import java.*. "http://www. try { media.rgagnon. 3. import java.waitForID(0). public class ImageCanvas extends Canvas { Image image.rgagnon.rgagnon. add(ull2).com/javadetails/java−0002. media.*.awt.getDefaultToolkit().java] import java.addImage(image.rgagnon.38 Display a GIF in a Canvas Current version of this HowTo : http://www.com/bigindex.com/howto.html".image. image = Toolkit.awt.. URLLabel ull3 = new URLLabel(this.html".

rgagnon. mt. add(new Button("hello")). frame./javadetails/java−0302. public class ImageFrame extends Frame private Image image. change the method to retrieve the image // and of course use your own image! image = Toolkit.drawImage(image. this). frame. System.printStackTrace(). } public void paint(Graphics g) { g..gif").exit(0). import java. } } 3.resize(400.awt.*.waitForID(0).event.setLayout(new BorderLayout()).39 Embed an image into a Frame . frame. } catch (Exception e) { e.39 Embed an image into a Frame Current version of this HowTo : http://www.out. ImageFrame() { super(""). // for Applet. frame..class [image file name]").awt.400)..show().*.addImage(image. add(new TextField(10)).println ("usage: ImageCanvas. mt. new ImageCanvas(argv[0])). import java. } setLayout(new FlowLayout()). 0).add("Center".catch (Exception e) {} } public ImageCanvas(ImageProducer imageProducer) { image = createImage(imageProducer).html A given image is tiled as the frame background.getImage("images/jht.0. try { MediaTracker mt = new MediaTracker (this). The result is not too good with Label. } Frame frame = new Frame(argv[0]).getDefaultToolkit(). } public static void main(String argv[]) { if (argv.length <1) { System. { 3. 0.com/javadetails/.

drawImage(image. } public void paint(Graphics g) { if(image != null) { int x = 0. getSize().height) { x = 0. y. 500). add(new Label("Hello")).out. addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { // change this for an Applet System. } } else { g.add(new List(20)).").clearRect(0. this).width) { g.. x.getHeight(null). getSize(). System. iframe. add(new TextArea(20. while(x< getSize().39 Embed an image into a Frame . while(y < getSize(). } public void update( Graphics g) { paint(g). } } ). x= x + image. } } The result : 3.. 0.println("Bye. y = 0. setSize(500. // Label may not look too good . } y = y + image.width.height).20)).setVisible(true). } } static public void main(String[] args) { ImageFrame iframe = new ImageFrame().exit(0).getWidth(null).

.awt. java. 20.drawImage(allIcons. 3.drawImage(icon[0].html It's a good idea to combine small GIFs into a single big one to speed up the loading process.net. Image icon[] = new Image[iconCount].io. Image allIcons. int iconWidth = 16.*. In the following snippet.40 Load several images from a single GIF ./javadetails/java−0239. public void init(){ loadImages("item. I assume that all images are the same height and width.rgagnon. } public void paint(Graphics g) g.com/javadetails/.*. 0.*. java.gif"). g.applet. } { this). 0. public class strip extends Applet{ int iconHeight = 16. this). 0. java. You may want to get this GIF ( ) if you want to try the example on your workstation! import import import import java. g.3.drawImage(icon[1]. 0. int iconCount = 2.40 Load several images from a single GIF Current version of this HowTo : http://www. this). 40. public void loadImages(String s) { MediaTracker t=new MediaTracker(this).*.

0.getImage(u).this).getDefaultToolkit(). m.getResource(imgName).getDefaultToolkit().drawImage(allIcons.getResourceAsStream("img/image.getResourceAsStream("image..rgagnon. g.1).0).1 applet] Because of some security reason. } for (int i=0. } [JDK 1. Toolkit tk = Toolkit.0. Graphics g=z. 0).gif"). try { URL u=new URL(getCodeBase().com/javadetails/.iconWidth. img = tk.iconHeight).iconHeight). } catch (MalformedURLException me) { System.printStackTrace().getGraphics(). i++) { Image z=createImage(iconWidth.1 application] String imgName = "image. it's not possible with some browser (like Netscape) to use the getResource() method from an Applet.jpg".out. m.gif"). g. i < iconCount. } catch (InterruptedException e) { System.41 Load an Image from a JAR file . t. s).41 Load an Image from a JAR file Current version of this HowTo : http://www.allIcons=createImage(1. Image img = null. icon[i]=z. } try { t. try { MediaTracker m = new MediaTracker(this). Image img = null. allIcons=Toolkit.clipRect(0. URL imgURL = getClass().out. try { MediaTracker m = new MediaTracker(this).waitForAll().getImage(imgURL)./javadetails/java−0240. Instead we must use the getResourceAsStream method. // for example 3.−i*iconWidth.println("MalformedURLException: " + me).addImage(allIcons.addImage(img. // // if your image is in a subdir in the jar then // InputStream is = getClass().println("interrupted").html [JDK1.waitForAll(15000). InputStream is = getClass(). } catch (Exception e) { e. } } } 3.

com/javadetails/.10000).rgagnon.. m..getIcon("OptionPane. case 2: return UIManager.gif").addImage(img.waitForAll().getIcon("OptionPane. Remember that it is always possible to the Java built−in icons so that you don't have to include your own standard icons.createImage(byBuf)..getIcon("OptionPane. m.getIcon("OptionPane.getSystemResource(name)). byte[] byBuf = = new byte[10000].gif"). consider making a small donation to show your support for this Web site and its content.errorIcon"). int byteRead = bis. case 3: return UIManager.2 application] URL url = this.read(byBuf.printStackTrace(). } 3.getDefaultToolkit().0. 0). button. case 1: return UIManager.42 Load an Icon from a jar (again) Current version of this HowTo : http://www. // a buffer large enough for our image // // can be // byte[] byBuf = = new byte[is. or something like that.read(byBuf).// BufferedInputStream bis = new BufferedInputStream(is).questionIcon"). } [JDK 1. } } catch(Exception e) { e. img = Toolkit.warningIcon"). public static Icon getIconForType(int iconType) { switch (iconType) { case 0: return UIManager. } ImageIcon img = getImageIcon("resources/images/icone. } return null./javadetails/java−0436.informationIcon"). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 3.getResource("myIcon.getClass().setIcon(new ImageIcon(url)). // is.42 Load an Icon from a jar (again) .html public static ImageIcon getImageIcon(String name) { return new ImageIcon(ClassLoader. If you find this article useful.available()].

// java how−to image for example.*. Modern JDK has now a complete library devoted to graphic manipulation.43 Scale an Image Current version of this HowTo : http://www./images/jht.drawImage(resizedImage.replicate). 80. ImageProducer prod = new FilteredImageSource(source. media.com/javadetails/.geom. javax.addImage(source. Image resizedImage.image. rescale it to the passed parameters and writes the result in the specified output file.*.1).getWidth(this)/2. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 3.awt.0).waitForID(0). source.*. 3. half the original size ImageFilter replicate = new ReplicateScaleFilter (source.*.".awt.io.this). import java. media. The following exampe takes a JPG file as input .*. } } Try it here.*..43 Scale an Image . import java.this).awt. java. } catch(InterruptedException e) {} } public void paint(Graphics g) { g. public class app extends java. media. public void init() { MediaTracker media = new MediaTracker(this). java./javadetails/java−0243. import import import import import java. can be JPG source = getImage(getDocumentBase().awt..addImage(resizedImage.Applet { Image source. java. g. try { media.drawImage(source.imageio.gif"). resizedImage = createImage(prod).applet.getHeight(this)/2).waitForID(1).getSource().rgagnon.A list of what icons are available can be found here If you find this article useful. 10. // scale down.10.net.10. consider making a small donation to show your support for this Web site and its content.*.image.html import java.*.awt.

parseInt(args[2]).drawRenderedImage(bsrc.new File(dest)).out. BufferedImage. BufferedImage bdest = new BufferedImage(width. Graphics2D g = bdest.jpg Input: Ouput: 3.read(new File(src)).*."JPG".com/javadetails/.net. int width.at). ImageIO.public class ScaleJPG { public static void scale(String src. height.*. } catch (Exception e) { e. AffineTransform at = AffineTransform.TYPE_INT_RGB).*.write(bdest.*. 3.awt. String dest) throws IOException { BufferedImage bsrc = ImageIO. } public static void main(String[] args) { if (args.jpg 250 70 javahowto2..applet.html This example display a GIF with a fade−in./javadetails/java−0249. java. } } else { System. Integer.Integer. args[3]).44 Fade an image .image. g.rgagnon.scale (args[0].printStackTrace().getWidth(). import import import import java. } } } Example : >java ScaleJPG javahowto.getScaleInstance((double)width/bsrc.createGraphics().parseInt(args[1]). fade−out effect.awt.getHeight()). int height. (double)height/bsrc.length == 4) { try { ScaleJPG.44 Fade an image Current version of this HowTo : http://www. java. java.println("\nUsage: java ScaleJPG src width height dest\n").

sign. faded = this.setLevel(level).printStackTrace(). } catch (Exception e) { e. try { tracker. tracker. fis = new FilteredImageSource(img.0). } } public void fadeIt() { Graphics g = this. } catch (Exception ex) { ex. tracker.drawImage(faded. sign = sign * −1.gif")). } if (level &gt.44 Fade an image .addImage(faded.getSource(). AlphaFilter f. tracker. 20).sleep(1000). 0) { level=0. faded.0. int level. level += sign.printStackTrace().public class FadeImage extends Applet { Image img.0).start().waitForID(0). } class FadeThread extends Thread { 3. try { Thread.waitForID(0). ft. public void init() { level = 0. 255) { level=255.addImage(img. MediaTracker tracker.flush(). ft. } catch (Exception e) {} } f. } f = new AlphaFilter(). FilteredImageSource fis. sign = sign * −1. FadeThread ft = new FadeThread()./images/gumby.setLevel(level). if (faded != null) faded. tracker = new MediaTracker(this).delayedFading(this. try { img = getImage(new URL(getDocumentBase(). if (level &lt. ". f) .0. } repaint(). sign = 15.createImage(fis). f.. } public void paint(Graphics g) { if (faded != null) { g.getGraphics().this).

The applet assumes the dimension 32x32 for the image. } public int filterRGB(int x. } public void run() { while (true) { try { sleep(delay).printStackTrace(). import java.delay = delay. import java.FadeImage fadeApplet.net. Image rot = null.rgagnon.com/javadetails/. You may want to grap this image for testing purpose. int y.45 Rotate an image . fadeApplet. int buffer[] = new int[32 * 32].fadeApplet = f.Applet. public void delayedFading(FadeImage f.45 Rotate an image Current version of this HowTo : http://www. } } } Try it here. int rotate[] = new int[32 * 32].*. } catch (Exception e) { e. 3. this.applet. public class rotateGumby extends Applet { Image img = null. } } } } class AlphaFilter extends RGBImageFilter { private int level. int rgb) { int a = level * 0x01000000. int delay. return (rgb & 0x00ffffff) | a. } public void setLevel(int lev) { level = lev.html The following snippet rotates an image (90 degrees)./javadetails/java−0248. int delay) { this.fadeIt(). public AlphaFilter() { canFilterIndexColorModel = true. 3..

addImage (img.addImage(image. } public void paint(Graphics g) { g. } catch (Exception e) { e.*. 0. "gumby.geom. } catch(InterruptedException e) { e. 0).drawImage(rot. try { mt. 0.awt. 32.grabPixels(). } catch (Exception e) { e.event. } } rot = createImage(new MemoryImageSource(32. We are using the Java2D package (and Swing). 0. 40. 0).*.image = image. 32)).printStackTrace(). PixelGrabber grabber = new PixelGrabber(img.swing. g. rotate.printStackTrace(). 32.waitForID(0). tracker.*.this). img = getImage(new URL(getDocumentBase(). import import import import java. y++) { for(int x = 0. x < 32. java. mt. 0.waitForAll(). 32). } } public void update( Graphics g) { paint(g). this). try { grabber.45 Rotate an image .printStackTrace(). public class RotatePanel extends JPanel { private Image image. } } public void rotate() { 3.drawImage(img. } } The next example will rotate a picture 5 degrees at a time. javax. tracker. y < 32. } for(int y = 0. buffer. MediaTracker mt = new MediaTracker(this). 32. public RotatePanel(Image image) { this. x++) { rotate[((32−x−1)*32)+y] = buffer[(y*32)+x].*. java.0.awt.awt.gif")). private double currentAngle. 0.public void init() { try { MediaTracker tracker = new MediaTracker (this). 0.

gif").add(rotatePanel. } }). } } 3. public class apptest extends Applet { 3. BorderLayout.0) { currentAngle = 0. xRot.getHeight(this))/2.getContentPane(). //draw image centered in panel int x = (getWidth() − image. newXform.html JDK1. image.drawImage(image.getWidth(this))/2.getWidth(this).rgagnon. Graphics2D g2d = (Graphics2D)g.rotate(Math.applet. if (currentAngle >= 360. } public static void main(String[] args) { JFrame f = new JFrame(). import java.0.add(b.CENTER). cp. } repaint().awt. } protected void paintComponent(Graphics g) { super. x./javadetails/java−0230.setLayout(new BorderLayout()).getDefaultToolkit().setTransform(origXform).SOUTH). yRot). int y = (getHeight() − image. //center of rotation is center of the panel int xRot = this.rotate().46 Create a scrollable canvas . b.46 Create a scrollable canvas Current version of this HowTo : http://www. final RotatePanel rotatePanel = new RotatePanel(testImage).*..getHeight()/2. this).getImage("c:/temp/gumby. AffineTransform newXform = (AffineTransform)(origXform.getHeight(this)). g2d.getWidth()/2.getTransform(). f. cp. Image testImage = Toolkit. f.setVisible(true).clone()). BorderLayout. y. JButton b = new JButton ("Rotate").//rotate 5 degrees at a time currentAngle+=5.setTransform(newXform).paintComponent(g). int yRot = this.toRadians(currentAngle). cp. g2d. AffineTransform origXform = g2d.1 using a ScrollPane import java.pack(). g2d.com/javadetails/. Container cp = f.*.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { rotatePanel. } public Dimension getPreferredSize() { return new Dimension (image.

0.fillRect(0.black). 500). 42)). offscreen. this). offscreen.drawImage(buffImage.300). s.46 Create a scrollable canvas .setColor(Color.100).awt. myCanvas() { super(). public void init() { setLayout(new FlowLayout()). ScrollPane s. offscreen.white). s). } public void update(Graphics g) { g.black.createImage(500.drawImage(buffImage.setFont(new Font("Courier". public void init() { setLayout(new BorderLayout()).2 using a Canvas with Scrollbar import java. offscreen. c = new myCanvas(). s. else g. 0.getGraphics(). Color. sc = new ScrollCanvas (150.add(c). initDone = true.0. g. boolean initDone = false. } public void initpaint(Graphics g) { try { buffImage = this.ITALIC. c. offscreen = buffImage.setColor(Color. s = new ScrollPane(). 500). this).150. } catch (Exception e) { e.white).setSize(100. Font.0.setSize(500. Color. } } } } JDK1.0.200. Graphics offscreen. 0.drawString("Hello World!". this).Canvas c. 0. add(sc). offscreen.*. 50). } public void paint(Graphics g) { if (!initDone) initpaint(g). import java. 0.*. public class apptest extends Applet { ScrollCanvas sc. 500. 300. } class myCanvas extends Canvas { Image buffImage.printStackTrace(). 0.applet. } 3. add("Center".drawImage(buffImage.

setLayout(new BorderLayout()). 0. 3.vh). rw = rw1. 0. ScrollIncrement.public boolean handleEvent(Event e) { if (e.handleEvent(e). c = new myCanvas(vw. } } return super.getValue(). c).redraw().SCROLL_PAGE_DOWN: case Event.SCROLL_ABSOLUTE: case Event. rw. b = b1. // constructor // visible h w // real h w // background foreground ScrollCanvas (int vw1. sh). vh = vh1.VERTICAL. add("West". rh. vw = vw1. Color b. add("East". rh).getValue(). add("South". sh = new Scrollbar (Scrollbar. int rw1.SCROLL_LINE_UP: case Event. Color f1) { super(). rw).0. sv = new Scrollbar (Scrollbar.SCROLL_LINE_DOWN: sc. b . c. 0. } } class myCanvas extends Canvas { int vw.id) { case Event. int vh1. int ScrollIncrement = 10. Color b1.f.target instanceof Scrollbar) { switch (e.46 Create a scrollable canvas . sh. int rh1.vh.draw(x.SCROLL_PAGE_UP: case Event. f = f1. } } class ScrollCanvas extends Panel { int vw. sv). vh. } public void redraw() { int y = sv.HORIZONTAL. } public Dimension preferredSize() { return new Dimension(vw. ScrollIncrement.f). rh = rh1. myCanvas c. int x = sh. vh. Scrollbar sv. int rw.y). } public Dimension minimumSize() { return new Dimension(vw.rh. return true.vh).

} public void initpaint(Graphics g) { try { buffImage = this. 50).ITALIC. int rw1. rh = rh1. rw. x.createImage(rw.46 Create a scrollable canvas .fillRect(0.drawImage(buffImage. } } public void draw (int x1.. y = −y1. offscreen. int vh1. update(getGraphics()). y. 0.setColor(f). f. this). } } { 3. y.int rw. myCanvas (int vw1. rh. } public Dimension preferredSize() { return new Dimension(vw.. f = f1. g.0.drawImage(buffImage.0. rh). initDone = true.drawImage(buffImage.vh). Font. b = b1. Color f1) { super(). else g. this). rw = rw1. } public Dimension minimumSize() { return new Dimension(vw. repaint(). offscreen."). int rh1. offscreen. initDone = false. } catch (Exception e) { System. offscreen.out. Color b. Color b1. x. 0.drawString("Hello World!". } public void update(Graphics g) { g. this). int x. Graphics offscreen.println("oups. y. boolean initDone. Image buffImage.setColor(b). vh = vh1.getGraphics(). } public void paint(Graphics g) { if (!initDone) initpaint(g). offscreen = buffImage. 42)). offscreen. int y1) x = −x1. vw = vw1.vh). rh).setFont(new Font("Courier".

} public void update( Graphics g) { paint(g). 0). public void init() { try { MediaTracker tracker = new MediaTracker (this). } setLayout(new FlowLayout()). while(y < size().*.rgagnon. } public void paint(Graphics g) { if(bgImage != null) { int x = 0.printStackTrace().47 Use an Image as the Applet background .applet. size(). } catch (Exception e) { e.drawImage(bgImage.net. } } } <HTML> <TABLE><TR><TD> <APPLET CODE=Tile.getWidth(null). 0.height).height) { x = 0.addImage (bgImage.gif"> </APPLET> /HMTL 3. } y=y+bgImage.jpg" in the APPLET tag public class Tile extends Applet { Image bgImage = null..com/javadetails/./javadetails/java−0233. } } else { g.width. add(new TextField(10)). add(new Button("Ok")). x=x+bgImage. // // // // TILE BACKGROUND in the HTML use : PARAM NAME="bgImage" VALUE="images/myImage.waitForAll(). size().width) { g. tracker.Applet. bgImage = getImage (new URL(getCodeBase(). x. getParameter("bgImage"))).class WIDTH=150 HEIGHT=150> <PARAM NAME="bgImage" VALUE="images/jht. y. import java. y = 0. this). tracker.clearRect(0.3.getHeight(null).47 Use an Image as the Applet background Current version of this HowTo : http://www. while(x<size().html import java.

event. try { 3. add(lbx).gif|Powerbuilder How−to [application version] import import import import java. add(can).net. } } class AFrame extends Frame implements ActionListener { List lbx. setSize(800. MyCanvas can. media. public class ImageBrowser { public static void main(String s[]) { AFrame f = new AFrame(). can = new MyCanvas().48 Have a simple Image browser Current version of this HowTo : http://www.getImage(theUrl). java. // to close the Frame addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { System.getSelectedIndex()].awt.*. 0). Image image = Toolkit. java. public AFrame() { setTitle("Image selection.2)).addImage(image..rgagnon. // action on listbox double click lbx.gif|Javascript How−to pht.addActionListener(this).gif|JAVA How−to jsht.getDefaultToolkit().600).*.com/javadetails/. setLayout(new GridLayout(1. } public void actionPerformed (ActionEvent ae) { String theUrl = url[lbx.Try it here.awt.html [imagelist. double click to display"). } } ).48 Have a simple Image browser .*./javadetails/java−0277. setVisible(true).exit(0).io. java. MediaTracker media = new MediaTracker(this).txt] jht. initLbx().*. String url[] = new String[50]. lbx = new List(). 3.

util. repaint().media.drawImage(image. setLayout(new BorderLayout()). "Center").waitForID(0).*.} } public void initLbx() { int i = 0. java.48 Have a simple Image browser . java.event. // lbx.readLine())) { java. } public void setImage(Image i) { image = i. can. url[i++] = st.*. public MyCanvas() { super(). while(null != (aLine = in. "|").nextToken()). 0.txt")). private MyCanvas can. BufferedReader in = new BufferedReader(new FileReader("imagelist. 3. public class ImageBrowserApplet extends Applet { public void init() { APanel p = new APanel(this). } } NOTE : You can download this example here [applet version] import import import import import java. try { String aLine = "". } } catch(Exception e) { e.StringTokenizer(aLine.io. } } class APanel extends Panel implements ActionListener { private List lbx.printStacktrace().*.add(st.addItem(st.applet. } catch (Exception e) { e.awt.setImage(image).} } } class MyCanvas extends Canvas { private Image image.*.0.nextToken().*.awt.printStackTrace().net. lbx.nextToken()).util. java. java. } public void paint(Graphics g) { if (image != null) g. add(p. this).StringTokenizer st = new java.

0).util. while(null != (aLine = in.openStream())).getImage(theUrl). URL source = new URL(parent. public MyCanvas() { super().addActionListener(this). can = new MyCanvas().readLine())) { java. url[i++] = st.2)).} } } class MyCanvas extends Canvas { private Image image. } catch (Exception e) { e. private String url[] = new String[50].StringTokenizer(aLine. "|").add(st. "imagelist. } public void setImage(Image i) { image = i.addItem(st.nextToken()). setBackground(new Color(0).printStackTrace().48 Have a simple Image browser . } public void paint(Graphics g) { if (image != null) 3..getDefaultToolkit().printStackTrace(). can. initLbx(). media.waitForID(0).getCodeBase().white). MediaTracker media = new MediaTracker(this). repaint(). url[lbx.getCodeBase().private Applet parent = null.} } public void initLbx() { int i = 0.StringTokenizer st = new java. // action on listbox double click lbx. add(can). BufferedReader in = new BufferedReader (new InputStreamReader(source.getSelectedIndex()]).setImage(image). media. lbx = new List(). public APanel(Applet a) { parent = a. } } catch(Exception e) { e. setLayout(new GridLayout(1. // lbx.nextToken(). try { String aLine = "". } public void actionPerformed (ActionEvent ae) { try { URL theUrl = new URL(parent.nextToken()).util. lbx. Image image = Toolkit.txt"). add(lbx).addImage(image.

waitForAll().drawImage(image.drawImage(img1.*. [JDK1. addMouseListener(this). tracker. } } NOTE : You can try this example here 3.49 Simulate a "mouse over" event to toggle an image Current version of this HowTo : http://www.addImage(img1.rgagnon.0.g.html Use a special Canvas to preload 2 GIFs.getDefaultToolkit(). } catch (Exception e) { e.49 Simulate a "mouse over" event to toggle an image . this). MediaTracker tracker.event. tracker.this).. public ToggleGifCanvas(URL n1.0.this).net.1). index++.awt. } } } public Dimension getPreferredSize (){ return new Dimension (img1. } public void mouseClicked(MouseEvent e) {} 3. 0. tracker./javadetails/java−0264.getWidth(this)). img2. } } public void paint(Graphics g) { if (img1 != null) { if (index == 0) { g.printStackTrace().getImage(n2).0. import java.drawImage(img2. int index = 0.*.*. img2. } else { g.0.com/javadetails/.getDefaultToolkit(). public class ToggleGifCanvas extends Canvas implements MouseListener { Image img1.1] import java. img2 = Toolkit.0).addImage(img2. and using a MouseListener simply toggle the image.getHeight(this). index−−.awt.0. import java.getImage(n1). try { img1 = Toolkit. URL n2) { tracker = new MediaTracker(this).

Image image = Toolkit.html One way is to use a transparent GIF as the cursor or create one. Cursor transparentCursor = Toolkit.*. repaint().public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) { index = 1. } public void mouseExited(MouseEvent e) { index = 0. import java. new URL(getDocumentBase().*. } } } Try it here. 0).printStackTrace().gif"). new Point(0.createImage( new MemoryImageSource(16. 0.getDefaultToolkit()."images/gumby2. pixels. public void init() { try { tgc = new ToggleGifCanvas (new URL(getDocumentBase(). 16. import java. repaint().getDefaultToolkit(). "invisibleCursor"). public class TestToogleGifCanvas extends Applet { ToggleGifCanvas tgc.gif"))../javadetails/java−0440.applet.50 Hide the mouse cursor Current version of this HowTo : http://www. add(tgc).createCustomCursor (image.net. } } To use such Canvas. and import java. try something like this. 16))."images/gumby.awt.50 Hide the mouse cursor . } catch (Exception e) { e. 3.*. int[] pixels = new int[16 * 16].rgagnon.com/javadetails/. This example needs our Gumby GIFs ( ). 3.

applet. filter). [Transparency.*.. // image of our friend.gif").addImage(GifOriginalWithWithBlueBackground. import java. ImageProducer ip = new FilteredImageSource(im. } else { // nothing to do return rgb. public class Transparency { public static Image makeColorTransparent (Image im.0). All we have to do is to look for the blue color with the "Alpha bits" set to opaque and make them transparent.html Here we have an Image with a blue background like and we want to display it in an Applet with a white background.Applet { Image GifOriginalWithWithBlueBackground. public class app extends java. public void init() { setBackground(new Color(0). Gumby with a blue background GifOriginalWithWithBlueBackground = getImage(getDocumentBase().getDefaultToolkit().51 Make a color transparent . final Color color) { ImageFilter filter = new RGBImageFilter() { // the color we are looking for.getSource(). import java. Image GifModifiedWithTransparentBackground../javadetails/java−0265."gumbyblu.. GifModifiedWithTransparentBackground = 3. public final int filterRGB(int x.awt.3.awt.*.*.java] import java. import java. int y.rgagnon. int rgb) { if ( ( rgb | 0xFF000000 ) == markerRGB ) { // Mark the alpha bits as zero − transparent return 0x00FFFFFF &rgb.java] import java.createImage(ip).image.*.com/javadetails/.image.51 Make a color transparent Current version of this HowTo : http://www. try { media.white). return Toolkit.getRGB() | 0xFF000000.waitForID(0).*. } } }. Alpha bits are set to opaque public int markerRGB = color.awt. media. } } [app.net. MediaTracker media = new MediaTracker(this).awt.

Transparency. g.com/javadetails/.h). try { File f = new File("myimage.BufferedImage.jrf.0.getGraphics(). } catch (JimiException je) { je. With this package.10.52 Save an Image as a GIF or JPEG file .acme.html Take a look at the following package : http://www.this).jpg").nih. 3.com/essentialjpeg/jpeg.TYPE_INT_RGB)..52 Save an Image as a GIF or JPEG file Current version of this HowTo : http://www. 10.htm for JPEG http://www.} Another way is to use the undocumented com. Sun introduces a new package called JIMI (available for download at their Web site.obrador.rgagnon.codec. new Color(0). g.com for GIF http://rsb.w. double h = 200.0. it's easy to convert a Java Image to a JPEG image file. } } [x.makeColorTransparent (GifOriginalWithWithBlueBackground./javadetails/java−0266.sun.10.drawLine(0.drawImage(GifOriginalWithWithBlueBackground.new FileOutputStream(f)).getSource()).jpeg package.image.2] // img is a Java Image // BufferedImage bimg = null.info. JimiRasterImage jrf = Jimi.drawImage(GifModifiedWithTransparentBackground.2.gov/ij/ can display BMP and save as GIF or TIFF With JDK1. Graphics2D g = (Graphics2D)image. Jimi.createRasterImage(image.class" NAME="myApplet" HEIGHT=200 WIDTH=200> </APPLET> </BODY></HTML> 3.putImage("image/jpeg". // [JDK1.0. BufferedImage image = new BufferedImage( (int)w. double w = 200. } catch(InterruptedException e) {} } public void paint(Graphics g) { g.printStackTrace().html] <HTML><HEAD></HEAD><BODY> <APPLET CODE="app. 80.(int)h.this).blue).

getHeight(null). Since JDK1.imageio. instead of Image you use BufferedImage which is a subclass of Image. import javax.BufferedImage bufferedImage) throws IOException { ImageIO.h. JPEGImageEncoder jpeg = JPEGCodec. javax.read(file). 3.0. jpeg. With ImageIO.w.pixels.h. } public static void writeImageToJPG (File file. public class FileOperations { public static BufferedImage readImageFromFile(File file) throws IOException { return ImageIO. fos. // Encode as a JPEG FileOutputStream fos = new FileOutputStream("out.0.com/javadetails/.int w = img.h.BufferedImage.imageio.valueOf(getParameter("BGCOLOR").createJPEGEncoder(fos). import java. bimg.close().0.rgagnon. } } 3.intValue()). import java.*.TYPE_INT_RGB). int [] pixels = new int[w * h]./javadetails/java−0234.w. use // PARAM NAME="bgColor" VALUE="B8B5AE" // (where VALUE is the same hexadecimal value // as the HTML COLOR value) // in the APPLET tag // in the JAVA init method : Color bgcolor = new Color( Integer.encode(bimg). } bimg = new BufferedImage(w.grabPixels(). PixelGrabber pg = new PixelGrabber(img.4.0.53 Use the same background color as the browser Current version of this HowTo : http://www.w).*.ImageIO lets you save and restore Images to disk in a platform independent format.awt."jpg". setBackground(bgcolor).printStackTrace().w).2.file). int h = img.image.getWidth(null).html // in the HTML.. 16). "png" and "jpeg" format are supported.pixels.53 Use the same background color as the browser .write(bufferedImage.0. } catch(InterruptedException ie) { ie.io. try { pg.setRGB(0.*.jpg").

"images/gumby2.54 Do simple animation using Images Current version of this HowTo : http://www. } class AnimationThread extends Thread { AnimationGifApplet animationApplet.delayedAnimation(this. at.0. index = (index <maxImg) ? index + 1 : 0.54 Do simple animation using Images .0.awt. "images/gumby.1).*. } } public void animate() { repaint()./javadetails/java−0262. we switch between 2 GIFs ( and ) import import import import java.gif")).awt. tracker. } 3. java. } public void paint(Graphics g) { if (img[0] != null) { g.gif")). MediaTracker tracker.waitForAll(). int delay) { this. public void delayedAnimation(AnimationGifApplet a.net. at.addImage(img[1].length − 1.*. } catch (Exception e) { e. img[1] = getImage(new URL(getDocumentBase(). try { // images loading img[0] = getImage(new URL(getDocumentBase().*. this. tracker.delay = delay.com/javadetails/. int maxImg.printStackTrace(). } AnimationThread at = new AnimationThread(). int index = 0.this).0). tracker.image.addImage(img[0].drawImage(img[index]..rgagnon.html By using a Thread.animationApplet = a. java. public class AnimationGifApplet extends Applet { Image [] img.applet. java.*. 500).start(). tracker = new MediaTracker(this). public void init() { img = new Image[2]. int delay.3. // 2 images in animation maxImg = img.

} } } } } Try it here. tracker = new MediaTracker(this). java. using a Thread.addImage(img[0].gif")).image.animate(). int index = 0. 3.com/javadetails/. img[1] = getImage(new URL(getDocumentBase().event. "gumby.addActionListener(this). and public class AnimationProgress extends Applet implements ActionListener{ Image [] img.printStackTrace(). for example ( ). java.applet. tracker.awt. Click the button to simulate some work. } catch (Exception e) { e. // 2 images in animation maxImg = img.net. "gumby2. MediaTracker tracker.awt. java.rgagnon. boolean working = false. img = new Image[2].55 Do simple animation to show "work in progress" .. int maxImg. add(b = new Button("Working")). animationApplet.*. Button b.LEFT))./javadetails/java−0263. click again to terminate the "work in progress" [JDK1.55 Do simple animation to show "work in progress" Current version of this HowTo : http://www.*.awt. try { // images loading img[0] = getImage(new URL(getDocumentBase(). java.length − 1.gif")).*. b. we switch between 2 GIFs.html Like the previous How−to.*.0). public void init() { setLayout(new FlowLayout(FlowLayout.1] import import import import import java. 3.*.public void run() { while (true) { try { sleep(delay).

1).delay = delay. } public void actionPerformed(ActionEvent ae) { working = !working./javadetails/java−0257.0. } } } public void animate() { repaint().printStackTrace().animate().rgagnon. } class AnimationThread extends Thread { AnimationProgress animationApplet.com/javadetails/. } public void paint(Graphics g) { if (img[0] != null) { if (working) { g. int delay..addImage(img[1].tracker. } public void run() { while (true) { try { sleep(delay). this. } AnimationThread at = new AnimationThread().68. } catch (Exception e) { e.56 Get the color of a specific pixel Current version of this HowTo : http://www. at.56 Get the color of a specific pixel .drawImage(img[index].waitForAll(). 500). animationApplet. tracker. int delay) { this. } catch (Exception e) { e.animationApplet = a. public void delayedAnimation(AnimationProgress a. at. index = (index <maxImg) ? index + 1 : 0. 3.html We assume that we have an Image called picture pixels = new int[width*height].printStackTrace(). } } } } } 3.this).start().delayedAnimation(this.

btnUndo.getRGB(x..yl. // and the Java Color is . width).green. Graphics offGra.read(urlImage). try { pg.awt. Button btnClear.. pixels.y).BufferedImage . int c = image..Vector.*. int h = 200. btnClear = new Button("Clear").y1.util.awt.rgagnon. 3. Image offImg.. height. add(btnClear). Color c = new Color(red. setBackground(new Color(0). int green = (c &0x0000ff00) >> 8. public class SimpleCAD extends Applet { int w = 200. individual pixel can be accessed via the pixels array. int blue = c &0x000000ff. 0.image.. Vector lines = new Vector(). int np = 0.ImageIO. int green = (c &0x0000ff00) >> 8. 0.grabPixels().black). public void init() { setLayout(new FlowLayout()). int red = (c &0x00ff0000) >> 16.imageio. int x2. int xl. int c = pixels[index]. // and the Java Color is . int x1..blue). // or pixels[x * width + y] int red = (c &0x00ff0000) >> 16.57 Do "rubber−band" drawing Current version of this HowTo : http://www.*. } catch (InterruptedException e) { } From here..green.applet.blue).y2. 0. Color c = new Color(red. import java.com/javadetails/. width. import java.57 Do "rubber−band" drawing . add(btnUndo).html import java. btnUndo = new Button("Undo"). import java. Here another way to achieve this import javax.PixelGrabber pg = new PixelGrabber(picture. int blue = c &0x000000ff. BufferedImage image = ImageIO. 3./javadetails/java−0251.

white).white).blue). repaint().x. y1. if (offGra == null) { offImg = createImage(dim. } public void Dragupdate(Graphics g) { /* ** rubber−band effect */ g.width.elementAt(i). // begin an new drawing process x2 = −1.fillRect(0. p.57 Do "rubber−band" drawing .setColor(new Color(0). y1.y. e. i < np.MOUSE_UP: // end a drawing process lines. return true.null).drawLine(x1. // x2 y2 last current point x2 = e.setColor(new Color(0). offGra. offGra.y.width != −1) { offGra. } public boolean handleEvent(Event e) { switch (e.MOUSE_DRAG: // xl yl line to be erased xl = x2.drawLine(x1. i++) { Rectangle p = (Rectangle)lines.x.width. case Event.height).width. x2 = xl = −1.0.MOUSE_DOWN: // new starting point x1 = e.addElement(new Rectangle(x1. if (xl != −1){ // erase the old line g.0. } offGra. offGra = offImg.setForeground(new Color(0). case Event.height).black). } } // put the OffScreen image OnScreen g.getGraphics(). p. dim.drawLine(p.x. 3. if (x2 != −1) { // draw the new one g. } } } public void update(Graphics g) { // draw an offScreen drawing Dimension dim = getSize(). p. yl = y2. dim.dim.y.drawImage(offImg. offGra. np++.y)). y1 = e. setForeground(new Color(0).x.setPaintMode(). return true.id) { case Event. x2. e.setXORMode(getBackground()).height).0. y2 = e. if (p. y2). yl). xl. y1. for (int i=0.

repaint().println ( "hex: " + Integer. } public void undo() { if (np>0) { lines.parseInt(args[1]).Dragupdate(getGraphics()). int j = Integer. np−−.. } public boolean action(Event e.k). } } public void resetDrawing() { lines. np=0.println("Color2Hex r g b"). if (e. } return super. } } 3.parseInt(args[2]). Object o) { if (e. System.removeElementAt(np−1).target == btnUndo) undo()./javadetails/java−0250.awt..html 3. return true.length != 3) { System.out.*.59 Draw a line or set a pixel in my own image Current version of this HowTo : http://www.target == btnClear) resetDrawing(). repaint()./javadetails/java−0255. Color c = new Color(i. } else { int i = Integer.58 Convert RGB value to Hexadecimal (to be used in HTML for example) Current version of this HowTo : http://www.com/javadetails/.rgagnon. return true.handleEvent(e). int k = Integer.parseInt(args[0]). } } } 3.removeAllElements().getRGB() &0x00ffffff ) ).com/javadetails/.out.html import java.rgagnon.toHexString( c.j.58 Convert RGB value to Hexadecimal (to be used in HTML for example) . public class Color2Hex { public static void main( String[] args ) { if (args.

} } public void paint(Graphics g) { g.. i. (int) (x1+xincdashspace*counter+xincdash). } public void setPixel (Image image. Graphics g = myImage.fillRect( x. import java. y.int x2.x. g.drawLine(0. double yincdash=(y2−y1)/(linelength/(dashlength)).sqrt((x2−x1)*(x2−x1)+(y2−y1)*(y2−y1)). return.*. 1. i+=2){ setPixel(myImage. g.0.i<linelength−dashlength.i+=dashlength+spacelength){ g.int y1. i <x.awt. } if ((dashlength+spacelength)*counter<=linelength) g.getGraphics(). i. 1 ).x2. double spacelength) { if((x1==x2){ g.drawImage(myImage. (int) (y1+yincdashspace*counter+yincdash)).blue). new Color(0).image.0.0. new Color(0). int y.60 Draw a dashed line Current version of this HowTo : http://www.0. g.int x1.setColor( color ).drawLine((int) (x1+xincdashspace*counter). 50.y). double dashlength./javadetails/java−0224. Color color ) { Graphics g = image. g. 50.awt. int y = 100. for (double i=0.*.rgagnon.drawLine(x1. counter++.this).html public void drawDashedLine(Graphics g. setPixel(myImage. (int) (y1+yincdashspace*counter). for(int i=0.import java. double xincdash=(x2−x1)/(linelength/(dashlength)). double xincdashspace=(x2−x1)/(linelength/(dashlength+spacelength)). } double linelength=Math. int counter=0. double yincdashspace=(y2−y1)/(linelength/(dashlength+spacelength)). int x.int y2.60 Draw a dashed line . g. public class CreateAnImage extends Applet { Image myImage. 3.y). double yincrement=(y2−y1)/(linelength/(dashlength+spacelength)).dispose( ).getGraphics( ).green). } } 3.y2).drawLine((int) (x1+xincdashspace*counter).*. myImage = createImage(x.com/javadetails/.y1.applet.drawLine(x. public void init() { int x = 100. import java.0.y).

5. import java. getSize().setColor(c). 5.height.html import java.sqrt(dX * dX + dY * dY). ddx = −scale * (double)dY. new Color(0).width.width/2. 0. int dY = y2 − y1.*.width. getSize().height/2.height. getSize().. } 3. getSize(). double scale = (double)(thickness) / (2 * lineLength). dx.5 : −0. = (int)ddx. getSize(). int y1.5. // The double double ddx += ddy += int dx int dy x.black).. } public void drawThickLine( Graphics g. int x2.y increments from an endpoint needed to create a rectangle. public class thickLine extends Applet { public void init( ) { } public void paint( Graphics g ) { drawThickLine (g. 4).blue). int y2.awt.. new Color(0). drawThickLine (g. int x1.height/2. dx. getSize(). int thickness. (ddy > 0) ? 0.fillPolygon(xPoints.red).. dy.width. int xPoints[] = new int[4].5.*. getSize(). 0. Color c) { // The thick line is in fact a filled polygon g.com/javadetails/. // Now we can compute the corner points.61 Draw a line with a thickness . } 3.height. int dX = x2 − x1.applet.y2). 0. dy. int yPoints[] = new int[4]. x2.. 0. dx.5 : −0. getSize(). yPoints[0] yPoints[1] yPoints[2] yPoints[3] = = = = y1 y1 y2 y2 + − − + dy. getSize(). 8. new Color(0). 0. getSize(). drawThickLine (g.61 Draw a line with a thickness Current version of this HowTo : http://www.rgagnon. new Color(0). = (int)ddy. (ddx > 0) ? 0. drawThickLine (g. ddy = scale * (double)dX. 12. dy. 0. // line length double lineLength = Math. xPoints[0] xPoints[1] xPoints[2] xPoints[3] = = = = x1 x1 x2 x2 + − − + dx. g.(int) (y1+yincdashspace*counter).green).width/2. yPoints./javadetails/java−0260.

61 Draw a line with a thickness .setStroke(new BasicStroke(width)). getContentPane(). BasicStroke bs = new BasicStroke(width).0.draw(new Line2D. 200).} Using JDK1.*.0.awt. public TestLine() { setSize(200.0. 100.setStroke(bs).add( panel. tl.*. public class TestLine extends JFrame{ private MyPanel panel. 100. public MyPanel(){} public void paintComponent( Graphics g ){ Graphics2D g2 = (Graphics2D)g.swing. 10.0f).0. } } class MyPanel extends JPanel { final static BasicStroke stroke = new BasicStroke(2. l.getGraphics(). 50.VALUE_ANTIALIAS_ON). g2d.0. int width = 10. y1. l.draw(new Line2D.KEY_ANTIALIASING.setStroke( stroke ).drawLine(x1. y2).Double(10. g2.3 import javax. JLabel l = new JLabel(). g2. "Center" ).setVisible( true ). RenderingHints.0. import java. } } 3.geom.0)).100.0.setRenderingHint (RenderingHints. final static BasicStroke wideStroke = new BasicStroke(8. import java. g2. g2. 10.setStroke( wideStroke ).2 public void paint(Graphics g){ Graphics2D g2d = (Graphics2D)g. panel = new MyPanel(). } On a Component int width = 10.0)). g2d.0f).drawLine(0. Using JDK1.*.Double(10. x2. g2. 50. } public static void main( String [] args ){ TestLine tl = new TestLine().100).awt.

colors. Graphics offGraphics. c). Color.yellow). Color.valueOf(s.hasMoreTokens()) { s = t.getMinimumSize(). c. numSlices = 0. } } class PieChartCanvas extends Canvas { /* ** author Ciaran Treanor ciaran@broadcom. colors. public void init() { float value. at = getParameter("depth").put("blue". Color. colors. Color. value = Float. colors.html import java.com/javadetails/. add("Center".green).red).put("black". String s.3.put("yellow".floatValue().62 Draw a pie chart Current version of this HowTo : http://www. i = s. String at = getParameter("width"). PieChartCanvas c = new PieChartCanvas(radius. Color. (Color)colors.put("white". Color. called = 1.put("red". radius..pink).valueOf(at)." StringTokenizer t = new StringTokenizer(at. Color.white). import java. while (t.magenta).cyan).util. 3.value−color. colors.applet.blue).put("pink".getMinimumSize().addSlice(value. Color. // Create Hashtable to map color name (String) to Color type Hashtable colors = new Hashtable().orange). colors. at = getParameter("values"). ".substring(i + 1))).Applet. // "value−color./javadetails/java−0261.rgagnon.put("green".width. int i.nextToken(). Color. radius = (at != null) ? Integer.").intValue() : 100. colors. Color. float total = 0. Color color[] = new Color[10]. colors..awt.put("orange". colors. } resize(c.height)..*.*.62 Draw a pie chart .ie */ final double aspectFudge = 2. import java. depth = (at != null) ? Integer. int radius. i)).substring(0.put("cyan".5. depth. value[] = new float[10]. public class Graph extends Applet { int depth. depth).black).put("magenta". colors. setLayout(new BorderLayout()).. Image gfxBuff.indexOf('−').intValue() : 20. c.get(s.valueOf(at).

} g. total += value. } } [JavaPie. int depth) { this.value = value.drawImage(gfxBuff. this. d. d. } public Dimension getPreferredSize() { return getMinimumSize(). x−−) { startAngle = −45. offGraphics.getGraphics().round(360 * (value[i] / total)). i++) { offGraphics. startAngle += angle.color = color.fillArc(0.fillArc(0. this. offGraphics. } public void paint(Graphics g) { int startAngle. this.width. x >= 1. i < numSlices. (int)angle). radius. 0. offGraphics = gfxBuff. (int)angle).width. this.height). x. angle = Math.62 Draw a pie chart . (int)(radius / aspectFudge).color[numSlices++] = color.class WIDTH=150 HEIGHT=150> 3. } // do the 3d effect for(int x = depth.setColor(color[i].setColor(color[i]). startAngle += angle. for(int i = 0. startAngle.depth = depth.fillRect(0. (int)(radius / aspectFudge).public PieChartCanvas(int radius. Color color) { this. i++) { offGraphics. } public void addSlice(float value. 0. i < numSlices.darker()). d.hmtl] <HTML> <TABLE><TR><TD> <APPLET CODE=Graph.height). if(gfxBuff == null) { gfxBuff = createImage(d. null).round(360 * (value[i] / total)). (int)((radius / aspectFudge) + depth)).value[numSlices] = value. angle = Math. 0. float angle.radius = radius. for(int i = 0. startAngle. } } // draw the pie slice startAngle = −45. 0. radius. offGraphics.setColor(getBackground()). } public Dimension getMinimumSize() { return new Dimension(radius. Dimension d = getSize(). offGraphics.

0.awt.5−green.rgagnon./javadetails/java−0364. g. } t=System.valueOf(t).add(BorderLayout.63 Draw faster rectangles . } public void actionPerformed(ActionEvent p1){ repaint(0.i++){ g. g.currentTimeMillis()−t.i<10000. } } 3. import java.70.drawRoundRect(10..i<10000.63 Draw faster rectangles Current version of this HowTo : http://www. Button b=new Button("Refresh").10.drawString(String.100. c. for(int i=0. long t=System.) 1.<PARAM NAME="depth" VALUE="30"> <PARAM NAME="width" VALUE="120"> <PARAM NAME="values" VALUE="1−red..event.valueOf(t).10.setSize(300.50.200.300). t=System. c.com/javadetails/. c. public class Class1 extends Frame implements ActionListener{ public void paint(Graphics g){ super.*.drawString(String.currentTimeMillis().7−blue"> </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 3.5 faster then drawRect(….70).) .100. } public static void main (String[] args){ Class1 c=new Class1().addActionListener(c).10. because one of them is completely native.300).setLayout(new BorderLayout()).drawRect(10.show().awt. } t=System.paint(g).130). import java.i++){ g.*.currentTimeMillis()−t. for(int i=0.html Thanks to Chikirev Sergey It seems that drawRoundRect(….SOUTH .currentTimeMillis(). b).50). b. c.130.0).

png"). 15.awt.getY().createScreenCapture( new Rectangle( myframe.io.jpg"). java.getDefaultToolkit()./javadetails/java−0489. java.createScreenCapture( new Rectangle( 15.html The screen capture is done with java. ImageIO./javadetails/java−0605.com/javadetails/. myframe. // ImageIO. consider making a small donation to show your support for this Web site and its content. 150. } } To capture a specific area BufferedImage screencapture = new Robot().getWidth().64 Get a screen capture and save it as a JPEG . Written and compiled by Réal Gagnon ©1998−2005 [ home ] 3.getHeight() ) ). 150)). javax.getX(). // Save as JPEG File file = new File("screencapture.write(screencapture.awt. // Save as PNG // File file = new File("screencapture. myframe.Toolkit.ImageIO.awt.com/javadetails/. "jpg". file). To capture a specific visual object BufferedImage image = new Robot().image. file).awt. IOException { // capture the whole screen BufferedImage screencapture = new Robot().. java.getScreenSize()) ).awt.rgagnon. "png".3.*.imageio.Robot. If you find this article useful..BufferedImage.write(screencapture.65 Display a TIF Current version of this HowTo : http://www. java. java.AWTException.awt.Rectangle.createScreenCapture( new Rectangle(Toolkit.Robot. import import import import import import import java. myframe.rgagnon. class ScreenCapture { public static void main(String args[]) throws AWTException.html 3.64 Get a screen capture and save it as a JPEG Current version of this HowTo : http://www.

media. channel. if (args.Image. RenderedImage im = dec.wrapRenderedImage(im).. java. com.codec. GIF. ByteBuffer buffer = ByteBuffer.media.getChannel()..sun.jai.showInputDialog(null.awt.ByteBuffer.media. java. It will also display other types (JPG. // JOptionPane.media. } FileInputStream in = new FileInputStream(path).jai.The regular JDK can only deal with JPG. import javax.JLabel. To deal with TIF file.println("image: " + path + "\n" + image).PlanarImage.read(buffer). Image.length==0) { path = JOptionPane.ImageDecoder.nio.allocate((int)channel.SCALE_SMOOTH). java. } public static void main(String[] args) throws Exception{ String path. String[] names = ImageCodec.nio.media. ImageDecoder dec = ImageCodec.io.sun. import javax. SeekableStream stream = new ByteArraySeekableStream(data).jai.getDecoderNames(stream). import javax. import import import import import import import import import import javax.array()). FileChannel channel = in. com.decodeAsRenderedImage(). see this HowTo. "Image Path". public class ImageViewer { static Image load(byte[] data) throws Exception{ Image image = null.JOptionPane.sun.64 Get a screen capture and save it as a JPEG .codec.out.swing. null). // System.FileInputStream.getAsBufferedImage().) by detecting the type. return image.ImageCodec.tif").jai.SeekableStream.swing.jai.sun. "c:/applications/sidebar. java. new JLabel( new ImageIcon( imageScaled )) ). } else { path = args[0].codec. BMP or PNG file with the package ImageIO. // make sure that the image is not too big // scale with a width of 500 Image imageScaled = image.ImageIcon.getScaledInstance(500. stream. This example will display a given TIF file.channels.swing.ByteArraySeekableStream.image.RenderedImage. Image image = load(buffer.showMessageDialog(null. −1.createImageDecoder(names[0]. java. com.awt. you must use the JAI (Java Advanced Imaging) package.FileChannel. } } 3.size()). image = PlanarImage. com..codec.

codec.getNumPages(). This is done with the JAI (Java Advance Image) package.JAI. import import import import import import import import com.66 Convert a multi−page TIF into single−page TIF Current version of this HowTo : http://www.renderable.sun.sun.media.TIFFEncodeParam.awt.tif"). This HowTo takes a multi−page TIF (from a FAX) and convert it into many single−pages TIF. int count = dec. ImageDecoder dec = ImageCodec.media.jar and jai_codec. TIFFEncodeParam param = new TIFFEncodeParam().image. for (int i = 0.doitJAI().out.media.image.media. public class TestTiff { public static void main(String[] args) throws IOException { new TestTiff()./javadetails/java−0535.jai.dev.jar http://java. null).codec.html Tagged Image File Format (abbreviated TIFF) is a file format for mainly storing images. rather than have each company promulgate its own proprietary format.The JAI package is composed of 2 jars : jai_core.66 Convert a multi−page TIF into single−page TIF .com/javadetails/.jsp > import java.media.COMPRESSION_GROUP4).java.RenderedImage.media. including photographs and line art.decodeAsRenderedImage(i).ImageDecoder. 3.createImageDecoder("tiff".FileSeekableStream.. i++) { RenderedImage page = dec.jai.jai.tif"). javax.codec.jai.codec. java. com.sun.out.println("This TIF has " + count + " image(s)").sun.getCanonicalPath()).io.ParameterBlock. // Intel System. i < count. System.ImageCodec.jai.awt.sun. http://java.net/#Downloads To write a TIF file.setCompression(TIFFEncodeParam. param. java.println("Saving " + f. } public void doitJAI() throws IOException { FileSeekableStream ss = new FileSeekableStream("d:/multi. param. TIFF was originally created as an attempt to get desktop scanner vendors of the mid−1980's to agree on a common scanned image file format.*.rgagnon.setLittleEndian(false). File f = new File("d:/single_" + i + ". see this HowTo 3.jai.com/javase/technologies/desktop/media/jai/ https://jai. com.RenderedOp.com/products/java−media/jai/index. com. ss. javax.sun.

/javadetails/java−0601. return bi. bg. null).imageio.toString()).getWidth(null).ParameterBlock pb = new ParameterBlock(). } 3.rgagnon. javax.getGraphics(). java.read(file).67 Convert an Image to a BufferedImage . You can use it from a command line or from a GUI. bg.getHeight(null).*.*.addSource(page).add(f.awt.com/ To do a TIF conversion.drawImage(im.image. use this command line : C:\IrfanView\i_view32" d:\multi.pb). } } } This solution is working but JAI is a slow performer. 0. pb.67 Convert an Image to a BufferedImage Current version of this HowTo : http://www.dispose(). public class ImageUtils { public static BufferedImage imageToBufferedImage(Image im) { BufferedImage bi = new BufferedImage (im.irfanview.add("tiff"). RenderedOp r = JAI. Written and compiled by Réal Gagnon ©1998−2006 [ home ] 3.io. consider making a small donation to show your support for this Web site and its content.*. You may want to consider to use an external utility to do this kind on conversion. a (free) multi−purpose graphic utility. 0. pb.tif) /killmesoftly irfanview is an amazing software when it comes to transform a graphic format to another one.awt.dispose(). If you find this article useful. java. Graphics bg = bi.add(param). A nice one is irfanview (win). pb.com/javadetails/.BufferedImage..*.create("filestore".tif /extract=(d:\. } public static BufferedImage readImageFromFile(File file) throws IOException { return ImageIO.im.TYPE_INT_RGB). http://www.html import import import import java. pb. r.

} else { //single click action could be added here System.when.BufferedImage bufferedImage) throws IOException { ImageIO. import java.when−timeMouseDown) < dClkRes)) { System. it's not needed.println("simple click " + currentTime).awt."jpg". if ((lastX==x) &(lastY==y) & ((event.lastY=0.when.applet./javadetails/java−0235.out. // last mouse down time int lastX=0. public class d extends Applet { int dClkRes = 300.rgagnon.html [JDK1. } } [JDK11] 3."png". } public static void writeImageToJPG (File file.public static void writeImageToPNG (File file. lastY=y. lastX=x.02] import java. so there isn't a back−conversion.com/javadetails/.write(bufferedImage. return false. timeMouseDown = event. // double−click speed in ms long timeMouseDown=0. } return true.*.println("double click " + currentTime).*.file). 3.68 Detect a double click vs simple click . int x. } } You need to do something to transform an Image to BufferedImage. // last x and y public boolean mouseDown(Event event. But since BufferedImage extends Image.file).out..BufferedImage bufferedImage) throws IOException { ImageIO.write(bufferedImage.68 Detect a double click vs simple click Current version of this HowTo : http://www. int y){ /* ** check for double click */ long currentTime = event.

/javadetails/java−0236.applet.addMouseListener(this).10).awt. } 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. public class d extends Applet implements MouseListener { public void init() { this.getX() + ":" + e.addMouseListener(this).drawString("Click here".out.out.getClickCount() == 2) System. if (e. } 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. } public void paint(Graphics g) { g. 3.println( " and it's a double click!").com/javadetails/.awt.*.println( " and it's a simple click!").println("That's the LEFT button").applet. public class d extends Applet implements MouseListener { public void init() { this. } } 3.out.69 Detect the mouse button used when clicking Current version of this HowTo : http://www. else System.import java.awt. import java.*. } public void paint(Graphics g) { g.rgagnon.awt. import java.getY() + ")" ).out. break. 10.event.drawString("Click here".*.69 Detect the mouse button used when clicking .println ( "Click at (" + e.*.*. import java. import java.html [JDK11] import java. 10..BUTTON1_MASK: { System.10).getModifiers()) { case InputEvent.event.*.

break.com/javadetails/. } case InputEvent.").html import java./javadetails/java−0276."North"). m1.println("That's the MIDDLE button"). new MenuShortcut(KeyEvent.70 Exit an application from a menu Current version of this HowTo : http://www.setActionCommand("Exit")."South"). 3.BUTTON2_MASK: { System. addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { // unique exit point System. MenuBar mb = new MenuBar().add(new MenuItem("Exit".exit(0). break.70 Exit an application from a menu . System. } } } } 3.println("Bye. setMenuBar(mb).out.awt.event.getActionCommand().awt.*.add(m).addActionListener(this). add(new Label ("You can quit with the MenuShortcut 'ctrl−x'"). setSize(300. add(new Label ("You can quit by clicking on the menu item 'Exit'").WINDOW_CLOSING)).. MenuItem m1 = m. show().equals("Exit")) processEvent(new WindowEvent(this. add(new Label ("You can quit by clicking on the 'X'"). import java."Center").out. } public void actionPerformed(ActionEvent evt) { String what = evt. WindowEvent. } } ). mb. ExitFromMenu() { super("").rgagnon.} case InputEvent.out.*. public class ExitFromMenu extends Frame implements ActionListener { Menu m = new Menu("Exit From Here").BUTTON3_MASK: { System.VK_X))). 300). m.println("That's the RIGHT button"). if (what.

event. b1. public void init() { setLayout(new FlowLayout())..getSource() == b1) { t1. } if (e. JTextField t1.addActionListener(this). ActionEvent.*.*. add(t1).getSystemEventQueue().getSource() == b2) { // from the b2 button. can be used too.com/javadetails/. add(b1).} static public void main(String[] args) { new ExitFromMenu().awt. Toolkit. } } } With Swing import java. public class TestEvent extends Applet implements ActionListener { Button b2. import java.addActionListener(this).71 Trigger a click on a Button .postEvent(ae).applet.awt.getDefaultToolkit(). b2. b2.dispatchEvent(ae). public class TestEventSwing extends JApplet implements ActionListener { JButton b1. we creating an event to trigger a click // on the b1 button ActionEvent ae = new ActionEvent((Object)b1. b1 = new Button("Output"). t1 = new TextField(30).event. add(b2).html Regular AWT import java. TextField t1.awt./javadetails/java−0468. import javax. } public void actionPerformed(ActionEvent e) { if (e.swing. ""). import java. b2 = new Button("Fire event 1st button").setText("1st button clicked"). // b1.71 Trigger a click on a Button Current version of this HowTo : http://www.*.rgagnon.*. import java. b1. 3.*.awt.ACTION_PERFORMED. } } 3.*.

b2. add(b1).rgagnon. // As an added bonus. } } } If you find this article useful. b1 = new JButton("Output"). consider making a small donation to show your support for this Web site and its content.com 3. b2 = new JButton("Fire event 1st button"). add(t1). } if (e. t1 = new JTextField(30).getSource() == b1) { t1. } public void actionPerformed(ActionEvent e) { if (e. add(b2).getSource() == b2) { // from the b2 button. b1.public void init() { setLayout(new FlowLayout()). a visual effect on b1 is visible! b1. we trigger a click on the b1 button.addActionListener(this). Written and compiled by Réal Gagnon ©1998−2005 [ home ] Written and compiled Réal Gagnon ©2007 real@rgagnon.doClick().com http://www.setText("first button clicked").addActionListener(this).71 Trigger a click on a Button .

4 Start the JVM with the "−D" switch to pass properties to the application and read them with the System.*.exec( "command.4 Environment 4.out.rgagnon. Properties envVars = new Properties().toLowerCase(). } else { 4 Environment . The following snippet puts all environment variables in a Properties class and display the value the TEMP variable.getProperty("os. import java. A more low−tech way./javadetails/java−0150. } else if ( (OS.indexOf("windows 9") > −1) { p = r.indexOf("nt") > −1) || (OS. JDK up to 1. then there is no 100% Java way to retrieve them.*. import java. SET myvar=Hello world SET myothervar=nothing java −Dmyvar="%myvar%" −Dmyothervar="%myothervar%" myClass then in myClass String myvar = System. is to use a JNI call to fetch the variables. public class ReadEnv { public static Properties getEnvVars() throws Throwable { Process p = null.getProperty("myvar").com /c set" ).5 or better provides a simpler way to achieve this..html NOTE: JDK1.getProperty("myothervar").util. If you don't know in advance. if (OS.indexOf("windows xp") > −1) ) { // thanks to JuanFran for the xp fix! p = r. Runtime r = Runtime. the name of the variable to be passed to the JVM. // System. One approach (not the easiest one). see this HowTo.getProperty() method.1 java−env 4.exe /c set" ). String OS = System. is to launch the appropriate call to the operating system and capture the output.2 Read environment variables from an application Current version of this HowTo : http://www.println(OS).com/javadetails/. String myothervar = System.name").indexOf("windows 2000") > −1 ) || (OS.exec( "cmd. see this HowTo.io.getRuntime().

pre−JDK 1. You could push it further and use "windows 2.readLine()) != null ) { int idx = line.indexOf("windows xp") > −1) ) { // ok // but specific to 2003 else if ( (OS. String value = line. String key = line.out. Here 2 ways to bypass this behaviour.setProperty( key.println("the current value of TEMP is : " + p. } return envVars. } BufferedReader br = new BufferedReader ( new InputStreamReader( p.indexOf("nt") > −1) || (OS." On Windows. } catch (Throwable e) { e.indexOf("windows xp") > −1) ) { I started with "windows 200" but thought "what the hell" and made it "windows 20" to lengthen its longivity.2 JVM has trouble reading the Output stream directly from the SET command.indexOf("nt") > −1) || (OS. envVars.substring( idx+1 ). The only thing to watch out for is to not overlap with "windows 9. the property value for "os. 4 Environment .getInputStream() ) ). Then. while( (line = br. idx ). value ). // System. // since no other OS would // return "windows" || (OS.out. we assume Unix (thanks to H.println( key + " = " + value ). we use a BAT file. after the SET command we print a known string. when we read this known string.name" is actually "windows 2003. we exit from loop. it never returns.printStackTrace().indexOf("windows 20") > −1 ) // better. Ware for the fix) p = r.rijnders for the w2k fix. String line.indexOf("windows 2000") > −1 ) || (OS. in Java.indexOf( '=' )." I suppose. on Windows 2003 server.indexOf("windows 2003") > −1 ) || (OS. System. } public static void main(String args[]) { try { Properties p = ReadEnv.// our last hope. } } } thanks to w. An update from Van Ly : I found that. instead of calling directly the SET command.substring( 0." So either that has to be added to the bunch of tests or just relax the comparison strings a bit: else if ( (OS.getEnvVars().getProperty("TEMP")). First.exec( "env" ).

io. Thanks to JP Daviau // UNIX public Properties getEnvironment() throws java.exec("env"). } else if ( (OS.txt")).get("MYENV_VAR"). int idx = line. // then read back the file Properties p = new Properties(). . To read only one variable : // NT version . hash.out.txt" ).readLine(). String value = line.indexOf( '=' ). String key = line..com /c set > envvar.IOException { Properties env = new Properties(). env. if (OS..getInputStream()).substring( idx+1 ).println(myvar). String myvar = br.println( key + " = " + value ). System.load(new FileInputStream("envvar.. String myEnvVar = env..exec( "command.. p. Java's System properties contains some useful informations about the environment.indexOf("windows xp") > −1) ) { // thanks to JuanFran for the xp fix! p = r..exec( "env. public class ShowSome { 4 Environment .exe /c set > envvar. } The other solution is to send the result of the SET command to file and then read the file from Java. while( (line = br. } Properties env = getEnvironment(). } . value ).exe /c echo %MYVAR%"). Process p = Runtime.bat" )..bat] @set @echo **end [java] . BufferedReader br = new BufferedReader ( new InputStreamReader( p. idx ).getInputStream() ) ).getRuntime().substring( 0. for example.indexOf("**end")>−1) break..put( key.exec( "cmd.txt" ).load(Runtime. } .indexOf("windows") > −1) { p = r.indexOf("nt") > −1) || (OS.indexOf("windows 2000") > −1 || (OS..getRuntime(). the TEMP and PATH environment variables (on Windows)..readLine()) != null ) { if (line.[env. if (OS. return env.exec("cmd. adaptation for other OS is left as an exercise.out.indexOf("windows 9") > −1) { p = r. System.

(java added all those except /lib and /usr/lib). System.d:\cfn\bin.out..C:\Program Files\Dell\OpenManage\ResolutionAssistant\Common\bin.C:\WINNT.getProperty("java.3/lib/i386/native_threads: /usr/lib/j2re1.println("PATH : " + System.out.library.path")).tmpdir")).path")+"}"). c:\depot\cdk\main\cdk\bin. C:\Program Files\Executive Software\DiskeeperServer\.c:\cygnus\cygwin−b20\H−i586−cygwin32\bin. System. System.C:\WINNT\system32.} LIBPATH: {D:\jdk1.getProperty("PATH")+"}").class.home")).D:\Program Files\IBM\GSK\lib. C:\WINNT\system32./bin:.. H:\pvcs65\VM\win32\bin. Ware about the PATH on different OS. } } Here some tips from H. System.io.getProperty("user.} LIBPATH: {/usr/lib/j2re1.3/lib/i386/client:/usr/lib/j2sdk1. d:\Program Files\Symantec\pcAnywhere. D:\orant\bin. 4 Environment .2\bin.D:\orant\bin. {" + 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/linux−bin:/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/.getProperty("java.out.D:\Program Files\IBM\GSK\lib.3\bin.\bin.println("CLASSPATH : " + System..c:\depot\cdk\main\cdk\bin.3\bin.println("CURRENT DIR: " + System.D:\jdk1. d:\Program Files\Symantec\pcAnywhere.3\bin. d:\OrbixWeb3.println("LIBPATH: {" + System. System. C:\WINNT.println("the current value of PATH is: p.2\bin.out.C:\WINNT\System32.getProperty("java. But these two lines aren't the same on window either: This system is windows nt the current value of PATH is: {d:\OrbixWeb3.out. c:\windows on Win9x System.path")).3/lib/i386:/usr/lib/j2re1. In unixes.c:\depot\ cdk\main\cdk\.c:\depot\cdk\main\cdk\.D:\jdk1.public static void main(String args[]){ System.H:\pvcs65\VM\win32\bin.2\bin.C:\WINNT.3/lib/i386:/usr/lib:/lib} on my linux workstation.getProperty("java.out..getProperty("user.library.d:\OrbixWeb3.println("TEMP : " + System. PATH is not quite the same as library path.\bin.d:\cfn\bin.dir")).out.. they are completely different−−−the libraries typically have their own directories. // ex.println("SYSTEM DIR : " + System.c:\cygnus \cygwin−b20\H−i586−cygwin32\bin.

See this Howto for common XP environment variables If you find this article useful.C:\Program Files\Executive Software\DiskeeperServer\.html JDK1.getenv() is back! import java./javadetails/java−0466.getenv("PATH")).5) . Written and compiled by Réal Gagnon ©1998−2005 [ home ] 4.rgagnon. for (Iterator it=env. the getenv() method was removed from the JDK.. 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. 4.com/javadetails/.com/javadetails/. // all of them Map env = System.Entry entry = (Map.println(entry.3 Retrieve environment variables (JDK1.out.out. 4.*. } } } See also this HowTo. jname.println("PATH = " + System. Rumors is that a mechanism to retrieve an environment will be back in JDK1. it.5) Current version of this HowTo : http://www.Entry)it.util. ) { Map. System./javadetails/java−0460.html For some odd reasons.rgagnon.4 Retrieve environment variable (JNI) Current version of this HowTo : http://www. public class Test { public static void main(String args[]) { // just one System.} Java is prepending itself! That confused me−−− and broke my exec from ant. (jboolean *)NULL) .hasNext(). jclass c. consider making a small donation to show your support for this Web site and its content.iterator().getenv(). But for now. jstring jname){ if ( jname == NULL ) { return NULL ..5 System. } const char *name = (*env)−>GetStringUTFChars(env.getValue()).5 (see this HowTo).next().getKey() + " = " + entry.3 Retrieve environment variables (JDK1.entrySet().

$(JAVAHOME)\lib\classes.zip.class Java−Bean: False Name: myCanvas.3 JAVAC= $(JAVAHOME)\bin\javac PATH=$(JAVAHOME)\bin.html # jMAKEFILE a MAKEFILE for JAVA development # (Microsoft nMAKE) # nmake /f j.5 Use a MAKE file Current version of this HowTo : http://www.SUFFIXES: . consider making a small donation to show your support for this Web site and its content.rgagnon.class Java−Bean: True << $(CLASSFILES) 4.1.$(JSDKHOME)\lib\classes.class .class: $(JAVAC) −classpath $(CLASSPATH) $(JAVACFLAGS) $< CLASSFILES = GetImage.5 Use a MAKE file . DOC=. jname.class SOURCEFILES = GetImage.java. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 4. See also this HowTo. JAVA=$(JAVAHOME)\bin\java JAVACFLAGS=−deprecation ..makefile.$(PATH) CLASSPATH=.jar $(JARFILE): $(CLASSFILES) $(SOURCEFILES) jar cfm0 $(JARFILE) <<manifest./javadetails/java−0158.. } NOTE : This is fine if the environment variable contains only regular 7−bit ASCII characters. value) : NULL .java \ myCanvas.tmp $(DATAFILES) Name: GetImage.com/javadetails/. If you find this article useful.mak doc # to generate JAVADOC .zip DEST=.java JAVAHOME=c:\windev\jdk1.SUFFIXES: .class .const char *value = getenv(name) . name) . return value ? (*env)−>NewStringUTF(env.class \ myCanvas.java . (*env)−>ReleaseStringUTFChars(env.java # begin −−−− JAR support −−−−−−−−−− JARFILE= theJAR.

startsWith("sun.out.println("This browser is not a Netscape Browser. return false.# end −−−− JAR support −−−−−−−−−− all : $(JARFILE) $(CLASSFILES) doc doc : $(CLASSFILES) javadoc −version −author −d $(DOC) $(SOURCEFILES) install : copy $CLASSESFILE $(DEST) clean: del $(CLASSFILES) 4.GenericAppletContext").").MozillaAppletContext").").rgagnon.applet. } public static boolean isMicrosoft() { try { Class.ms.forName("netscape.com/javadetails/.applet.println("This browser is a Microsoft Browser.forName("com.toString().println("This browser is a Netscape Browser.out.println("This browser is not a Microsoft Browser.out.").").applet. 4.6 Detect the browser/JVM type Current version of this HowTo : http://www.. return false. } return true.6 Detect the browser/JVM type . String appletContext = getAppletContext().html One way is to instanciate a known browser−specific method and catch the Exception if not found import java. } return true.AppletViewer")) theBrowser = "APPLETVIEWER". public class BrowserDetector extends Applet { public void init() { if ( isNetscape() ) System.*. if (appletContext.out./javadetails/java−0160. } } Or by examining the string representation of the getAppletContext() method String theBrowser = "APPLICATION".applet. if ( isMicrosoft() ) System. } catch (ClassNotFoundException e) { System. } catch (ClassNotFoundException e) { System. } public static boolean isNetscape() { try { Class.

by looking at the string representation of the getDefaultToolkit() method. else if (appletContext.class" HEIGHT=100 WIDTH=400 ARCHIVE=}.startsWith( "sun.startsWith ( "sun. During layout time.startsWith("sunw.plugin. else if (appletContext. <HTML></HTML><HEAD> <SCRIPT> function isBrowser(b. else if (appletContext.WToolkit")) theJVM = "JAVA".tags.plugin.awt.navig.ms. } For example. For an application.startsWith( "sun.WToolkit")) theJVM = "JVIEW".jar".jar".")) theBrowser = "MICROSOFT".viewer.v) { browserOk = false. we decide which archive to use.startsWith( "com. } archiveToBeUsed = "java102. } else { if isBrowser("Netscape".class exists in three versions. String toolkit = Toolkit.jar". else if (appletContext.windows.hotjava. our MyApplet.6 Detect the browser/JVM type .applet.1 applet and finally a version for JDK102−only browser.ms.toString().appName. the other is a JDK1.IExplorerAppletContext") theBrowser = "MICROSOFTPLUGINJRE1.startsWith("com.TagAppletPanel")) theBrowser = "HOTJAVA".ActiveXApplet")) theBrowser = "MICROSOFTPLUGIN.equals("APPLICATION") { if (toolkit. browserOk = (navigator. 4) { archiveToBeUsed = "n4.plugin. else if (appletContext. versionOk = (v <= parseInt(navigator.indexOf(b) != −1).getDefaultToolkit().else if (appletContext.win32. if (theBrowser. we detect the JVM type String theJVM = "". One is using Microsoft−specific classes. the javascript entity is remplaced by the right archive name. > </APPLET> </BODY></HTML> 4.AppletPlugin")) theBrowser = "NETSCAPEPLUGIN". else if (toolkit.applet.ocx.startsWith("netscape.startsWith( "sun. if (isBrowser("Microsoft".")) theBrowser = "NETSCAPE".4. By using a javascript entities. return browserOk &versionOk. The idea is to put all the required classes in an ARCHIVE file. } } </SCRIPT></HEAD><BODY> <APPLET CODE ="MyApplet.appVersion)).awt.context. versionOk = false. 4)) { archiveToBeUsed = "ie4.

For Java classes./javadetails/java−0163.com/javadetails/.rgagnon.rgagnon. 4.rgagnon.8 Use a precompiler "à la C" with Java Current version of this HowTo : http://www.. Execute your applet. In application java −verbose:class MyApp NOTE: This can be useful if you want to trim a JAR to include only classes actually used./javadetails/java−0165.. Open the Java console 2.com/javadetails/.write() method to generate the right APPLET tag instead of a the Javascript entity to be compatible with Netscape and IE. 4.html In Netscape 1.NOTE: You may need to use the document.7 Fix the "Wrong magic number" error message Current version of this HowTo : http://www. 4.9 Determine what are the classes actually used in a Java Applet or application Current version of this HowTo : http://www. 4.com/javadetails/. Check the console and take note of the loaded classes. This is used by the browser JVM as a quick check of whether the called file is really a Java class.html The "magic number" is represented by the first few bytes of a given file./javadetails/java−0164.7 Fix the "Wrong magic number" error message . It is used to identified the file type. If the message is displayed and you are sure that you have uploaded a "real" class to web server then it's probably because the FTP download has been done in TEXT mode instead of BINARY so the resulting file on the server is corrupted.html Check this list of what is available.. 4. the magic number is 0xCAFEBABE (you can verify this by viewing a class file with hexadecimal editor or the DOS Debug utility). Press "9" to set the Debug level 3.

jar.properties. doclet. The new file must be in the package com. The default is 1Mb.ClassUse_Subinterface=Subinterfaces of {0} in {1} doclet. in our case for french.SerialData=Serial Data\: doclet.Packages=Paquetages doclet.html By default. Copy it under the name standard_fr.Frame_Version=Frame version doclet. the JVM will use up to 16Mb of RAM.com/javadetails/..Window_Split_Index={0}\: {1}−Index doclet.resources. the standard. no space between ms/mx and the value : java −mx20m myApp 4. The tools.2.4. When starting the JVM. With JDK1.Warn_inline_taglet=Inline tag {0} should only be used with a {1}.properties files (keep the directory structure)./javadetails/java−0131.rgagnon. we need a file called standard_fr.properties used by Javadoc to generated the labels.10 Set the memory available to the JVM .doclets.Generated_Docs_Untitled=Generated Documentation (Untitled) [standard_fr.SerialData=Donn\u00E9e s\u00E9rialis\u00E9e\: 4.10 Set the memory available to the JVM Current version of this HowTo : http://www. appending "m" to n will specified the number in megabytes.rgagnon. you may need to increase this value to give more room to the garbage collector.properties (extract)] doclet..properties. for example to set the maximum at 20Mb : java −mx 20m myApp −ms n Sets the startup size of the memory allocation pool. you need to create the appropriate resource bundle. If your program allocates a lot of memory. Extract from tools.jar in the lib directory contains the resource bundle standard. two parameters can be adjusted to suit your memory needs : −mx n Sets the maximum size of the memory allocation pool where n is in bytes.Packages=Packages doclet. [standard.standard. that syntax have changed.properties (extract)] doclet. Translate it (or you can download my "incomplete" version here).sun.tools.11 Generate the Javadoc "en français" Current version of this HowTo : http://www./javadetails/java−0437. appending "m" to n will specified the number in megabytes. To add a new language.com/javadetails/.Window_Split_Index={0}\: {1}−Index doclet.html The javadoc utility uses the regular Java mechanism to internationalize its output.Since=Since\: doclet. where n is in bytes.

</i>]]></bottom> </javadoc> If you find this article useful.5 new features Current version of this HowTo : http://www.. To generate in french.5.12 Use JDK1. use the −locale switch on the command line javadoc −locale fr .Since=Depuis\: doclet.properties into the tools.. make sure to use quotes!) : 4.Frame_Version=Version avec cadres doclet.12 Use JDK1. put your standard_fr. doclet.com/javadetails/.sun. 2003 Real's Howto.resources)..0−beta−b32c) JAVA HOTSPOT(TM) CLIENT VM (BUILD 1..jar making sure that the file is located in the right package (along standard. <javadoc locale="fr" sourcefiles="c:/client/Client.rgagnon.doclets. Using Ant. Standard Edition (build 1. Do it again but with the complete path (if the path contains spaces.5 new features .properties in com. it's because the JVM can't be found through the PATH.html • Download the JDK1.doclet.Generated_Docs_Untitled=Documentation g\u00E9n\u00E9r\u00E9e Once everything translated.Warn_inline_taglet=Inline tag {0} should only be used with a {1}.5.tools. NOTE : Make sure the −locale switch is the first one.standard./javadetails/java−0462. MIXED MODE) On Windows.0−BETA−B32C. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 4.0−beta" Java(TM) 2 Runtime Environment. consider making a small donation to show your support for this Web site and its content. if you have a "file not found" message.ClassUse_Subinterface=Sous−interfaces de {0} dans {1} doclet.5 and install it.5. • From a shell. type java −version The response should be something like java version "1.java" destdir="javadoc/Client" author="true" version="true" use="true" private="true" windowtitle="Client"> <doctitle><![CDATA[<h1>Client</h1>]]></doctitle> <bottom><![CDATA[<i>Copyright &#169.

0\bin\javac" −source 1.io.0\bin\java" Test15 Local time: 15:26:04 If you find this article useful.readInt().5 Test15. • Run it >"C:\Program Files\Java\j2sdk1. if(magic != 0xcafebabe) { 4.util. java.13 Check the class version . public class ClassVersionChecker { public static void main(String[] args) throws IOException { for (int i = 0.2 0 1.5 0 1.rgagnon.0 3 1.com/javadetails/. if you don't specify it you won't be able to access the new features (like System.5. args) { System. i++) checkClassVersion(args[i])...Calendar.*. Possible major/minor value : major 45 45 46 47 48 49 50 minor Java platform version 3 1.java Note the switch "−source 1.0\bin\java" −version • Let's do our first jdk1. consider making a small donation to show your support for this Web site and its content.html The first 4 bytes are a magic number.5.13 Check the class version Current version of this HowTo : http://www.5 program : public class Test15 { public static void main(String . 0xCAFEBABe. } private static void checkClassVersion(String filename) throws IOException { DataInputStream in = new DataInputStream (new FileInputStream(filename))..3 0 1.6 import java.1 0 1. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 4.getInstance()).printf()).5". int magic = in."c:\program files\java\j2sdk1.length. } } • 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./javadetails/java−0544.out. i < args.out.4 0 1. to identify a valid class file then the next 2 bytes identify the class format version (major and minor).printf("Local time: %tT".

lang.getClassPath()).out.14 Get the system properties or the JVM uptime ..readUnsignedShort().util. import java./javadetails/java−0549. it has the value 0xCAFEBABE..management.rgagnon.close(). x. we denote the version of its class file format as M.5] import java.1.0 v Mj.doit(). minor_version.class ClassVersionChecker.5 < 2. } int minor = in.14 Get the system properties or the JVM uptime Current version of this HowTo : http://www.out. A Java virtual machine implementation can support a class file format of version v if and only if v lies in some contiguous range Mi. } public void doit() { try{ RuntimeMXBean mx = ManagementFactory.com/javadetails/. class file format versions may be ordered lexicographically.Together. 0 from The Java Virtual Machine Specification magic The magic item supplies the magic number identifying the class file format. major_version The values of the minor_version and major_version items are the minor and major version numbers of this class file. If a class file has major version number M and minor version number m.System.out. 4. for example.html The RuntimeMXBean defines several convenient methods for accessing system properties about the Java virtual machine.0 < 2.lang. 1.println("BOOTCLASSPATH:\n" + mx.println(filename + " is not a valid class!"). Only Sun can specify what range of versions a Java virtual machine implementation conforming to a certain release level of the Java platform may support. 4. a major and a minor version number determine the version of the class file format.RuntimeMXBean. } } > java ClassVersionChecker ClassVersionChecker. import java. class JMXTest { public static void main(String args[]) { JMXTest x = new JMXTest(). " + minor). System.readUnsignedShort(). System.getRuntimeMXBean().println(filename + ": " + major + " . Thus.getBootClassPath()).class: 49 .out.Date.m. int major = in.m. in. System. [J2SE 1.ManagementFactory.println("CLASSPATH:\n" + mx.management.

html public static boolean is64BitVM() { String bits = System. } // probably 32bit return false.html If you type.arch.println("VM start time : " + new Date(mx.5./javadetails/java−0565. } } } 4.0−b64) Java HotSpot(TM) Client VM (build 1.// the input arguments passed to the Java virtual machine // which does not include the arguments to the main method.rgagnon.data.println("SYSTEM PROPERTIES:\n" + mx. // a map of names and values of all system properties.16 Set the default JVM type Current version of this HowTo : http://www.15 Detect if running in a 64bit JVM Current version of this HowTo : http://www..printStackTrace().15 Detect if running in a 64bit JVM . mixed mode.vm.println("COMMAND LINE ARGS:\n" + mx.equals("64") { return true.5. "?").out.data.0" Java(TM) 2 Runtime Environment. System. } } 4.equals("?") { // probably sun.getStartTime())).name property return System.getProperty("sun.toLowerCase(). } catch (Exception e) { e.getUptime() + " ms").getInputArguments()).com/javadetails/. Standard Edition (build 1.model".getProperty("java.out. System. in a Shell > java −version you get java version "1.indexOf("64") >= 0. if (bits.name") . } if (bits. sharing) 4. System.getSystemProperties()). System..println("VM up time : " + mx.out.out.5.com/javadetails/.rgagnon.0−b64.arch./javadetails/java−0566.model isn't available // maybe not a Sun JVM? // try with the vm.

html method 1a : redirect to a file // Win95 (?) javac −J−Djavac./javadetails/java−0147.pipe. you'll need to download the SDK to get both systems.17 Capture the output of JAVAC Current version of this HowTo : http://www.5. the 64−bit JRE is an overlay on top of the 32−bit distribution.rgagnon. On Windows.0−sun. On Debian GNU/Linux with Sun Java 1. On Solaris. In general the client system is better suited for interactive applications such as GUIs.sun. However. The client system is optimal for applications which need fast startup times or small footprints. Some of the other differences include the compilation policy. the file is in /etc/java−1. 4.The default JVM with a JIT (Just−In−Time compiler) for a "client" mode is used.java 2output. They are essentially two different compilers (JITs)interfacing to the same runtime system. and inlining policy.0\lib\i386. Where do I get the server and client systems? Client and server systems are both downloaded with the 32−bit Solaris and Linux downloads. The default setting is defined the file jvm. From the Hot Spot FAQ at http://java. The other available mode is "server". you get only the client.txt // WinNT (or better) javac MyClass.txt method 1a : redirect to stdout with a pause after each screen full 4.heap defaults. on Linux and Windows.output=true myClass. A content like −client KNOWN −server KNOWN defines the client as the default.5. if you download the JRE. it's in C:\Program Files\Java\jre1.com/docs/hotspot/HotSpotFAQ. only the server system is included.5. it's a completely separate distribution. For 64−bit.html#compiler_types.cfg.com/javadetails/.java >output.17 Capture the output of JAVAC . For 32−bit Windows. −server KNOWN −client KNOWN sets the server as the default. the server system is optimal for applications where the overall performance is most important. What's the difference between the −client and −server systems? These two systems are different binaries..0.

..println( " : " + buf ). Process p = Runtime.getRuntime(). String buf. BufferedReader se = new BufferedReader ( new InputStreamReader( p. while( (buf = se.DataInputStream(System.java 21 | MORE method 2 : use JAVA to capture the output // // // // [JDK 1.18 Freeze the JVIEW window in MS VJ++ .io.html 4.txt import java. System.getErrorStream() ) ).println( "END (rc:" + p. Or simply execute JVIEW directly in a DOS window with jview <classname> Check this How−to for a better way.java".out.. String aLine = in.*. compile.rgagnon.com/javadetails/.in).18 Freeze the JVIEW window in MS VJ++ Current version of this HowTo : http://www. public class JC { public static void main( String args[] ) throws IOException.java (use redirection to keep the output) java JC mySource. } } or you can always use a small text editor like Textpad where you can write with Java code (with syntax coloring).// WinNT (or better) javac MyClass. System./javadetails/java−0148.io.readLine(). InterruptedException { String fn = "JC. and the JVIEW window won't close until you hit ENTER..19 Know details about the JAVA at run−time Current version of this HowTo : http://www. if( args.io./javadetails/java−0149.java >output. 4.waitFor() + ")" ). 4.out.println( "BEGIN (" + fn + ")" ).out. capture compiler output and launch your Applet or Application directly from the editor. add the following line at the end : java.1] to compile: java JC mySource.html In your source.length > 0 ) fn = args[0].readLine()) != null ) System.exec( "javac −verbose " + fn ).rgagnon.DataInputStream in = new java.com/javadetails/.

Applets can read certain system properties by invoking System.getProperty(String key)
java.version java.vendor java.vendor.url os.name os.arch file.separator path.separator line.separator java.class.version Java version number Java vendor−specific string Java vendor URL Operating system name Operating system architecture File separator (eg, "/") Path separator (eg, ":") Line separator Java class version number

But applets are prevented from reading these system properties (for security reason):
java.home java.class.path user.name user.home user.dir Java installation directory Java classpath User account name User home directory User's current working directory

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");

Here a dump that can be useful in a log file:
public String dump() { StringBuffer sb = new StringBuffer(); Runtime rt = Runtime.getRuntime(); long freeMemory = rt.freeMemory(); long totalMemory = rt.totalMemory(); sb.append("free memory=" + freeMemory); sb.append("\n"); sb.append("total memory=" + totalMemory); sb.append("\n"); java.util.Properties p = null; try { p = System.getProperties(); } catch(Exception e) { e.printStackTrace(); return ""; } java.util.Enumeration en = p.propertyNames(); while (en.hasMoreElements()){ String s = (String) en.nextElement(); String strValue= p.getProperty(s); sb.append(s + "=<" + strValue + ">"); sb.append("\n"); } // result to a string return sb.toString(); }

4.18 Freeze the JVIEW window in MS VJ++

4.20 Detect the Microsoft JVM version installed
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0327.html
class MSJVMversion { public static void main(String[] args) { String build; build=com.ms.util.SystemVersionManager.getVMVersion().getProperty ("BuildIncrement"); System.out.println("Microsoft JVM installed is " + build); } }
NOTE:The above snippet will return the Microsoft VM version. This not the same thing as as the JDK version. In this case , Microsoft's Java environment only goes up to 1.1.4 and there is no plan to upgrade it.

4.21 Run JAVA as a Windows service
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0151.html A solution adapted to Java, is the Java Service Wrapper ( http://wrapper.tanukisoftware.org/doc/english/introduction.html ) (opensource). The setup is very simple with one configuration file and your Java service can be notified when the service is stopped. If you log in and log out from a machine and a java service is running then the service may be stopped. The fix is to use Java 1.3.1 or higher and start the process with the JVM switch −Xrs (Reduce Signals Xtended−switch) to stop the Windows signal from killing the JVM. For BEA JRockit, it's the −Xnohup Also, it's possible to the utility SRVANY.EXE, included with the NT resource Kit. http://www.techeez.com/windows_tips/service_under_nt.htm SVRANY is used to run any EXE as a windows service. In our situation, SVRANY will run the specified JAVA.EXE with our class a parameter. But this solution presents many problems. For exemple, if you kill the SVRANY.EXE process (stop the service) then the JAVA.EXE is not killed, you need to do it manually.

4.22 Execute a class from Windows Explorer
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0328.html This HowTo will you show how to start a class (with a main() method) without opening a DOS Shell or using a JAR file directly from Windows Explorer.

4.20 Detect the Microsoft JVM version installed

Type the following VBScript using a text editor and save it as WRunJava.vbs. You need to save the script in the SendTo subdirectory located in the Windows directory On a Win98 system, it's C:\Windows\SendTo. On XP, go to Documents and Settings folder then select the folder of a specific user, eg. c:\documents and settings\'user name'\SendTo. NOTE The SendTo folder is hidden by default. If it is not visible, on the Tools menu, click Folder Options. On the View tab, click Show hidden files and folders. SO you save the scripts shown below, into the SendTo folder. Then in Window Explorer, locate a class file that can be executed (with a main() method). Right click on it, select the Send To menu and you should see an entry called WRunJava.vbs. Simply select it and the class should be launched via javaw.exe .
' [WRunJava.vbs] start a java class without 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) cmdline = "javaw.exe −cp " &javapath &" " &javaclass WSHShell.Run cmdline, 1, false ElseIf fso.GetExtensionName(javaclass) = "jar" Then javacompletepath = fso.GetAbsolutePathName(javaclass) cmdline = javaclass WSHShell.Run cmdline, 1, false Else WScript.Echo "Not a java class! (" &javaclass &")" End if End If Set WSHShell = Nothing Set FSO = Nothing WScript.Quit(0)

You need a second script to launch a java class with a console (useful to see debugging traces or text−only Java program). Called it CRunJava.vbs . Then you will have two choices from the SendTo menu, one for console−based program and one for GUI−based (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

4.20 Detect the Microsoft JVM version installed

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 cmdline = "cmd /k java.exe −cp " &javapath &" " &javaclass ' close the console ' cmdline = "cmd /c java.exe −cp " &javapath &" " &javaclass WSHShell.Run cmdline, 1, false ElseIf fso.GetExtensionName(javaclass) = "jar" Then javacompletepath = fso.GetAbsolutePathName(javaclass) cmdline = "java.exe −jar " &javaclass WSHShell.Run cmdline, 1, false Else WScript.Echo "Not a java class! (" &javaclass &")" End if End If Set WSHShell = Nothing Set FSO = Nothing 'WScript.Quit(0)

Note : A JAR can be made self executable (with double click), see this HowTo

4.23 Create an icon to launch java apps for Windows?
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0157.html Let's say you have a class named myApp.class and it is located in the directory myJavaApp on drive C:. Then create a Shortcut to the myApp.class. Next edit the properties of the Shortcut and change the line
c:\myjavaapp\MyApp.class 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.

4.24 Fix the "out of environment" error when setting a new CLASSPATH
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0159.html

4.23 Create an icon to launch java apps for Windows?

DOS has a limit on available environment space. You can adjust this in CONFIG.SYS. If your SHELL statement is set to COMMAND.COM, simply add/modify the SHELL parameter for adjusting the environment size:
SHELL=C:\windows\command.com C:\windows /p /E:4096

will set off 4 Kb for environment variables. Command line in DOS has a limit of 127 characters. If you need more room to lanch the JVM then you have the following workaround. • Use environment variable like
SET MYCLASSPATH = /files/classes/lib/examples.jar SET MYARGS = −Djava.security.policy=/files/policy java −cp %MYCLASSPATH% %MYARGS% myClass

• Use a BAT file.

4.25 Query Windows registry
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0480.html We launch the REG utility and capture the output. The performance is poor so it's a good idea to cache frequently used values.
Note : The Microsoft ® Windows NT ® Server 4.0 Resource Kit contains REG.EXE. In Windows 2000 and later REG.EXE is a native command. The REG utility can be used to write values in the registry (reg add /? for more infos).

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"; public static String getCurrentUserPersonalFolderPath() { try { Process process = Runtime.getRuntime().exec(PERSONAL_FOLDER_CMD); StreamReader reader = new StreamReader(process.getInputStream()); reader.start(); process.waitFor(); reader.join();

4.25 Query Windows registry

String result = reader.getResult(); int p = result.indexOf(REGSTR_TOKEN); if (p == −1) return null; return result.substring(p + REGSTR_TOKEN.length()).trim(); } catch (Exception e) { return null; } } public static String getCPUSpeed() { try { Process process = Runtime.getRuntime().exec(CPU_SPEED_CMD); StreamReader reader = new StreamReader(process.getInputStream()); reader.start(); process.waitFor(); reader.join(); String result = reader.getResult(); int p = result.indexOf(REGDWORD_TOKEN); if (p == −1) return null; // CPU speed in Mhz (minus 1) in HEX notation, convert it to DEC String temp = result.substring(p + REGDWORD_TOKEN.length()).trim(); return Integer.toString ((Integer.parseInt(temp.substring("0x".length()), 16) + 1)); } catch (Exception e) { return null; } } public static String getCPUName() { try { Process process = Runtime.getRuntime().exec(CPU_NAME_CMD); StreamReader reader = new StreamReader(process.getInputStream()); reader.start(); process.waitFor(); reader.join(); String result = reader.getResult(); int p = result.indexOf(REGSTR_TOKEN); if (p == −1) return null; return result.substring(p + REGSTR_TOKEN.length()).trim(); } catch (Exception e) { return null; } } static class StreamReader extends Thread { private InputStream is; private StringWriter sw;

4.25 Query Windows registry

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"); } }

See also this HowTo and this one.
If you find this article useful, consider making a small donation to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998−2007 [ home ]

4.26 Quickly retrieve available Java JVM on a workstation (Windows)
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0525.html Use regedit utility to query the Windows registry, the result is written into a file.
start /w regedit /e jre.txt "HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment"

The content of jre.txt on my machine :
Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment] "CurrentVersion"="1.5" [HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.4] "JavaHome"="C:\\Program Files\\Java\\j2re1.4.1_02" "RuntimeLib"="C:\\Program Files\\Java\\j2re1.4.1_02\\bin\\client\\jvm.dll" "MicroVersion"="1"

4.26 Quickly retrieve available Java JVM on a workstation (Windows)

[HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.4.1_02] "JavaHome"="C:\\Program Files\\Java\\j2re1.4.1_02" "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"

A CMD file for Windows to display the default JRE used :
@echo off ::Find the current (most recent) Java version start /w regedit /e reg1.txt "HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment" type reg1.txt | find "CurrentVersion" > reg2.txt if errorlevel 1 goto ERROR for /f "tokens=2 delims==" %%x in (reg2.txt) do set JavaTemp=%%~x if errorlevel 1 goto ERROR echo Java Version = %JavaTemp% del reg1.txt del reg2.txt

::Get the home directory of the most recent Java start /w regedit /e reg1.txt "HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\%Ja type reg1.txt | find "JavaHome" > reg2.txt if errorlevel 1 goto ERROR for /f "tokens=2 delims==" %%x in (reg2.txt) do set JavaTemp=%%~x if errorlevel 1 goto ERROR echo Java home path (per registry) = %JavaTemp% del reg1.txt del reg2.txt pause

The above script returns the default JVM if the PATH variable does not override it!
If you find this article useful, consider making a small donation to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998−2006 [ home ]

4.27 Get the Windows "My Documents" path
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0572.html This value is stored in the registry and there is no easy way to get it with regular Java unless you execute an external utility, see this HowTo. As an alternative, we can use a method provided by the JFileChooser class. 4.27 Get the Windows "My Documents" path

import javax.swing.JFileChooser; javax.swing.filechooser.FileSystemView; public class GetMyDocuments { public static void main(String args[]) { JFileChooser fr = new JFileChooser(); FileSystemView fw = fr.getFileSystemView(); System.out.println(fw.getDefaultDirectory()); } }

4.28 Get a return code from a VBS
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0575.html You can't detect directly if Windows service is running or not in Java. However, it's easy to do from a VBS. You execute the script from Java, wait for its completion and capture the return code. Obviously, this is useful only on the Windows plateform.
import java.io.File; import java.io.FileWriter; public class VBSUtils { private VBSUtils() { } public static boolean isServiceRunning(String serviceName) { try { File file = File.createTempFile("realhowto",".vbs"); file.deleteOnExit(); FileWriter fw = new java.io.FileWriter(file); String vbs = "Set sh = CreateObject(\"Shell.Application\") \n" + "If sh.IsServiceRunning(\""+ serviceName +"\") Then \n" + " wscript.Quit(1) \n" + "End If \n" + "wscript.Quit(0) \n"; fw.write(vbs); fw.close(); Process p = Runtime.getRuntime().exec("wscript " + file.getPath()); p.waitFor(); return (p.exitValue() == 1); } catch(Exception e){ e.printStackTrace(); } return false; }

public static void main(String[] args){ // // DEMO // String result = ""; msgBox("Check if service 'Themes' is running (should be yes)");

4.28 Get a return code from a VBS

result = isServiceRunning("Themes") ? "" : " NOT "; msgBox("service 'Themes' is " + result + " running "); msgBox("Check if service 'foo' is running (should be no)"); result = isServiceRunning("foo") ? "" : " NOT "; msgBox("service 'foo' is " + result + " running "); } public static void msgBox(String msg) { javax.swing.JOptionPane.showConfirmDialog((java.awt.Component) null, msg, "VBSUtils", javax.swing.JOptionPane.DEFAULT_OPTION); } }

4.29 List currently running processes (Windows)
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0593.html

4.29.1 Using TASKLIST.EXE
The Microsoft TASKLIST.EXE is used to dump the list of the currently running processes. It is similar to tasklist window but for the console. From a Java program, we are launching TASKLIST.EXE and capture its output. Note : TASKLIST.EXE is not included the HOME edition of XP. But you can download it from Web, for example : http://www.computerhope.com/download/winxp.htm.
import java.io.*; import java.util.*; public class WindowsUtils { public static List listRunningProcesses() { List<String> processes = new ArrayList<String>(); try { String line; Process p = Runtime.getRuntime().exec("tasklist.exe /nh"); BufferedReader input = new BufferedReader (new InputStreamReader(p.getInputStream())); while ((line = input.readLine()) != null) { if (!line.trim().equals("")) { // keep only the process name processes.add(line.substring(0, line.indexOf(" "))); } } input.close(); } catch (Exception err) { err.printStackTrace(); } return processes; } public static void main(String[] args){ List<String> processes = listRunningProcesses(); String result = "";

4.29 List currently running processes (Windows)

// display the result Iterator<String> it = processes.iterator(); int i = 0; while (it.hasNext()) { result += it.next() +","; i++; if (i==10) { result += "\n"; i = 0; } } msgBox("Running processes : " + result); } public static void msgBox(String msg) { javax.swing.JOptionPane.showConfirmDialog((java.awt.Component) null, msg, "WindowsUtils", javax.swing.JOptionPane.DEFAULT_OPTION); } }

4.29.2 Using a VBS
Another technique to build the required VBScript on−the−fly, execute it and capture its output.
import import import import import java.io.BufferedReader; java.io.File; java.io.FileWriter; java.io.InputStreamReader; java.util.*;

public class VBSUtils { private VBSUtils() { } public static List<String> listRunningProcesses() { List<String> processList = new ArrayList<String>(); try { File file = File.createTempFile("realhowto",".vbs"); file.deleteOnExit(); FileWriter fw = new java.io.FileWriter(file); String vbs = + + + + + + + + "Set WshShell = WScript.CreateObject(\"WScript.Shell\")\n" "Set locator = CreateObject(\"WbemScripting.SWbemLocator\")\n" "Set service = locator.ConnectServer()\n" "Set processes = service.ExecQuery _\n" " (\"select name from Win32_Process\")\n" "For Each process in processes\n" "wscript.echo process.Name \n" "Next\n" "Set WSHShell = Nothing\n";

fw.write(vbs); fw.close(); Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath()); BufferedReader input = new BufferedReader (new InputStreamReader(p.getInputStream())); String line; while ((line = input.readLine()) != null) { processList.add(line); } input.close();

4.29.2 Using a VBS

} catch(Exception e){ e.printStackTrace(); } return processList; } public static void main(String[] args){ List<String> processes = listRunningProcesses(); String result = ""; Iterator<String> it = processes.iterator(); int i = 0; while (it.hasNext()) { result += it.next() +","; i++; if (i==10) { result += "\n"; i = 0; } } msgBox("Running processes : " + result); } public static void msgBox(String msg) { javax.swing.JOptionPane.showConfirmDialog((java.awt.Component) null, msg, "VBSUtils", javax.swing.JOptionPane.DEFAULT_OPTION); } }

4.30 Windows registry vs. Java JDK/JRE installation
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0604.html The JDK itself does not use the windows registry to run. It is the JRE that uses the system registry to run in some situations like an Applet or a program started with the WebStart technolgy. Finally, the JRE will only use the registry if it is run from the Windows system directory (ex . C:/winnt/system32/java.exe). This would happen if the user just types "java" on the commandline in some random directory, because the system directory is always in the user's path. In this situation, the java.exe will locate the current Java installation by looking at the registry key
[HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\CurrentVersion]

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

4.30 Windows registry vs. Java JDK/JRE installation

"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 WebStart−based programs, the registry is always used to determine the current JRE.

4.31 Use a JAR/ZIP/CAB file with an Applet
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0153.html [JAR format] JAR (Java ARchive) is a platform−independent file format that allows you to bundle a Java applet and its requisite components (.class files, images and sounds) into a single JAR file. JAR supports compression, which reduces the file size, further improving the download time. The applet author can digitally sign individual entries in a JAR file to authenticate their origin (using the JAVAKEY utility). However, to sign JAR to be used with a "real−world" browser (eg. Netscape), you must use Netscape's utilities ZIGbert or GUI JAR Archiver to sign it. These utilities can be freely downloaded from the Netscape Web site. For more infos about signing Applet for Netscape, check this JAVA How−to. The browser need to be JDK1.1 compatible to handle JAR file. If a JAR file is used with an Applet, the browser will look first into the JAR to load all classes. If the search fails in the JAR file, then the browser looks in the applet's base directory. To specify the use of a JAR file with an applet:
<APPLET CODE=a.class ARCHIVE="abc.jar" WIDTH=100 HEIGHT=100> </APPLET>

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 :
java −classpath c:\jdk1.1.3\lib\classes.zip;.;.\HelloWorld.jar HelloWorld

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:

4.31 Use a JAR/ZIP/CAB file with an Applet

jar cvfO myArchive.jar *.class

[ZIP format] JDK1.0.2 introduces the ZIP "un−compressed" 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

or check for InfoZIP at http://www.cdrom.com/pub/infozip/ To use a ZIP archive, simply use the HTML ARCHIVE tag
<APPLET CODE="a.class" ARCHIVE="abc.zip" WIDTH=618 HEIGHT=410> </APPLET>

[CAB format] CAB (for CABINET) is used only by Microsoft Internet Explorer. It offers compression (like the JAR but the ZIP format is un−compressed). 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, non−MS 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.

4.31 Use a JAR/ZIP/CAB file with an Applet

Written and compiled by Réal Gagnon ©1998−2000 mailto:real@rgagnon.com

[ home ]

4.32 Make ZIP/JAR file always accessible from applet
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0154.html [Netscape 4] Manual method Copy the ZIP/JAR file in the PLUGINS directory and remove the reference in the ARCHIVE parameter of the APPLET tag. For example, to be able use SWING classes from Netscape, copy SWING.JAR and ROSE.JAR in the PLUGINS directory and restart Netscape. Automatic method Automatic installation can be done with Netscape using the SmartUpdate mechanism. The JAR must be signed with the Netscape Signing Tool.Check the following links for more infos: http://developer.netscape.com/docs/manuals/communicator/jarman/ http://developer.netscape.com/docs/manuals/signedobj/overview.html

4.33 Make a JAR executable
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0166.html In the manifest file of a JAR, it is possible to specify the class to be used when the JVM is lauched with the JAR as parameter. The class must have a main(). Try with this simple class
import java.awt.*; import java.awt.event.*; public class MyClass { public static void main(String[] args) { Frame f = new Frame(); f.addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); f.add(new Label("Hello world")); f.setSize(200,200); f.setVisible(true); } }

Then create this manifest file (manifest.mft) with any text editor. 4.32 Make ZIP/JAR file always accessible from applet

Manifest−Version: 1.jar If you need to pass parameters. for example SET PATHEXT=..mft *.. The Class−path is used to specify the dependency of this jar (if any).34 Accessing jars from within a jar Current version of this HowTo : http://www. 4. The file association mechanism is made during the installation of the JRE.jar . It is important because when running a jar . typing "MyJar" on the DOS command line will invoke "javaw −jar MyJar. you can also make JARs run from the command−line by setting the PATHEXT environment variable. NOTE: On WinXp (or better)..html Supposed we have a jar called Main.rgagnon.jar file (if the JRE is correctly installed) or by typing java −jar myjar. you can modify the association easily (use /? to display the syntax of the assoc and ftype utilities).jar).jar=jarfile >ftype jarfile jarfile="C:\Program Files\Java\jre1.JAR Then if you have the jar file MyJar.EXE.jar .com/javadetails/. jar cvfm myjar.jar accessible via the PATH environment variable.0_10\bin\javaw.CMD.jar" . In the manifest file of the first jar (Main.34 Accessing jars from within a jar .class by double−clicking on the MyJar.jar manifest.jar and Third. Next..jar for the application.0 Main−Class: MyClass Class−path: . Main−Class specifies the entry point with the main(String args[]) method.exe" −jar "%1" %* If the association is broken or you need to change the JRE used then by using the assoc/ftype utilities. the CLASSPATH definition (as defined by the environnement variable) is overridden.jar) with the MyClass class. you adjust the Class−Path setting : 4. You can verify that everything is ok with the following command from a DOS Shell >assoc . your user account needs to be at the Admin level.BAT./javadetails/java−0319. On Windows (NT or better). use the −D switch before the −jar switch and use the getProperty() method to get the value.5. you include the manifest file in the JAR (MyJar. This application needs Second. You add the directories and jars separated by a space.class Then you are able to start the MyClass.

ulc).out.html import java.rgagnon.jar The value of the Class−Path attribute specifies the relative URLs of the extensions or libraries that this application or extension needs. The application or extension class loader uses the value of this attribute to construct its internal search path.LIST file in the META−INF directory which will enable the application class loader to download the right jar files when it is searching for classes or resources.urlB }.Manifest−Version: 1.xerces. You can use the −i option to speed up your application's class loading time: jar −i main..com/javadetails/. import java.35 Access a JAR outside the CLASSPATH .*.ChildNode".toURL(). } catch(Exception e) { e. URL[] urls = { urlA.35 Access a JAR outside the CLASSPATH Current version of this HowTo : http://www.jar Third.io.zip. import java. } } } 4. import java. true.*.apache./javadetails/java−0409.*.36 Extract a file from a Jar Current version of this HowTo : http://www.util.printStackTrace(). // Class c = Class.util. URLClassLoader ulc = new URLClassLoader(urls). public class ExtraLoader { public static void main(String[] args) { try { URL urlA = new File("C:/xtras/xercesImpl.html The following snippet extract a file (mydb.*.net. URL urlB = new File("C:/xtras/xmlParserAPIs. // System. 4.io.jar")..println(c.mdb) from a jar.rgagnon.dom.jar.jar This will build an an INDEX.jar"). URLs are separated by one or more spaces.*./javadetails/java−0429. import java. 4.0 Main−Class: MyClass Class−Path: Second.com/javadetails/.toURL().forName ("org.getName()).

getCodeSource().toString(). } } Grab this auto−run Jar if you want to try it..").35 Access a JAR outside the CLASSPATH .mdb").getInputStream(entry)). java −jar mydb. and the mydb..printStackTrace().flush(). File efile = new File(dest. if (nBytes <= 0) break. I got a problem when the jar file was located in C:\Program Files\xyz due to the embedded space.getProtectionDomain(). JarFile jar = new JarFile(home). byte[] buffer = new byte[2048]. nBytes).read(buffer).getEntry("mydb. ZipEntry entry = jar. out.getLocation().jar (A tip from Fred Hommersom) Your code reads: String home = getClass().mdb file should appear in the current directory.getLocation(). getCodeSource().mft Manifest−Version: 1. To create an auto−run JAR.0 Classpath: .) { int nBytes = in. So I modified the code to 4.class mydb.. first create a manifest.close().close().write(buffer. in.mft ExtractFromJAR.mdb Run it .getProtectionDomain(). out.jar manifest.toString().getName()).public class ExtractFromJAR { public void extractMyMDBromJAR(String dest){ try { String home = getClass(). entry. 0. } catch (Exception e) { e. } } public static void main(String args []){ new ExtractFromJAR().jar Main−Class: ExtractFromJAR Create the JAR C:\jdk141\bin\jar cvfm mydb.substring(6).extractMyMDBFromJAR(". OutputStream out = new BufferedOutputStream(new FileOutputStream(efile)). substring(6). InputStream in = new BufferedInputStream(jar. for (.\mydb. } out.

jar.println(classJar).getClass().getPath().getClass(). String classJar = this. } System.getCodeSource().say(). import java. If you find this article useful.out.String home = getClass(). public class HelloClass { public static void main(String[] args) { new HelloClass().getName().38 Get list of classes in package (in a Jar) Current version of this HowTo : http://www.jar *** running from jar! jar:file:/C:/DEV/WORK/JAVA/Hello.rgagnon.class (in=1059) (out=601) (deflated 43%) >java com.com/javadetails/.jar!/com/rgagnon/HelloClass.*. " ").class >java −jar Hello.com/javadetails/. '/').println("*** running from jar!"). } public void say() { String className = this.rgagnon. } } The output >jar cvfm Hello.class")./javadetails/java−0513.*. if (classJar.util..getProtectionDomain() .toString(). import java.out.class See these related HowTo's : 1 2 4.io.37 Determine if running from JAR .getResource("/" + className + ". 4.class added manifest adding: com/rgagnon/HelloClass./javadetails/java−0391.getLocation() .startsWith("jar:")) { System.util.mft com\rgagnon\HelloClass.HelloClass file:/C:/DEV/WORK/JAVA/com/rgagnon/HelloClass.replace('.37 Determine if running from JAR Current version of this HowTo : http://www.html import java.'. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 4.jar manifest. consider making a small donation to show your support for this Web site and its content.rgagnon.html package com.*.rgagnon..replaceAll("%20".

out.")).handlers.4.mail. "com.mail.class.getName().mail.class Found com.replaceAll("\\.class. if (debug) System. com.sun.handlers.mail.handlers. } return classes. System.class.replaceAll("/".getName ().mail.endsWith (". try{ JarInputStream jarFile = new JarInputStream (new FileInputStream (jarName)).class Found com.class Found com.getClasseNamesInPackage ("C:/j2sdk1.1_02/lib/mail. public static List getClasseNamesInPackage (String jarName.sun. com .handlers. } if((jarEntry.text_xml.class")) ) { if (debug) System.class Found com.add (jarEntry.message_rfc822.handlers.message_rfc822.text_plain.handlers.getName ().println(list).println ("Jar " + jarName + " looking for " + packageName).mail.sun.mail.handlers.handlers. JarEntry jarEntry.sun.public class PackageUtils { private static boolean debug = true.mail.mail.text_xml.")). } } } catch( Exception e){ e.1_02/lib/mail.handlers.sun.37 Determine if running from JAR .mail.image_gif.mail.multipart_mixed. packageName = packageName.4.sun. while(true) { jarEntry=jarFile.handlers. } /** * */ public static void main (String[] args){ List list = PackageUtils.image_jpeg. classes. .replaceAll("/".out.class Found com.class [com. String packageName){ ArrayList classes = new ArrayList ().text_html. "/"). /* output : Jar C:/j2sdk1.out.sun.sun.class] */ } } 4. "\\. com.jar".text_html.sun.getName().mail.class Found com.handlers.sun.sun.jar looking for com/sun/mail/handlers Found com. "\\.getNextJarEntry ().sun.image_jpeg.handlers")." .startsWith (packageName)) & (jarEntry.println ("Found " + jarEntry. if(jarEntry == null){ break.printStackTrace ().

Hello Then build the executable Jar and run it. package com.say("Hello World!").39 Add version to Jar packaging .jar Hello World! Now modify the manifest to include versioning information.html Let's say we have the following class (package is mandatory) package com. } Hello() { Package p = this.getPackage()./javadetails/java−0388. } } First create a MANIFEST. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 4.println("Hello Specification Version : " + p.out.rgagnon. } public void say(String s) { System.If you find this article useful.0 Main−Class: com.println(s).1 Modify the class to display the version.class >java −jar hello. System. >jar cvfm hello.getClass(). consider making a small donation to show your support for this Web site and its content.com/javadetails/.rgagnon.rgagnon.0 Main−Class: com. Manifest−Version: 1.jar MANIFEST.say("Hello World!").rgagnon.rgagnon.out. public class Hello { public static void main(String[] args) { new Hello().39 Add version to Jar packaging Current version of this HowTo : http://www.MF file : Manifest−Version: 1..MF com\rgagnon\Hello.println("Hello Implementation Version : " 4.out.Hello Specification−Version: 2. public class Hello { public static void main(String[] args) { new Hello().1 Implementation−Version: 1.getSpecificationVersion()). System.

*.getJarImplementationVersion(javaMailJar)).3.out.println(s).3 * Implementation−Version: 1.jar".1 Hello World! See also this Howto. Manifest manifest = jarfile.IOException { JarFile jarfile = new JarFile(jar).MF com\rgagnon\Hello.+ p.getValue("Implementation−Version").0/lib/mail.println("Implementation−Version: " + JarUtils.getMainAttributes().howto.getJarSpecificationVersion(javaMailJar)).jar. /* * output : * Specification−Version: 1.getMainAttributes().out. return att.util. import java. System.getImplementationVersion()).getValue("Specification−Version").1 */ } } 4.rgagnon.getManifest().1 Implementation Version : 1. public class JarUtils { public static String getJarImplementationVersion(String jar) throws java.IOException { JarFile jarfile = new JarFile(jar).class > java −jar hello. } public static String getJarSpecificationVersion(String jar) throws java. package com.jar MANIFEST. Manifest manifest = jarfile. } } Compile and rebuild the Jar and execute > jar cvfm hello.39 Add version to Jar packaging . } public static void main(String[] args) throws java. This example opens a given Jar and outputs its version information.println("Specification−Version: " + JarUtils.out.io. Attributes att = manifest.io. } public void say(String s) { System.5.getManifest(). Attributes att = manifest.IOException{ String javaMailJar = "C:/Program Files/Java/jre1.io.jar Specification Version : 2. return att. System.

xml 4.xml compile: [javac] Compiling 1 source file • Go back to the editor and add the jar building command. } } • Execute your antenv. public class Hello { public static void main( String[] args ){ System." /> </target> <target name="jar" depends="compile"> <jar destfile="hello.5. rename the folder to \Ant • Create a file call antenv.apache.%path% • Create a simple Hello class as shown below (you need have a package).html • Download ANT from http://ant.40 Use ANT to Build a JAR with version/build number .. • .org/bindownload.cmd.class" /> </target> </project> • Execute your Ant script : > ant jar Buildfile: build..out." includes="**/*.cmd to set the environment • Compile your Hello class and make a jar to check if your environment is ok.jar howto/Hello." /> </target> </project> Go back to the DOS shell and launch Ant with > ant compile Buildfile: build.class(in = 415) (out= 284) (deflated 31%) > java −cp hello. You may need to adjust the values according to your installation! set ANT_HOME=c:\ant set JAVA_HOME=C:\Progra~1\Java\jdk1. <project default="buildHello"> <target name="compile"> <javac srcdir=".class added manifest adding: howto/hello.. you must execute this file to set up the environment. and load it into your favorite editor.0 set PATH=%ANT_HOME%\bin.4..%JAVA_HOME%\bin.xml which is the default ant build file .rgagnon. Type the following ant script and save it.40 Use ANT to Build a JAR with version/build number Current version of this HowTo : http://www.println( "Hello World" ). The target compile is also executed since the target jar depends on it. Before using ANT.jar howto.Hello Hello World • Create a build.jar" basedir=".java > jar −cvf hello.cgi • Unzip into the root of C: (Windows)./javadetails/java−0532. <project default="buildHello"> <target name="compile"> <javac srcdir="..com/javadetails/. package howto. > javac howto/Hello.

compile: jar: [jar] Building jar: /Dev/hello. build." /> </target> <target name="jar" depends="compile"> <delete file="hello.MF howto/ howto/Hello. Add the following lines to build.Hello Hello World • Make your Jar auto−executable by specifying the Main class into a MANIFEST.MF"> <attribute name="Built−By" value="${user.number.jar"/> <delete file="MANIFEST. <project default="buildHello"> <target name="compile"> <javac srcdir=". > java −jar hello. is available in your Ant script." /> </target> <target name="jar" depends="compile"> <delete file="hello.Hello"/> 4. The version number is also a property.num (so you need to keep it!).name}"/> <attribute name="Main−Class" value="howto.name}"/> <attribute name="Main−Class" value="howto.jar jar −tvf hello.num"/> <manifest file="MANIFEST. Ant will create (if necessary) and increment a property in a file called build..jar Hello World • Add a build number with the Ant task buildnumber .40 Use ANT to Build a JAR with version/build number .jar" basedir=".jar 0 Wed May 03 17:06:32 55 Wed May 03 17:06:32 55 Wed May 03 17:06:32 335 Wed May 03 16:36:16 EST EST EST EST 2006 2006 2006 2006 META−INF/ META−INF/MANIFEST.Hello"/> </manifest> <jar destfile="hello." includes="**/*.MF"/> <manifest file="MANIFEST. Then a property.MF" /> </target> </project> • Now you can launch Hello with only > ant jar .jar"/> <delete file="MANIFEST.MF file to be included in the Jar.jar BUILD SUCCESSFUL Total time: 2 seconds $ jar −tvf hello.num" value="1.jar howto.class • Try your new Jar file > java −cp Hello.00"/> <buildnumber file="build..MF"/> <property name="version.xml <project default="buildHello"> <target name="compile"> <javac srcdir=".class" manifest="MANIFEST. Here it is hard−coded in the script but you can read it from a file.MF"> <attribute name="Built−By" value="${user.

40 Use ANT to Build a JAR with version/build number . } } • Finally we add a target to cleanup and the main target to build everything to the build. 4.jar" basedir=".Hello"/> <attribute name="Implementation−Version" value="${version.MF" /> </target> <target name="cleanup"> <delete> <fileset dir=".num}−b${build. the entry will be Implementation−Version: 1.num" value="1.jar" basedir=".MF" /> </target> </project> • If you examine the MANIFEST.num"/> <manifest file="MANIFEST.xml file. you now see a new entry Implementation−Version: 1. <project default="buildHello"> <target name="compile"> <javac srcdir="." /> </target> <target name="jar"> <delete file="hello.println("version : " + Hello.getPackage().00"/> <buildnumber file="build.out.jar"/> <property name="version.jar.00−b1 • and after the next build operation." includes="**/*.MF"> <attribute name="Built−By" value="${user.class" manifest="MANIFEST. public class Hello { public static void main( String[] args ){ System.println( "Hello World ").<attribute name="Implementation−Version" value="${version." includes="**/*.num}−b${build.number}"/> </manifest> <jar destfile="hello.MF.MF"/> </delete> </target> <target name="buildHello" depends="compile.." includes="**/*.getImplementationVersion() ).cleanup" /> </project> • Build and launch the Hello class > ant buildHello .out.name}"/> <attribute name="Main−Class" value="howto. package howto.class"/> <fileset file="MANIFEST..00−b2 • Modify the Hello class to read the Implementation−Version information and display it. System.number}"/> </manifest> <jar destfile="hello.class.class" manifest="MANIFEST.

00"/> <buildnumber file="build.\lib 4. Here some techniques to set the classpath definition automatically.class" manifest="MANIFEST.MF"> <attribute name="Built−By" value="${user.00−b3 b3 == build #3 (if it's your third build !) Build number is great but a Built date is useful too! . <target name="jar"> <delete file="hello.name}"/> <attribute name="Main−Class" value="howto.cmd ..num" value="1.cmd @echo off call buildclasspath. we need a set of 3 CMD files to scan a given directory and build the classpath defintion with all the jars found.num}−b${build.jar Hello World version : 1. Written and compiled by Réal Gagnon ©1998−2006 [ home ] 4..num"/> <tstamp> <format property="TODAY" pattern="yyyy−MM−dd HH:mm:ss" /> </tstamp> <manifest file="MANIFEST. consider making a small donation to show your support for this Web site and its content. If you find this article useful.com/javadetails/.number}"/> <attribute name="Built−Date" value="${TODAY}"/> </manifest> <jar destfile="hello.41 Include all jars in the classpath definition .html Specifying all the required jar in the classpath can be a pain.> java −jar hello./javadetails/java−0587. 4..42 Windows batch file For Windows 2000 (or better).rgagnon.Hello"/> <attribute name="Implementation−Version" value="${version.jar" basedir="." includes="**/*.jar"/> <property name="version.MF" /> </target> See also this Howto . main.41 Include all jars in the classpath definition Current version of this HowTo : http://www.

jar ) do call buildclasspath_append. All jar files in the specified directory. will be similarly expanded... The CLASSPATH environment variable. javac −cp "C:\mylib\*" HelloWorld. where defined.%1 With XP (or better). java MyClass 4.html. then the class path element foo/* is expanded to a A. except that the order of jar files is unspecified.JAR.JAR.%CLASSPATH% :END buildclasspath_append.jar:b. ex. For example. java MyClass buildclasspath.Echo The Classpath definition is %CLASSPATH% . even hidden ones.jar) DO set CLASSPATH=!CLASSPATH!. As a special convenience.jar and b. a single batch file can do the job.com/javase/6/docs/technotes/tools/windows/java.sun.43 JDK6 . it's simpler .. if directory foo contains a. there is a new way to include jars in a given directory without explicitly to specify each one of them.cmd %%~fsi if "%_CLASSPATH%" == "" goto END set CLASSPATH=%_CLASSPATH%.%%G Echo The Classpath definition is %CLASSPATH% .) FOR /R ... @echo off setlocal ENABLEDELAYEDEXPANSION if defined CLASSPATH (set CLASSPATH=%CLASSPATH%.do?bug_id=6510337 Note : Use quote to avoid problem during the wildcard expansion.. are included in the list.\lib %%G IN (*. A classpath entry consisting simply of * expands to a list of all the jar files in the current directory.43 JDK6 According to http://java.sun.java 4.cmd set CLASSPATH=%CLASSPATH%.JAR (a java program cannot tell the difference between the two invocations). Note : There is a bug when using this feature with JAVAW..) else (set CLASSPATH=. see http://bugs.com/bugdatabase/view_bug. 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 .cmd set _CLASSPATH=%CLASSPATH% set CLASSPATH=%1 for %%i in ( %1\*.jar or .

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/*. lib/utils.44 JAR (and ANT) . See http://java.jar mailer_client. Manifest−Version: 1. compile" description="generate jar" > <jar destfile="${dist}/${jar}"> <manifest> <attribute name="Main−Class" value="${Main_Class}"/> <attribute name="Class−Path" value=".0 Class−Path: customer_client. Remember that when you launch an application with java −jar myjar.jar"/> </fileset> </path> <pathconvert property="manifest.jar lib/client.com/docs/books/tutorial/deployment/jar/downman.jar" to="lib/*. so ensure that your editor is not set up to trim trailing spaces on saves and exits. The line with the Class−Path: 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.jar The manifest file format restrictions mandated by the JDK requires the use of a space ' ' character as the line continuation character.44 JAR (and ANT) The best solution when you have a jar is to try to include the required jars into the manifest declaration. <target name="MyJar" depends="dist.html Ant can be used to build your Jar and built the manifest class−path definition.jar signon_client.classpath" pathsep=" "> <path refid="build.jar"/> </chainedmapper> </mapper> </pathconvert> 4.4.jar the CLASSPATH definition (as defined by the environment variable) is overriden by the "class−path" defined the jar's manifest.sun.classpath"/> <mapper> <chainedmapper> <flattenmapper/> <globmapper from="*.

45 Detect the browser/JVM type Current version of this HowTo : http://www.*.org/manual/CoreTasks/manifestclasspath.println("This browser is a Netscape Browser.classpath}"/> </manifest> </jar> </target> Latest Ant version (1. <manifest> <attribute name="Main−Class" value="com.applet. public class BrowserDetector extends Applet { public void init() { if ( isNetscape() ) System.. } public static boolean isNetscape() { try { Class.apache.dir}"> <include name="*. } catch (ClassNotFoundException e) { System. </jar> 4. return false./javadetails/java−0160.out..MozillaAppletContext")..mycompany.println("This browser is not a Netscape Browser.file}"> <classpath refid="build−classpath" /> </manifestclasspath> <jar> ...TestMain"/> <attribute name="Class−Path" value="${manifest.7) includes a task called ManifestClassPath which converts a classpath into a space−separated list of items used to set the Manifest Class−Path attribute.dir}/${jar.TestMain"/> <attribute name="Class−Path" value=".").<target depends="compile" name="buildjar"> <jar jarfile="${basedir}/${test.println("This browser is a Microsoft Browser.html One way is to instanciate a known browser−specific method and catch the Exception if not found import java.").html <path id="build−classpath"> <fileset dir="${build. See http://ant.45 Detect the browser/JVM type .jar"/> </fileset> </path> <manifestclasspath property="lib.forName("netscape.rgagnon.list}"/> </manifest> .applet.").out. } 4.out.com/javadetails/.mycompany.list" jarfile="${build. if ( isMicrosoft() ) System. ${lib.jar}"> <fileset dir="${build}" /> <manifest> <attribute name="Main−Class" value="com.

applet.getDefaultToolkit(). else if (appletContext.toString().windows.println("This browser is not a Microsoft Browser.IExplorerAppletContext") theBrowser = "MICROSOFTPLUGINJRE1.appVersion)). versionOk = (v <= parseInt(navigator. By using a javascript entities.startsWith("com. } } Or by examining the string representation of the getAppletContext() method String theBrowser = "APPLICATION".1 applet and finally a version for JDK102−only browser.appName.class exists in three versions. For an application.startsWith( "com.win32.startsWith( "sun.tags.awt.")) theBrowser = "MICROSOFT".applet. the javascript entity is remplaced by the right archive name.ocx. else if (appletContext.startsWith("netscape. else if (appletContext.plugin.AppletPlugin")) theBrowser = "NETSCAPEPLUGIN". String toolkit = Toolkit.ms.")) theBrowser = "NETSCAPE".applet. 4. if (appletContext.navig. if (theBrowser.indexOf(b) != −1). One is using Microsoft−specific classes.context. we detect the JVM type String theJVM = "".v) { browserOk = false.plugin.45 Detect the browser/JVM type .").return true.viewer.WToolkit")) theJVM = "JAVA". else if (toolkit.startsWith ( "sun. The idea is to put all the required classes in an ARCHIVE file.toString(). the other is a JDK1. return browserOk &versionOk.out. } catch (ClassNotFoundException e) { System. During layout time.equals("APPLICATION") { if (toolkit. browserOk = (navigator.startsWith( "sun. else if (appletContext. } return true. we decide which archive to use.startsWith("sun.startsWith( "sun. String appletContext = getAppletContext().awt. else if (appletContext. versionOk = false.ActiveXApplet")) theBrowser = "MICROSOFTPLUGIN.TagAppletPanel")) theBrowser = "HOTJAVA".WToolkit")) theJVM = "JVIEW". by looking at the string representation of the getDefaultToolkit() method. } For example. our MyApplet.startsWith("sunw. } public static boolean isMicrosoft() { try { Class.ms.forName("com.GenericAppletContext"). <HTML></HTML><HEAD> <SCRIPT> function isBrowser(b.hotjava.applet.plugin. else if (appletContext.ms.4. return false.AppletViewer")) theBrowser = "APPLETVIEWER".

html">Oups! You don't have JAVA enabled.rgagnon.class" NAME="myApplet" HEIGHT=400 WIDTH=400 ALT="Oups! You don't have JAVA enabled"> <A HREF="nojava..com/javadetails/.jar".com/javadetails/. 4.jar". } } </SCRIPT></HEAD><BODY> <APPLET CODE ="MyApplet.jar".} archiveToBeUsed = "java102.46 Detect if Java is enabled from HTML Current version of this HowTo : http://www. if (isBrowser("Microsoft". click here.write() method to generate the right APPLET tag instead of a the Javascript entity to be compatible with Netscape and IE. it's in the folder : C:\Documents and Settings\ <username>\ Application Data\ Sun\ Java\ Deployment\ log It's a file with the extension ./javadetails/java−0161.</A> </APPLET> </BODY></HTML> 4.html The Java Console Window Log is also stored on disk.47 See the Java Console Window Log (Java plugin) Current version of this HowTo : http://www. check this How−to <HTML><HEAD></HEAD><BODY> <APPLET CODE="MyApplet.rgagnon.trace 4. } else { if isBrowser("Netscape". 4)) { archiveToBeUsed = "ie4./javadetails/java−0533. On the Windows plateform.class" HEIGHT=100 WIDTH=400 ARCHIVE=}. > </APPLET> </BODY></HTML> NOTE: You may need to use the document.. 4) { archiveToBeUsed = "n4.html For a Javascript solution.46 Detect if Java is enabled from HTML .

rgagnon.46 Detect if Java is enabled from HTML .com http://www.If you find this article useful. consider making a small donation to show your support for this Web site and its content.com 4. Written and compiled by Réal Gagnon ©1998−2006 [ home ] Written and compiled Réal Gagnon ©2007 real@rgagnon.

2 Load resources based upon client environment at startup Current version of this HowTo : http://www. 5 Internationalization . // Object aCheckbox = (JCheckBox)MyResources. [International. One way is to use Properties files and the other are classes extending the ListResourceBundle base class. add(aCheckbox). MessageFormat mf = new MessageFormat (MyResources. add(aLabel). JTextField aTextField. java. JCheckBox aCheckbox. You need to follow a naming standard so that the JVM retrieves the right resources bundle. java. JLabel vLabel.getObject("aCheckbox"). add(aButton).text.getString("aLabel")).java (main program)] import import import import import javax. // String aLabel = new JLabel (MyResources.html There are two ways to include resources based on the current Locale.rb.*. java. java. // String concatenation with MessageFormat Date d = new Date(). public void initGUI(){ setLayout(new FlowLayout()).*.awt.rb. JButton aButton.format(new Object [] { d })).event. aButton = new JButton (mf. JButton vButton.swing.getString("aButton"))./javadetails/java−0133.. Note that if a resource is missing for the current locale then the default definition is used.util.rgagnon.5 Internationalization 5.*.com/javadetails/.1 java−inter 5.rb.*.awt. public class International extends JFrame implements ActionListener { JLabel aLabel. NumberFormat nf.*.

getObject("aNumber")). } catch (ParseException pe) { pe.rb.setText(MyResources.validate(). } } } public static void main(String args[]) { System.").parse(aTextField.printStackTrace().setText(nf.rb.getSource() == vButton) { try { nf.invokeLater(t).getString("numERR")). this.format(dn)). Thread t = new Thread () { public void run() { International frame = new International().rb. // Number input validation vButton = (JButton)MyResources.// Number format output double dn = 3.setVisible(true).getText()). aTextField. vLabel. this.invalidate().util.java (default resources)] import java. vLabel. aTextField = new JTextField(6).getString("numOK")).400). vLabel. add(vLabel). add(aTextField).getBundle("MyResources").addActionListener(this).println("Current Local : " + Locale.1416.*.invalidate().*.*.initGUI(). import javax. vButton.setText(MyResources.getObject("vButton").validate(). } public void actionPerformed(ActionEvent ae) { if (ae. SwingUtilities. public Object [][] getContents() { return contents. add(vButton). } }. frame.. frame.text. setSize(400.swing. 5 Internationalization .out.. nf = (NumberFormat) (MyResources. import java.rb. vLabel = new JLabel("validation message . } } [MyResources. vLabel.getDefault()). public class MyResources extends ListResourceBundle { public static ResourceBundle rb = ResourceBundle.

} [MyResources_fr.long}"}. { "aCheckbox". { "numERR". "aButton" . } static final Object[][] contents = { { "aLabel" . "numERR" . "Valide!"}. "une étiquette (fr)" } .date. "Valid!" }. "Invalid"} [MyResources_en. public class MyResources_fr extends ListResourceBundle { public Object [][] getContents() { return contents.} static { { { { { { { }. }. new JButton("Validation du nombre")}. "aNumber" . new JCheckBox("Oui (fr)")} .java (french language (for Canada) resources)] import java. "une étiquette (fr CA)" } . new JButton("Validate number")}. } static final Object[][] contents = { { "aLabel" .util. } 5 Internationalization . } [MyResources_fr_CA.java (english language resources)] The classname format is [name][language ID][country code]. new DecimalFormat("0. "Invalide"} }.*. "numOK" .util.swing.*.util. "vButton" . "a Label (en)" } }. "aCheckbox".####")}.*.java. public class myResources_fr_CA extends ListResourceBundle { public Object [][] getContents() { return contents. { "vButton" . import javax.java (french language resources)] import java. public class MyResources_en extends ListResourceBundle { public Object [][] getContents() { return contents. You can retrieve a list of language IDs and country codes at the Unicode organization Web site import java. "Today {0. } static final Object[][] contents = { { "aLabel" . { "numOK" . "A Label" } .*. } final Object[][] contents = { "myLabel" . new JCheckBox("Yes") } .

btnQuit. JButton btnQuit.swing.FRANCE. localeCurrent).awt. See this How−to. java.*.*.*.GERMANY }. r0.getString("r1")).rgagnon.java (main program)] import import import import import java. If a specific resource is not in a specific Locale ListResourceBundle then the default resource is used.setText(rb. The properties files must have the .setLocale(localeCurrent). Locale localeCurrent.com/javadetails/. To use a properties file instead of a class to store resources then look at this HowTo.getBundle("ResourcesDynamic".getString("r0")). JRadioButton r0.3 Load resources dynamically Current version of this HowTo : http://www.getString("btnQuit")).html This HowTo lets you select a language and change its GUI to reflect the choice. public class InternationalDynamic extends JFrame implements ActionListener { static Locale[] localesSupported = { Locale.*. a ListResourceBundle.util. [InternationalDynamic. ButtonGroup bg. It is possible to substitute them for Properties files without any change to the code. r1.getString("title")). java. ResourceBundle rb.event. JLabel today.setText(rb.3 Load resources dynamically ..getString("r2")). r1. this. We have a class per Locale.This example uses ListResourceBundle classes to store the required resources. 5. int localeChoosen = 0.awt.US. } public void initText() { setTitle (rb. Locale.*.setText(rb. We are using a special class. r2. rb = ResourceBundle./javadetails/java−0134.setText(rb.properties extension.text. javax. 5. r2. boolean defaultDone = false. to store our resources. public void initLocale(){ localeCurrent = localesSupported[localeChoosen]. Locale. java.

equals("r0")) r0. localeCurrent). } // QUIT button btnQuit = new JButton(). else r2.equals("r1")) r1.3 Load resources dynamically .format(new Object [] { d })).add(r1). else if (rDef.exit(0). // default RADIO button if (!defaultDone) { String rDef = rb. setSize(400. r0 = new JRadioButton().100). // RADIO buttons bg = new ButtonGroup(). bg.setSelected(true). add(r1).add(r0). r2 = new JRadioButton().setText(mf.setSelected(true). defaultDone = true. r1. r1 = new JRadioButton(). // today label today = new JLabel(). } public void actionPerformed(ActionEvent ae){ if (ae. if (rDef.addActionListener(this). btnQuit.addActionListener(this). setVisible(true). add(r0).getSource() == btnQuit) { System.setSelected(true). bg. add(today). MessageFormat mf = new MessageFormat (rb. // r0. } public void initGUI(){ setLayout(new FlowLayout()). } 5.addActionListener(this). } else { if (localeChoosen == 0) r0.setSelected(true).setSelected(true). bg. else r2.getString("rDefault"). add(r2).add(r2). r2.addActionListener(this). else if (localeChoosen == 1) r1.setSelected(true). add(btnQuit).Date d = new Date().getString("today"). today.

{ "today" .util. i. "Example" }. "Quit"}.getDefault()). "r0" }.*.long}"}.long}"}. else if (ae.util. } [ResourcesDynamic_en.getSource() == r1) localeChoosen = 1. { "r1". }. { "r1". }. } static final Object[][] contents = { { "title".3 Load resources dynamically . " (def) {0. " (en) {0. "United States" } . i.getSource() == r2) localeChoosen = 2.getSource() == r0) localeChoosen = 0.else if (ae. "France" } . "United States" } .java (english language resources)] import java. else if (ae. SwingUtilities.*.initText().initLocale(). { "rDefault" . initLocale(). } 5.pack().java (default resources)] import java. { "btnQuit" .date. i. } public static void main(String args[]) { System. { "r2" . "r0" }. "France" } .invokeLater(t). { "today" . pack(). } static final Object[][] contents = { { "title". } } [ResourcesDynamic. i. { "btnQuit" . { "r2" . "Germany"}.initGUI(). { "rDefault" . "Germany"}. public class ResourcesDynamic extends ListResourceBundle { public Object [][] getContents() { return contents. "Example" }. "Quit"}. } }. Thread t = new Thread () { public void run() { InternationalDynamic i = new InternationalDynamic(). { "r0" .out.println("Current Locale : " + Locale. initText().date. { "r0" . public class ResourcesDynamic_en extends ListResourceBundle { public Object [][] getContents() { return contents.

The drawback is when there is a modification. } static final Object[][] contents = { { "title". { "r2".date.[ResourcesDynamic_fr.dd. "Etats−Unis" } . { "rDefault". } [ResourcesDynamic_de.MM. { "btnQuit". With a resources file. the resources were stored in classes. "Quitter" }. "r1" }. { "r0" . it will look for properties files.date. "Deutschland" }. "verlassen"}. } If you find this article useful. from the programmer's point of view. Written and compiled by Réal Gagnon ©1998−2007 [ home ] 5. { "r1". we simply add or modify the resource in a special file with a regular text editor. { "btnQuit". { "today" . " (fr) {0. In fact. "Frankreich" } .java (french language resources)] import java.java (german language resources)] import java. " (de) {0. the ResourceBundle will construct the filename using the same 5. We don't have to specify filenames.4 Load resources via a resources file . public class ResourcesDynamic_fr extends ListResourceBundle { public Object [][] getContents() { return contents. "France" } .com/javadetails/. consider making a small donation to show your support for this Web site and its content. to use properties file very easily. public class ResourcesDynamic_de extends ListResourceBundle { public Object [][] getContents() { return contents. { "r1".. { "today" . "Vereinigte Staaten" } ./javadetails/java−0135. { "r0" . }. we must recompile the class. "Exemple" }. dd/MM/yyyy}"}. { "rDefault".yyyy}"}.util. } static final Object[][] contents = { { "title".*. there is no difference if the resources are stored in classes or properties files. "r2" }.html With the previous JAVA How−to. The JDK provides a class.util.4 Load resources via a resources file Current version of this HowTo : http://www.rgagnon. The ResourceBundle will look first for classes and if not found.*. }. PropertyResourceBundle. "Beispiel" }. "Allemagne" }. { "r2".

getString("r0")). JRadioButton r0.setText(rb.text. rb = ResourceBundle. r2.java] import import import import import java.ResourcesDynamic". this. [InternationalDynamic. 5.*. Locale localeCurrent.setText(rb. public void initLocale(){ localeCurrent = localesSupported[localeChoosen]. MessageFormat mf = new MessageFormat (rb. public class InternationalDynamic extends JFrame implements ActionListener { static Locale[] localesSupported = { Locale.swing. // RADIO buttons bg = new ButtonGroup(). java.getString("today"). } public void initText() { setTitle (rb. If the properties are stored in subdirectory .mechanism used for classes. The ResourceBundle try to load the properties file from the current classpath. javax. let's say that the properties file is in a subdirectory called "subdir" (from the current directory). } public void initGUI(){ setLayout(new FlowLayout()).*. boolean defaultDone = false.*. int localeChoosen = 0. today. r2. Date d = new Date(). localeCurrent).event.GERMANY }. r0.*. java. Then you can load the ResourcesDynamic resources file with ResourceBundle.getBundle("subdir.4 Load resources via a resources file ." instead of "/". java. use ". The file must have the extension .getString("btnQuit")). ResourceBundle rb.FRANCE. ButtonGroup bg. For example. JLabel today.properties. JButton btnQuit.awt. r1. localeCurrent).getString("r1")).setText(rb.ResourcesDynamic".setText(rb. r1. Locale.setText(mf. btnQuit.getBundle("res. localeCurrent).util.getString("r2")). Locale.*.awt.setLocale(localeCurrent).US.format(new Object [] { d })).getString("title")).

// today label today = new JLabel().add(r2). } public static void main(String args[]) { System.exit(0).getSource() == r1) localeChoosen = 1. } else if (ae.getSource() == r0) localeChoosen = 0.equals("r1")) r1. add(btnQuit).addActionListener(this).addActionListener(this). else r2. } else { if (localeChoosen == 0) r0. bg.4 Load resources via a resources file . } // QUIT button btnQuit = new JButton(). add(r2). 5. setVisible(true). if (rDef. initLocale(). bg.add(r1). initText(). else if (ae.addActionListener(this).equals("r0")) r0.addActionListener(this).add(r0).getSource() == btnQuit) { System.setSelected(true).setSelected(true). // r0. else if (rDef. // default RADIO button if (!defaultDone) { String rDef = rb.r0 = new JRadioButton().getDefault()). r2 = new JRadioButton(). add(r0). else r2. btnQuit.setSelected(true). r2.getString("rDefault"). r1. setSize(400.setSelected(true). } public void actionPerformed(ActionEvent ae){ if (ae.println("Current Locale : " + Locale. else if (localeChoosen == 1) r1. r1 = new JRadioButton(). add(r1). defaultDone = true.setSelected(true).out. else if (ae. pack().setSelected(true).100). add(today). bg.getSource() == r2) localeChoosen = 2.

invokeLater(t).MM.initGUI().properties] title=Example r0=United States r1=France r2=Germany rDefault=r0 btnQuit=Quit today=(en) {0. } }. SwingUtilities.4 Load resources via a resources file . i. i.long} [ResourcesDynamic_fr. i.date.Thread t = new Thread () { public void run() { InternationalDynamic i = new InternationalDynamic().date.properties] title=Example r0=United States r1=France r2=Germany rDefault=r0 btnQuit=Quit today=(def) {0. consider making a small donation to show your support for this Web site and its content.properties] title=Exemple r0=Etats−Unis r1=France r2=Allemagne rDefault=r1 btnQuit=Quitte today=(fr) {0.initLocale().date.initText(). dd/MM/yyyy} [ResourcesDynamic_de.properties] title=Beispiel r0=Vereinigte Staaten r1=Frankreich r2=Deutschland rDefault=r2 btnQuit=Verlassen today=(de) {0.dd.yyyy} If you find this article useful.date.pack(). Written and compiled by Réal Gagnon ©1998−2007 [ home ] 5.long} [RresourcesDynamic_en. } } [RresourcesDynamic. i.

add(b).com/javadetails/.5 Display "special character" using Unicode Current version of this HowTo : http://www. The euro−currency sign € : String EURO = "\u20ac" For example : import java. public class TestUnicode extends java.applet. public void init () { setLayout(new FlowLayout())..5 Display "special character" using Unicode . Here a quick list for accentued letters : á à â é è ê î ç \u00e0 \u00e1 \u00e2 \u00e9 \u00e8 \u00ea \u00ee \u00e7 Á À Â É È Ê Î Ç \u00c0 \u00c1 \u00c2 \u00c9 \u00c8 \u00ca \u00ce \u00c7 5. public static final String REGISTERED = "\u00ae".awt. Label b = new Label(REGISTERED + " R\u00e9al's Software " + " price : 100 " + EURO).html The copyright symbol © : String COPYRIGHT = "\u00a9"". public static final String EURO = "\u20ac".*. Label a = new Label(COPYRIGHT + " R\u00e9al Gagnon"). The registered symbol ® : String REGISTERED = "\u00ae".Applet { public static final String COPYRIGHT = "\u00a9".rgagnon.5./javadetails/java−0136. } } Output : Java not enabled! A list of Unicode characters is available at the Unicode organization Web site. add(a).

public class MessageBoxExample extends JPanel implements ActionListener { JButton go.netscape.rgagnon.rgagnon. // default value button = new JRadioButton("English".*./javadetails/java−0137.com/Tokyo/Pagoda/1675/ for a more complete overview.addActionListener(this).6 Display chinese/japanese characters Current version of this HowTo : http://www. button. 5.*.geocities. String msg ..properties] Yes=Yes No=No Cancel=Cancel SaveMsg=Do you want to save your data [JOptionPane_fr.com/javadetails/.awt.7 Localize a JOptionPane dialog Current version of this HowTo : http://www.add(button).6 Display chinese/japanese characters .*. one for french.html A useful link to integrate international characters set in Netscape is http://developer.properties] Yes=Oui No=Non Cancel=Annuler SaveMsg=Voulez−vous sauvegarder vos donnees Then import import import import javax.5. group. one for english .html and check also http://www.com/javadetails/.html This example will show 2 radio buttons. true).awt.*. ButtonGroup group. [JOptionPane_en. 5. java.com/software/jdk/i18n. java. button./javadetails/java−0138.US. public MessageBoxExample() { group = new ButtonGroup().setActionCommand("en").swing..util. Create 2 properties files. AbstractButton button. Locale locale. locale = Locale. one for english messages and buttons and the other one for french. java.event. Press the button to display a localized JOptionPane according to the radio button selected. add(button).

US.US. UIManager.showConfirmDialog(this. } public void actionPerformed(ActionEvent e) { int result. rb.getString("Yes")). frame. UIManager.getSource() instanceof JRadioButton) { if (e.getActionCommand().cancelButtonText".FRANCE. button. if (e. 200). go.setVisible(true). group.getString("No")).yesButtonText".addActionListener(this).getPreferredSize()). add(button).6 Display chinese/japanese characters . frame. } } 5.getString("Cancel")). } public static void main(String s[]) { JFrame frame = new JFrame("").setSize(panel.out.put("OptionPane.setActionCommand("fr").put("OptionPane. MessageBoxExample panel = new MessageBoxExample().add(panel."Center").addActionListener(this). button.exit(0). } } public Dimension getPreferredSize(){ return new Dimension(200.noButtonText".button = new JRadioButton("Francais"). frame. UIManager. locale).msg).getString("SaveMsg").println(result). setUILanguage(). rb = ResourceBundle. System. msg = rb.equals("en")) locale = Locale. go = new JButton("Do it").getBundle("JOptionPane".add(button). else locale = Locale. add(go). rb.getContentPane(). } } ). rb. } public void setUILanguage() { ResourceBundle rb.put("OptionPane. frame. } else { // the button action result = JOptionPane.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System. locale = Locale.

doubleValue())./javadetails/java−0139. one for french.getInstance(). one for english.java] 5. [JFileChooser_en.0.properties] Title=JFileChooser de R\u00e9al lookInLabelText=Courant filesOfTypeLabelText=Type de fichier upFolderToolTipText=Remonte Then [LocalizeJFileChooser.rgagnon. Number n = nf.com/javadetails/..rgagnon. one for english . as well as messages produced by the tools provided with the JRE.html Modern Swing release have now built−in ready−to−use translations for the JFileChooser.html Depending on the International setting. The language is choosen based on the current Locale. Create 2 properties files.parse(((TextField)theComponent).8 Validate/Convert a number using the current Locale() Current version of this HowTo : http://www.getText()). The user interface elements provided by the J2SE Runtime Environment 5.5. These user interface elements are localized into the following languages: Sun Supported Locales This example will show 2 radio buttons. BigDecimal aDecimal = new BigDecimal(n./javadetails/java−0299.8 Validate/Convert a number using the current Locale() . Press the button to display a localized JFileChooser according to the radio button selected. messages written by the runtime environment to the standard output and standard error streams.. NumberFormat nf = NumberFormat.properties] Title=Real's JFileChooser lookInLabelText=Current filesOfTypeLabelText=File type upFolderToolTipText=go up [JFileChooser_fr.com/javadetails/. The NumberFormat class can handle this based on the current Locale(). one for french (these files are incomplete but should be enough to get you started). include Swing dialogs. So you don't have to do anything to display the JFileChooser in the right language. 5. numbers with comma as decimal separator may be permitted.9 Localize a JFileChooser Current version of this HowTo : http://www.

getString("Title"). String z_choosertitle. UIManager.util. group.addActionListener(this).getString("filesOfTypeLabelText")).US. add(go). } public void setUILanguage() { ResourceBundle rb.event.setActionCommand("en").put ("FileChooser.fileNameLabelText FileChooser. group. go. rb = ResourceBundle.US.awt. UIManager.addActionListener(this). locale = Locale.*. add(button).getString("upFolderToolTipText")).add(button). java.8 Validate/Convert a number using the current Locale() . rb.upFolderToolTipText".*.put ("FileChooser. rb.filesOfTypeLabelText".swing. ButtonGroup group. button. z_choosertitle = rb. Locale locale. String msg . button = new JRadioButton("Francais").awt. /* do the same with : FileChooser.put ("FileChooser.import import import import javax.setActionCommand("fr"). // default value button = new JRadioButton("English". java. public LocalizeJFileChooser() { group = new ButtonGroup().lookInLabelText". locale = Locale. button. add(button).add(button). UIManager.homeFolderToolTipText FileChooser. button. protected JFileChooser z_chooser. java. rb. locale). public class LocalizeJFileChooser extends JPanel implements ActionListener { JButton go. button.getString("lookInLabelText")).*.getBundle("JFileChooser".detailsViewButtonToolTipText 5. go = new JButton("Do it"). AbstractButton button.newFolderToolTipText FileChooser.addActionListener(this). true).*.listViewButtonToolTipTextlist FileChooser.

if (e.openButtonToolTipText=Open FileChooser.getContentPane().cancelButtonToolTipText=Cancel FileChooser. z_chooser. if (z_chooser. LocalizeJFileChooser panel = new LocalizeJFileChooser(). frame.gargoylesoftware. frame. frame.8 Validate/Convert a number using the current Locale() .")).getActionCommand().FRANCE.US.cancelButtonText=Cancel FileChooser.setDialogTitle(z_choosertitle). */ } public void actionPerformed(ActionEvent e) { int result. } else { z_chooser = new JFileChooser().APPROVE_OPTION) return.getSource() instanceof JRadioButton) { if (e.setCurrentDirectory(new java.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System. You can examine the Swing sources to get these values or check http://www. z_chooser. setUILanguage().saveButtonToolTipText=Save FileChooser.equals("en")) locale = Locale.exit(0).updateButtonText=Update FileChooser. } public static void main(String s[]) { JFrame frame = new JFrame("").setSize(panel.saveButtonText=Save FileChooser.openButtonText=Open FileChooser. 200).io.FileChooser.html for a list of them.com/papers/plafdiff. } } ).getPreferredSize()). else locale = Locale.helpButtonToolTipText=Help Almost all Swing widgets can be customize this way. } } 5.helpButtonText=Help FileChooser.File(". frame. } } public Dimension getPreferredSize(){ return new Dimension(200.add(panel."Center").updateButtonToolTipText=Update FileChooser.setVisible(true).showOpenDialog(this) != JFileChooser.

10 Disable localization Current version of this HowTo : http://www.ClassUse_Subinterface=Sous−interfaces de {0} dans {1} doclet.properties into the tools.doclets.SerialData=Donn\u00E9e s\u00E9rialis\u00E9e\: doclet.Generated_Docs_Untitled=Generated Documentation (Untitled) [standard_fr.Packages=Paquetages doclet.Window_Split_Index={0}\: {1}−Index doclet.region=US MyApplication If you find this article useful.10 Disable localization .Generated_Docs_Untitled=Documentation g\u00E9n\u00E9r\u00E9e Once everything translated.jar making sure that the file is located in the right package (along standard.resources.tools.html By default.SerialData=Serial Data\: doclet..rgagnon. To bypass this configuration.properties (extract)] doclet. we need a file called standard_fr./javadetails/java−0437.Frame_Version=Version avec cadres doclet. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 5.properties.sun. Extract from tools.com/javadetails/. Copy it under the name standard_fr.Since=Since\: doclet.properties files (keep the directory structure). you specify on the command line the locale to be used : java −Duser. consider making a small donation to show your support for this Web site and its content.com/javadetails/.Since=Depuis\: doclet. To add a new language. doclet. you need to create the appropriate resource bundle.Window_Split_Index={0}\: {1}−Index doclet.rgagnon../javadetails/java−0418. doclet. the JVM uses the current locale as defined by the OS. The tools.jar in the lib directory contains the resource bundle standard.language=en −Duser.11 Generate the Javadoc "en français" Current version of this HowTo : http://www. put your standard_fr.Frame_Version=Frame version doclet.ClassUse_Subinterface=Subinterfaces of {0} in {1} doclet.properties (extract)] doclet.Warn_inline_taglet=Inline tag {0} should only be used with a {1}. Translate it (or you can download my "incomplete" version here).5. [standard.standard. in our case for french.properties used by Javadoc to generated the labels.properties in 5.html The javadoc utility uses the regular Java mechanism to internationalize its output.properties.jar.Warn_inline_taglet=Inline tag {0} should only be used with a {1}. The new file must be in the package com. the standard.Packages=Packages doclet.

Take the following example : import java.util. import java. public class TestSort1 { String [] words = { "Réal". consider making a small donation to show your support for this Web site and its content.Arrays.. "Raoul".util.com/javadetails/.*.resources). <javadoc locale="fr" sourcefiles="c:/client/Client. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 5. "Rico" }.com.html Sort utilities are now part of latest JDK versions.java" destdir="javadoc/Client" author="true" version="true" use="true" private="true" windowtitle="Client"> <doctitle><![CDATA[<h1>Client</h1>]]></doctitle> <bottom><![CDATA[<i>Copyright &#169.Arrays./javadetails/java−0343.sort(myArray. public static void main(String args[]) { 5. use the −locale switch on the command line javadoc −locale fr . Using Ant..standard.util. Case insensitive java.sort(myArray). Case sensitive java. 2003 Real's Howto.doclets. To generate in french.</i>]]></bottom> </javadoc> If you find this article useful.tools..CASE_INSENSITIVE_ORDER).*.io.12 Sort a String array Current version of this HowTo : http://www.sun. Sort with international characters.12 Sort a String array . String. NOTE : Make sure the −locale switch is the first one.. "Real".rgagnon.

String[] strArray) { String tmp.sort(words. 5.write("\n").. .12 Sort a String array .flush().out.new TestSort1().text. public static void sortArray(Collator collator. i++) { w.write("Before :\n")..sort(words). } w. To solve the problem . i < 4 .sort(words).util.doit(). // w.Arrays.close(). } public void doit() { try { // to be able output french character at the console Writer w = new BufferedWriter (new OutputStreamWriter(System. replace java. for(int i=0. } java.getInstance(Locale. w.util.write(words[i] + " ")..collator. for(int i=0. "Cp850")).FRENCH)). java.. Locale loc = Locale. w. } catch(Exception e){} } } The output is : Before : Réal Real Raoul Rico After : Raoul Real Rico RéaAl which is wrong since we expect to find "Réal" after "Real". sortArray(Collator. i++) { w. and the output will be : Before : Réal Real Raoul Rico After : Raoul Real Réal Rico Or you can do it the long way : .util. by java.getInstance(loc).FRENCH. w. i < 4 .arrays.arrays. words).write(words[i] + " ").write("\nAfter :\n").

j < strArray..length.13 Accentuated characters in Properties/ResourceBundle file . String s2 = "famille".com/javadetails/. } } } } 5./javadetails/java−0496. notation • To avoid having to type all the \u../javadetails/java−0492. j++) { if( collator. use the native2ascii tool (included with the SDK).println("not ok s1 > s2 ").14 Compare accentuated letters Current version of this HowTo : http://www.. consider making a small donation to show your support for this Web site and its content. // here we are expecting "é" < "f" if (s1.rgagnon. strArray[i] = strArray[j].rgagnon.length == 1) return.out.html The rules are • Only use ISO Latin 1 characters in the Properties/ResourceBundle files • For other characters use the \u.. strArray[j] ) > 0 ) { tmp = strArray[i]. } 5. strArray[j] = tmp. i < strArray.compareTo(s2) > 0) { // s1 lexicographically follows s2 which is not true! System. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 5..html class Test { public static void main(String args[]) { String s1 = "état". for (int i = 0. // // // // // // // // (javadoc) The result of String. The result is zero if the strings are equal. notation manually. compareTo returns 0 exactly when the equals(Object) method would return true.length.compare(strArray[i]. i++) { for (int j = i + 1.13 Accentuated characters in Properties/ResourceBundle file Current version of this HowTo : http://www.. The result is a positive integer if this String object lexicographically follows the argument string.if (strArray.compareTo() is a negative integer if this String object lexicographically precedes the argument string. If you find this article useful..com/javadetails/.

5. equal to or greater than zero // depending on whether the source String is less than. This can be useful before inserting data into a database to made sorting easier. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 5.compare() compares the source string to the target string // according to the collation rules for this Collator.FRANCE).text.util.text.setStrength(java.rgagnon..SECONDARY). // equal to or greater than the target string.Collator frCollator = java.getInstance(java.out.println("ok s1 == s2 ").compare(s1.println("ok s1 < s2 "). another possibility is to convert to uppercase/lowercase both items to be compared.Collator frCollator = java.out. s2) < 0) { // s2 lexicographically follows s1 System.setStrength(java.compareTo(s2) != 0) { System.text. s2) == 0) { // s2 lexicographically follows s1 System. // to be non case sensitive if (frCollator.FRANCE). if (frCollator. consider making a small donation to show your support for this Web site and its content.Collator.setStrength(java.com/javadetails/.text. // Returns an integer less than.Collator./javadetails/java−0456.Collator. String s2 = "État".text.15 Unaccent letters .CANONICAL_DECOMPOSITION).// (javadoc) // Collator.Locale. frCollator.Collator. // or frCollator. } java.SECONDARY). } } } NOTE: Also. } } } Equality class Test { public static void main(String args[]) { String s1 = "état".15 Unaccent letters Current version of this HowTo : http://www.getInstance(java.text.out.util.Collator.Locale. frCollator. If you find this article useful.html The following snippet removes from a String accentued letters and replace them by their regular ASCII equivalent. // here we are expecting "état" == "État" if (s1.compare(s1.text. java.println("not ok s1 != s2 ").

So if we pass à. java.text. JDK1.) and can change at any time without notice with SDK versions (1.è. and are not supported.1. public static void main(String args[]) throws Exception{ System.Ê. public class Accent { public static String value = "é à î _ @". In general.ê. etc). For an alternative to the sun."A").Ù.replaceAll("[ÈÉÊË]".2. so Technique 1 will cause compiler errors in JDK6. s.DECOMP. Then using a regular expression. etc.. s. see Unicode Normalization). However. Windows.replaceAll("[ÀÂ]". s.replaceAll("[èéêë]". s.Û. it can now be found in java.Technique 1 It's a simple using the sun.Ô. Macintosh.Â.replaceAll("[ûù]". since the class is in sun. 1.Normalizer and its usage is slightly different (but enough to break it).Normalizer class.* is risky: they are not portable.é."i").. s.replaceAll("Ô".replaceAll("[ïî]"."u").2.text.NFD).ô"."a"). writing java programs that rely on sun.println(formatString(value)). can be different across OS platforms (Solaris. it is considered outside of the Java platform. s s s s s s s s s s = = = = = = = = = = s. Try : java.à."e")."U"). s. the method returns a + ` . return temp.À.text.Normalizer."E"). replaceAll() and regular expressions on a String can also be used : public class Test { public static void main(String args[]) { String s = "È.Normalizer.normalize(s.* package.ï."").î."I"). // output : e a i _ @ } public static String formatString(String s) { String temp = Normalizer. s.Î.out. We are calling the normalize() with the option DECOMP (for decomposition.û.ù. s.4 import sun.replaceAll("[àâ]". 0)."O").text.normalize(s.Normalizer. Linux.É. you may to take a look at IBM's ICU4J project on SourceForge. } } A note from ajmacher: The Normalizer API changed in JDK6.replaceAll("[ÛÙ]". s."o"). we clean up the string to keep only valid US−ASCII characters.text.â. 1. 5.Ï.text.15 Unaccent letters . Technique 2 As an alternative.Normalizer class.replaceAll("[^\\p{ASCII}]".ë. Normalizer.Ë.3.Form.replaceAll("[ÏÎ]".replaceAll("Ô".2.

append(PLAIN_ASCII. } public static void main(String args[]) { String s = "The result : È. int n = s.e.I.append(c). if (pos > −1){ sb.ç". System.À.é.E.ï. } else { sb.E.A.è.a.û.Ù.O.c } } 5.u. The following HowTo is faster because we using one String to contain all the possible characters to be converted and a String with the ASCII equivalent.u.E. private static final String UNICODE = "\u00C0\u00E0\u00C8\u00E8\u00CC\u00EC\u00D2\u00F2\u00D9\u00F9" +"\u00C1\u00E1\u00C9\u00E9\u00CD\u00ED\u00D3\u00F3\u00DA\u00FA\u00DD\u00FD" +"\u00C2\u00E2\u00CA\u00EA\u00CE\u00EE\u00D4\u00F4\u00DB\u00FB\u0176\u0177" +"\u00C3\u00E3\u00D5\u00F5" +"\u00C4\u00E4\u00CB\u00EB\u00CF\u00EF\u00D6\u00F6\u00DC\u00FC\u0178\u00FF" +"\u00C5\u00E5" +"\u00C7\u00E7" . there are a little bit slow.Â.a.charAt(pos)).U.Û.out.e.i.a.println(AsciiUtils.println(s). int pos = UNICODE.U.e.System.E. for (int i = 0.e.u.E.I.É.I.e.u..ô. i < n.charAt(i).e.à.length().â. i++) { char c = s.Ï.A.i.Î.I.toString().a.. can't be instanciated! private AsciiUtils() { } // remove accentued from a string and replace with ascii equivalent public static String convertNonAscii(String s) { StringBuffer sb = new StringBuffer(). // output : // The result : E. public class AsciiUtils { private static final String PLAIN_ASCII = "AaEeIiOoUu" // grave + "AaEeIiOoUuYy" // acute + "AaEeIiOoUuYy" // circumflex + "AaOo" // tilde + "AaEeIiOoUuYy" // umlaut + "Aa" // ring + "Cc" // cedilla .U.o. So we need to detect the position in the first String and then do a lookup in the second String.convertNonAscii(s)).î.e. // output : E.ë.o } } Technique 3 While the two techniques above are ok.indexOf(c).15 Unaccent letters .Ë.U.Ê.ù.A. // private constructor.A.e.ê. } } return sb.i.i.out.Ô.E.O.

err. } ps. w.out.16 Output french characters to the console Current version of this HowTo : http://www. "Cp850").exit(0). java −Dfile.println(). w. } } } An alternative is to start the JVM and pass on the command line the default file encoding to be used. } catch (UnsupportedEncodingException error) { System.rgagnon.flush(). import java. true.println(error). } } Note : List of supported encodings here 5. // Unicode for "é" try { // output to the console Writer w = new BufferedWriter (new OutputStreamWriter(System.close(). String javaString = "caractères français : à é \u00e9". public class test { public static void main(String[] args) { PrintStream ps = null.write(javaString).io. Then you will be able to use regular System. public class DosString { public static void main(String args[]){ String javaString = "caractères français : à é \u00e9". w. This is done via the OutputStreamWriter class./javadetails/java−0046.*.out.com/javadetails/.encoding=Cp850 MyApp Alternate technique import java.html Since Java string are Unicode encoded.. "Cp850")). you must specified a different encoding when printing to a DOS console.Thanks to MV Bastos for the "tilde" bug fix! 5.16 Output french characters to the console .*.io.println(javaString). } catch (Exception e) { e.printStackTrace().out. System. // Unicode for "é" try { ps = new PrintStream(System.

out./javadetails/java−0524. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 5.17 Get the default character set of the JVM .5.4 System./javadetails/java−0505.out.io.. Clipper. Sybase).17 Get the default character set of the JVM Current version of this HowTo : http://www. consider making a small donation to show your support for this Web site and its content.io.println(System.OutputStreamWriter( new java.18 Convert OEM (DOS) file to Ansi (Windows) Current version of this HowTo : http://www.*. mySQL.html public class Hello { public static void main(String args[]) throws Exception{ // not crossplateform safe System.ByteArrayOutputStream()).com/javadetails/.out. This can be useful when migrating data from a legacy database (ex.println(java.html We are using an InputStreamReader which convert the specified input encoding to Unicode and an OutputStreamWriter which from Unicode to the specified output encoding. public class OemToAnsi { public static void main(String args[]) throws Exception{ if (args.nio. import java.length != 2) { System.out.println( "Usage : java OemToAnsi inputdosfile outputansifile" ).com/javadetails/. // jdk1. dBase) to newer DBMS (ex.defaultCharset().getEncoding() ).rgagnon.getProperty("file.encoding")). } } Output example (winXP) >java Hello Cp1252 Cp1252 windows−1252 See also java encoding table for the encoding sets supported. // jdk1.rgagnon.io. 5.charset..5 System. If you find this article useful.Charset.name()).println( new java.

CharsetDecoder.nio.nio.decode(ByteBuffer.nio. String oemString = "". byte bytearray [] = test.CharBuffer. w.ByteBuffer. java.com/javadetails/. // this String is OK //String test = "Real".close(). java.close(). r.19 Detect non−ASCII character in a String Current version of this HowTo : http://www.Charset. r. public class TestAscii { public static void main (String args[]) throws Exception { // this String throws an Exception. "Cp1252")).wrap(bytearray)). codepage output Cp1252" } // input FileInputStream fis = new FileInputStream(args[0]). System. consider making a small donation to show your support for this Web site and its content.exit(1).write(oemString). "Cp850")).readLine()) != null) { w.toString().out. Written and compiled by Réal Gagnon ©1998−2006 [ home ] 5.getBytes().newDecoder().charset. while ( (oemString= r. try { CharBuffer r = d.charset.19 Detect non−ASCII character in a String .println("Test string : " + test).nio.charset.nio. // output FileOutputStream fos = new FileOutputStream(args[1]). } 5. Writer w = new BufferedWriter(new OutputStreamWriter(fos..forName("US−ASCII"). java.CharacterCodingException. } w.out.rgagnon. java. System.println( " note : codepage input Cp850 ).System.exit(0).html import import import import import java.flush(). CharsetDecoder d = Charset. System. } } See also this related HowTo If you find this article useful. BufferedReader r = new BufferedReader(new InputStreamReader(fis./javadetails/java−0536. it contains an accentued letter String test = "Réal".

19 Detect non−ASCII character in a String .rgagnon.com http://www. Written and compiled by Réal Gagnon ©1998−2006 [ home ] Written and compiled Réal Gagnon ©2007 real@rgagnon.println("Ok. it's ASCII only!").println("only regular ASCII characters please!"). } System. // interrupt the processing throw new Exception(e).out.out. } } If you find this article useful.com 5. consider making a small donation to show your support for this Web site and its content.catch(CharacterCodingException e) { System.

/javadetails/java−0028. aTextArea). add("Center" . setSize(500. PrintStream aPrintStream = new PrintStream( new FilteredStream( new ByteArrayOutputStream())). int off. import java.setErr(aPrintStream).event.awt.6 IO 6.html [JDK1.append(aString).awt. aTextArea. System.1] import java.append(aString).. System. } } ). RedirectedFrame(boolean logFile) { this.setOut(aPrintStream).1 java−io 6.2 Redirect output(stdout/stderr) to a frame Current version of this HowTo : http://www. len). if (logFile) { 6 IO .*.rgagnon.300).com/javadetails/. aTextArea. public class RedirectedFrame extends Frame { TextArea aTextArea = new TextArea(). boolean logFile. setLayout(new BorderLayout()). } public void write(byte b[].*.*. int len) throws IOException { String aString = new String(b . displayLog().io.logFile = logFile. off . addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { dispose(). } class FilteredStream extends FilterOutputStream { public FilteredStream(OutputStream aStream) { super(aStream). import java. } public void write(byte b[]) throws IOException { String aString = new String(b). setTitle("Error message").

close().width) / 2. return "−−−−−−\r\n" + sw.println(stack2string(e)).*.height) / 2). } catch (Exception e) { System.newInstance(). Rectangle abounds = getBounds(). } 6.3 Redirect printStackTrace() to a String Current version of this HowTo : http://www.rgagnon.FileWriter aWriter = new FileWriter("error. e.write(aString).forName("unknown")./javadetails/java−0029.height − abounds.log". requestFocus(). aWriter. } } } Check also this simple Swing solution.io.width − abounds.. true).printStackTrace(pw). } catch (Exception e) { // for applet. } } } public void displayLog() { Dimension dim = getToolkit(). Dimension dd = getSize().com/javadetails/. } public static void main(String s[]){ try { // force an exception for demonstration purpose Class. setVisible(true).newInstance(). public class TestStack2String { public static void main(String s[]){ try { // force an exception for demonstration purpose Class.3 Redirect printStackTrace() to a String .toString() + "−−−−−−\r\n".printStackTrace(). } } public static String stack2string(Exception e) { try { StringWriter sw = new StringWriter(). always RedirectedFrame(false) RedirectedFrame r = new RedirectedFrame(true). setLocation((dim. 6.getScreenSize(). PrintWriter pw = new PrintWriter(sw).html import java. e. aWriter.out. (dim.forName("unknown"). // or this could be changed to: // throw new Exception().

exit(0). true.close().html Since Java string are Unicode encoded. java −Dfile. // Unicode for "é" try { ps = new PrintStream(System. w. String javaString = "caractères français : à é \u00e9". } catch (Exception e) { e. } catch (UnsupportedEncodingException error) { System. "Cp850").*.write(javaString).println(). you must specified a different encoding when printing to a DOS console. System.out. "Cp850")).encoding=Cp850 MyApp Alternate technique import java. w. 6. } } } 6.rgagnon.printStackTrace(). } ps. // Unicode for "é" try { // output to the console Writer w = new BufferedWriter (new OutputStreamWriter(System. This is done via the OutputStreamWriter class.com/javadetails/. public class test { public static void main(String[] args) { PrintStream ps = null. w. } } } An alternative is to start the JVM and pass on the command line the default file encoding to be used.*.4 Output french characters to the console . public class DosString { public static void main(String args[]){ String javaString = "caractères français : à é \u00e9".out.io.out.println(javaString).flush().io.println(error).. Then you will be able to use regular System./javadetails/java−0046.4 Output french characters to the console Current version of this HowTo : http://www. import java.err.catch(Exception e2) { return "bad stack2string".

sys But the bad news is that you are restricted this way to run only DOS−based application so it won't work for Java stuff!!! So the only solution left for NT (unless you write some JNI functions.10H".println(ANSI_CLS).SYS : device=c:\windows\command\ansi.out. for (int i=0. String ANSI_AT55 = "\u001b[10. see this HowTo) is to use brute force.println(). } } NOTE: Check this "old" text file to have an overview of ANSI.sys Then you send the appropriate escape codes to the console public class AnsiConsole { public static void main(String args[]) { String ANSI_CLS = "\u001b[2J". System.EXE does not support ANSI escape sequences.NT file: dosonly device=c:\winnt\system32\ansi. System. String ANSI_HOME = "\u001b[H". For example. String ANSI_BOLD = "\u001b[1m". The Good news is that you can use COMMAND. NT's CMD.com/javadetails/. System.5 Clear the console and control attributes .read().. System.in.print (ANSI_BOLD + "Press a key.}catch(Exception e){} System. String ANSI_REVERSEON = "\u001b[7m".5 Clear the console and control attributes Current version of this HowTo : http://www.COM instead. this can be done with the driver ANSI.println (ANSI_AT55 + ANSI_REVERSEON + "Hello world" + ANSI_NORMAL).out.out.} } Note : List of supported encodings here 6.rgagnon.SYS. add the following lines in the CONFIG. String ANSI_NORMAL = "\u001b[0m". you need something like this in the CONFIG.out. To use ANSI.." + ANSI_NORMAL). on Win9x installation.println (ANSI_HOME + ANSI_WHITEONBLUE + "Hello world" + ANSI_NORMAL). String ANSI_WHITEONBLUE = "\u001b[37.SYS's Escape Sequences.SYS is loaded via the CONFIG./javadetails/java−0047.html On Win9x.. try {System. 6.println(ANSI_CLS). i++) System.44m".SYS file.out.out. i<25.

NONE).com/javadetails/. g.dispose(). // what you like to print printText(myJob.setDialog(JobAttributes. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 6. s). } } } 6.DialogType.6 Print text to a printer easily Current version of this HowTo : http://www. out.end(). if (myJob != null) { Graphics g = myJob. // the printer to be used PrintJob myJob = getToolkit(). public class SimplePrinting { public static void main(String[] args) { try { FileWriter out = new FileWriter("lpt1").getPrintJob(this. PageAttributes thePageAttribs = new PageAttributes().If you find this article useful.io.getText().getGraphics().html A quick and simple way to output some text to a printer is to print to OS logical device attached a printer. // CR out. if (g != null) { String s = myArea.write("Hello world"). out. on a Windows machine : import java.html JobAttributes theJobAttribs = new JobAttributes()./javadetails/java−0051.. } catch (IOException e) { e. "PrintJob". thePageAttribs).*. } myJob. } 6. For example.rgagnon. consider making a small donation to show your support for this Web site and its content.com/javadetails/.7 Print without a Dialog Current version of this HowTo : http://www../javadetails/java−0350.printStackTrace(). g.write(0x0D). theJobAttribs.setPrinter("HP DeskJet 610C").rgagnon.6 Print text to a printer easily . theJobAttribs.close(). theJobAttribs.

Third method JDK1.1 In you program. } 6.out. public class TestReadLine { public static void main (String args[]) { StreamTokenizer Input=new StreamTokenizer(System. try { aLine = input.print(" Your first name : ").DataInputStream in = new java.io.nextToken().printStackTrace().printStackTrace().readLine().DataInputStream(System.readLine()).0. System.print(s).2 java.8 Simple input from the keyboard Current version of this HowTo : http://www..out.com/javadetails/. System.io. try { i = Integer.io.in).readLine(). } catch (Exception e) { e.print(s).html First method import java.6.InputInt("<prompt>") for an integer./javadetails/java−0053.parseInt(input.println("Hi " + Input.sval + "!"). BufferedReader input = new BufferedReader(new InputStreamReader(System. use EasyInput. System.8 Simple input from the keyboard . } } } Second method JDK1.inputStr("<prompt>") to input a String or EasyInput. } catch (Exception e) { e.out.in)).printStackTrace().in).rgagnon. String aLine = in. } return i. } return aLine. Input.in)). try { System. public class EasyInput { public static int inputInt(String s) { BufferedReader input = new BufferedReader(new InputStreamReader(System. } catch (Exception e) { e. } public static String inputStr(String s) { String aLine = "".*.out. int i =0.

rgagnon. 6. "parity=n". "stop=1". "baud=9600". Then to write. } } } 6. "/c".9 Initialize and write to a serial port .exe".out.com String cmd[] = { "c:\\winnt\\system32\\cmd.html This is for JAVA application only (JDK1. System.com/javadetails/. if( p./javadetails/java−0062. data. public class SerialTest { public static void main( String args[]) { Runtime rt = Runtime.1). }.public static void main(String s[]) { while(true) { int y = inputInt(" Year: "). int m = inputInt("Month: "). "/min". "c:\\winnt\\system32\\mode. BufferedOutputStream bos = new BufferedOutputStream( fos ). (Win)Initialization is done via the MODE. 0.out. // for Win95 : c:\\windows\\command. "start".com // c:\\windows\\command\\mode. fos. fos.5 provides the Scanner class to do this. String portname = "com1:".. System.exit( −1 ). portname.length ).println("Error executing command: " + cmd ). FileOutputStream fos = new FileOutputStream( portname ).exec( cmd ).".printStackTrace(). see this HowTo.com". } } } NOTE: JDK 1. simply open a stream using the OS logical name attached to the serial port.9 Initialize and write to a serial port Current version of this HowTo : http://www.getRuntime(). } catch( Exception e ) { e. String you = inputStr("Your name: ").getBytes(). } byte data[] = "Writing a byte stream out of a serial port.COM utility. "data=8".close(). try { p = rt.println(you + " " + y + m + d).waitFor() != 0 ) { System.write( data. int d = inputInt(" Day: "). You can use the same technique to print to the printer port (in this case the local name would be "LPTx:"). Process p = null.

com/javadetails/. } int index = name..11 Get the volume label Current version of this HowTo : http://www. index). } public static String get(String path) { FileSystemView view = FileSystemView. if (name == null) { return null. If you find this article useful.length() < 1) { return null. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 6. System. if (name == null || name.rgagnon.*.PrintStream(new java. System. import javax.. public class VolumeLabel { private VolumeLabel() { } public static void main(String[] args) { System.io. } 6.setErr(nps). String name = view.6..setErr(nps).lastIndexOf(" (").html This will retrieve the hard disk volume label : import java. System.10 Redirect to a NULL device .*.io.getFileSystemView().setOut(new java.swing. } name = name.setOut(nps).filechooser.io./javadetails/java−0453. consider making a small donation to show your support for this Web site and its content.OutputStream() { public void write(int b){}})).10 Redirect to a NULL device Current version of this HowTo : http://www.out.substring(0.setOut(nps).trim().rgagnon.html This can be useful if you want to suppress all output. System. if (index > 0) { name = name.println("\"" + get(args[0]) + "\"")./javadetails/java−0455.com/javadetails/. File dir = new File(path). //Windows style PrintStream nps = new PrintStream(new FileOutputStream("NUL:")). System. //One−liner style : subclass OutputStream to override the write method .. // Unix style PrintStream nps = new PrintStream(new FileOutputStream("/dev/null")).getSystemDisplayName(dir).

. consider making a small donation to show your support for this Web site and its content./javadetails/java−0491.html A Scanner breaks its input into tokens using a delimiter pattern.rgagnon.13 Open or close a CD/DVD drive Current version of this HowTo : http://www.*.12 Easy keyboard input (JDK1. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 6.return name.com/javadetails/.5) Current version of this HowTo : http://www. System. which by default matches whitespace. } } The output Running from c:\temp >java VolumeLabel c: "temp" >java VolumeLabel c:\ "HARDDISK1" If you find this article useful. consider making a small donation to show your support for this Web site and its content.com/javadetails/. import java. The resulting tokens may then be converted into values of different types using the various next methods.rgagnon. class TestScanner { public static void main(String args[]) { String input = "10:11:12".hasNextInt()) { int i = sc.useDelimiter(":").html Java provides no way to interact with a cd drive.println(i).12 Easy keyboard input (JDK1. 6. Scanner sc = new Scanner(input). while (sc.nextInt(). One easy way on the Windows plateform is to call a VBS script. } } } If you find this article useful.. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 6.util.out./javadetails/java−0574.5) .

Eject". Runtime.cdromCollection.exec("wscript " + file.close().12 Easy keyboard input (JDK1.waitFor().Component) null.getPath()).io. "CDUtils". // thanks to TrueJavaProgammer for the waitFor() tip! // Runtime.close().getByDriveSpecifier(\"" + drive + "\") \n" + "cd. // to close a CD.write(vbs). import java. fw.io.sleep(2000).cdromCollection. public class CDUtils { private CDUtils() { } public static void open(String drive) { try { File file = File. // Thread. String vbs = "Set wmp = CreateObject(\"WMPlayer.deleteOnExit(). 6. fw.DEFAULT_OPTION).Eject ". // Thread.write(vbs).FileWriter(file).getPath()). "Press OK to close CD".awt.Eject \n " + "cd. javax.showConfirmDialog((java. fw.Component) null. Runtime.exec("wscript " + file.printStackTrace().getByDriveSpecifier(\"" + drive + "\") \n" + "cd.exec("wscript "+ file.getPath()).waitFor(). } catch(Exception e){ e.getPath()).vbs").showConfirmDialog((java.5) . FileWriter fw = new FileWriter(file).". import java. } catch(Exception e){ e. "Press OK to open CD".vbs").swing.".JOptionPane.swing.File.awt.swing. } } public static void main(String[] args){ javax.waitFor().getRuntime().open("D:\\"). } } public static void close(String drive) { try { File file = File.swing. This technique is useful to do something that a regular Java can't do because it's too specific to OS where the Java is running.io.getRuntime(). we are creating a temporary vbs file and execute it.JOptionPane.In this HowTo.sleep(2000).createTempFile("realhowto". "CDUtils".deleteOnExit().DEFAULT_OPTION).JOptionPane. file.OCX\") \n" + "Set cd = wmp.printStackTrace().getRuntime(). // thanks to TrueJavaProgammer for the waitFor() tip! // Runtime.FileWriter. javax.getRuntime().exec("wscript " + file. fw. javax.JOptionPane. CDUtils. we need eject two times! String vbs = "Set wmp = CreateObject(\"WMPlayer. FileWriter fw = new java.OCX\") \n" + "Set cd = wmp. The vbs file is created in the "temporary" folder and is deleted by the JVM at the end. file.createTempFile("realhowto".

. } } NOTE : Windows Media Player version 7 or later is required 6. java.currentTimeMillis() − start)).. System.out. System. java. public class Test { public static void main(String. } System..out. java. java.BufferedWriter.print(String.CDUtils.OutputStreamWriter.io. By default.. the overall execution time will be better.html If your program is doing a lot printing to the console using System. } } The result is >java Test >NUL Loop time: 7000 Now.currentTimeMillis()..out.io. public class Test { public static void main(String.println() is not well suited to handle many repetitive outputs in a batch mode.out.out.io.println("Loop time: " + (System. If your output is mainly ASCII−based then by removing the Unicode−related activities.io.print('\n').args) throws Exception { long start = System. for (int i = 0.io.14 Get faster console output (System.FileOutputStream.args) throws Exception { BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new 6. java. rewrite this program to use a 512−bytes buffer and specify the ASCII as character−encoding to be used.err. i++) { System. i < 1000000.OutputStreamWriter.println() replacement) .io.println() then it is possible to get a good performance boost by using an alternative to do the console output.println() replacement) Current version of this HowTo : http://www. System. java.valueOf(i)).com/javadetails/.out.close("D:\\"). System. Because of its small buffer size.FileOutputStream.FileDescriptor.io.rgagnon.14 Get faster console output (System.BufferedWriter.io.out.out. import import import import java.print("abcdefghijk ")./javadetails/java−0603. Each line is flushed right away. Consider this program : import import import import java.print() is only line−buffered and does a lot work related to Unicode handling.FileDescriptor.

16 Using Runtime. while ((line = input. 6. } } 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..err. BufferedReader input = new BufferedReader (new InputStreamReader(p.out. } input.html Be sure to read this Javaworld article. import java. out.15 Execute an external program Current version of this HowTo : http://www.println("Loop time: " + (System.getInputStream())). public class CmdExec { public static void main(String argv[]) { try { String line. i < 1000000.currentTimeMillis().FileDescriptor.flush().write(String.15 Execute an external program .out). 512).com/javadetails/. long start = System.close(). System.getenv("windir") +"\\system32\\"+"tree.write("abcdefghijk ").*.valueOf(i)). } out.exec() method.rgagnon.getRuntime()./javadetails/java−0014.readLine()) != null) { System.exec (System.println(line). It describes the various pitfalls related to the Runtime. 6. for (int i = 0. } catch (Exception err) { err.currentTimeMillis() − start)).FileOutputStream(java. "ASCII"). i++) { out.exec() This example will capture the output (from stdio) of an external program. } } } 6. Process p = Runtime.com /A").io.write('\n').io.printStackTrace(). out.

6. "−c".cmd (set the errorlevel 0 (execution Ok) @java −version 6.cmd (set the errorlevel manually) @echo hello world @exit 42 test.*. command. "ls > hello"}. } } } test.getenv("temp"))).io. builder.io. Map<String.util. Process p = Runtime. System. p.17 Windows CMD (or BAT) file and retrieve the errorlevel or exitcode // win xp import java.getenv("windir") +"\\system32\\"+"tree.directory(new File(System.println(p.com"). ProcessBuilder builder = new ProcessBuilder(command).17 Windows CMD (or BAT) file and retrieve the errorlevel or exitcode . Runtime.waitFor(). String> environ = builder.exec("test.5.IOException { List<String> command = new ArrayList<String>().environment().printStackTrace().cmd (set the errorlevel 1 (problem detected) @java −garbage test. public class CmdExec { public static void main(String argv[]) { try { String line.getRuntime().add("/A").getRuntime(). import java. public class CmdProcessBuilder { public static void main(String args[]) throws InterruptedException.out.cmd").add(System. 6.*. import java.exitValue()).19 Using the ProcessBuilder Since 1. command. } catch (Exception err) { err.6.*.18 Launch a Unix script String[] cmd = {"/bin/sh".exec(cmd). It's possible to set a starting directory. the ProcessBuilder class provides more controls overs the process to be started.

The following example start a Dial−up connection on the Win plateform : [Dialup.").dll is not available.DLL.getRuntime().doc // to start Word if the doc extension is associated with it. On NT and W2K.RnaDial MyConnection").6).readLine()) != null) { System.20 Windows rundll32 utility Windows File association Any program using the Windows file association mechanism can be started with the rundll32 utility.getenv("temp") ).exec("rundll32. final Process process = builder.dll.println("Directory : " + System.out. myresume.println("Done.println("Program terminated!").exe instead. You still need to press ENTER to CONNECT.out. String line. BufferedReader br = new BufferedReader(isr). while ((line = br.21 PDF (Windows only) public class ShowPDF { public static void main(String[] args) throws Exception { Process p = Runtime.start().waitFor().getRuntime() .java] public class Dialup { public static void main(String[] args) throws Exception { Process p = Runtime. there is an option in the Connection properties to connect automatically. } } The "MyConnection" is the DUN and it's case sensitive. p.20 Windows rundll32 utility . } } 6. Use rasdial. See also this one to open the default browser. Runtime.System. InputStream is = process.ShellExec_RunDLL " + file.getInputStream(). rasdial "connection name" rasdial "connection name" /d to drop rasdial /? for more options 6. See also this HowTo about the new Desktop API.out. } System. InputStreamReader isr = new InputStreamReader(is).out. System.getRuntime() 6. the recommended solution (but you need JDK1. rnaui.getAbsolutePath()).exec ("rundll32 SHELL32. // "file" is the filename of the data file // ex.println(line).exe rnaui.

p.22 PDF (Mac only) public class ShowPDF { public static void main (String[] args) throws Exception{ Process p = Runtime.vbs"). } } If you need to pass arguments. p.23 Path to executable with spaces in them You can include a path for the program to be executed. "\"DummyTitle\"".fileName}. public class Test { public static void main(String[] args) throws Exception { Process p = Runtime.vbs"). or // with a visible console Runtime.pdf").exe\""). 6. 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. you need to put the path in quotes if the path contains spaces.out.getRuntime().exec( "\"c:/program files/windows/notepad. // with no visible console Runtime.waitFor(). Runtime.dll. } } More runddl32 examples 6. 6. String fileName = "c:\\Applications\\My Documents\\test. "start".24 VBSCRIPT // Win9x Runtime.exec("open /Documents/mypdf. // WinNT Runtime.FileProtocolHandler c:/pdf/mypdf.getRuntime(). } } 6. System.println("Done. "−o=This is an option" }.doc".").getRuntime().exec(commands).exec("cscript myscript.getRuntime().getRuntime(). Runtime.getRuntime().exec("start myscript. String[] cmd = { "myProgram.exec("rundll32 url.vbs").exec("wscript myscript. On the Win plateform.getRuntime().exec(cmd).waitFor().getRuntime()..pdf").22 PDF (Mac only) . "/c".vbs").exec("cmd /c start myscript. String[] commands = {"cmd".exe". it's safer to a String array especially if they contain spaces.

It's a feature. String[] commands = {"cmd".io.exec("hh.exec(commands).println("action " + action + " supported? " + desktop..html JDK1. "\"DummyTitle\""..xls".exec("cmd /c start excel.*.getRuntime()./javadetails/java−0579.25 HTML Help (Windows only) .6 The java.exe").awt.rgagnon.26 Start Excel import java..Desktop class uses your host operating system's file associations to launch applications associated with specific file types. "start". Runtime.io.out. if (Desktop.isSupported(action)).IOException.exe myhelpfile.getRuntime(). class StartExcel { public static void main(String args[]) throws IOException { String fileName = "c:\\temp\\xls\\test2. . 6.values()) { System.chm").fileName}.6.com/javadetails/.IOException. for (Desktop. First it's a good idea to check if the Desktop operations are supported on the running plateform. import java. } } 6.isDesktopSupported()) { Desktop desktop = Desktop.25 HTML Help (Windows only) Runtime.getRuntime(). } } It's important to pass a dummy title to the Windows start command where there is a possibility that the filename contains a space.Action.Action action : Desktop. 6. class StartExcel { public static void main(String args[]) throws IOException { Runtime. "/c".getDesktop().27 Launch the application associated with a file extension Current version of this HowTo : http://www.awt. } } To load a worksheet import java.

open(document).com/javadetails/. • PRINT.getDesktop(). take this simple application : public class Program2 { public static void main(String arg[]) { System.. launching the user−default mail client with an optional mailto URI. } See the javadoc at http://java.28 Launch an application from another application .getDesktop().sun./javadetails/java−0394.getDesktop(). dt. launching a registered application to edit a specified file.html See also this HowTo and this one. • OPEN. dt. launching a registered application to open a specified file. launching a registered application to print a specified file. } public static void print(File document) throws IOException { Desktop dt = Desktop.com?SUBJECT=Love me tender&BODY=love me sweet public static void mail(URI document) throws IOException { Desktop dt = Desktop. dt. • EDIT.browse(document). it is more appropriate to instanciate and called the main method of the other application.out. launching the user−default browser to show a specified URI • MAIL. } // default browser public static void browse(URI document) throws IOException { Desktop dt = Desktop.com/javase/6/docs/api/java/awt/Desktop.print(document). then // application associated to a file extension public static void open(File document) throws IOException { Desktop dt = Desktop.getDesktop(). For example. dt. } } To call the above application from another 6. 6.html While you can exec("java myaotherapp").mail(document). } // default mail client // use the mailto: protocol as the URI // ex : mailto:elvis@heaven.rgagnon.println("Hello from Program2").28 Launch an application from another application Current version of this HowTo : http://www.The possible actions are • BROWSE.

out.println("Hello from Program2").java] public class Program2 { public static void main(String arg[]) { System.out. // if you need parameters // String[] args = new String[] { "Hello". invoke(null.out.println("Hello from Program1a"). [Program2.join(). t1. } } 6. // Class params[] = new Class[] { args.getClass() }). System. } } [Program1a. } catch(Exception e){ e. "world" }.main(new String[]{}).println("Hello from Program2").out.} } } Launch many programs using Thread and use join() to wait for the completion.out.printStackTrace(). t1.println("Hello from Program1a").forName(name). getDeclaredMethod("main".out.} }.println("Hello from Program1b").println("Hello from Program1a"). new Object[] {new String[] {}}).java] public class Program1a { public static void main(String arg[]) throws Exception{ System.public class Program1a { public static void main(String arg[]) { System. new Program1b().} }. The dynamic version is little more tricky. System.out. new Thread(){ public void run() { Program2.start().println("Hello from Program2"). System.start(). System.main(new String[]{}). try { Class. } } The above example is used when the class is hard−coded.out.execute("Program2"). Thread t1 = new Thread(){ public void run() { Program2.println("Hello from Program2"). } public void execute(String name) { Class params[] = {String[]. public class Program1b { public static void main(String arg[]) { System.class}.28 Launch an application from another application . params).

add(lbx). initLbx().html|JAVA http://www.*.rgagnon.awt.awt. // to close the Frame addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { 6.com/javadetails/java−0002. This example is Windows oriented since I have used the start command which supports the file association./javadetails/java−0071. } } class AFrame extends Frame implements ActionListener { List lbx.txt] http://www.com/javadetails/java−0005.*. public class StartBrowser { public static void main(String s[]) { AFrame f = new AFrame(). java. [urlList.The output : C:\>java Program1a Hello from Program1a Hello from Program2 Hello from Program2 Hello from Program2 Hello from Program2 Hello from Program1a 6.rgagnon.rgagnon.29 Start the default browser from an application Current version of this HowTo : http://www.applet. setSize(400.rgagnon. // action on listbox double click lbx.net.html In this snippet. String url[] = new String[50]..html|JAVA http://www.event.html|JAVA http://www.htmL|JAVA How−to How−to How−to How−to How−to 1 2 3 4 5 [StartBrowser.addActionListener(this). java.rgagnon. lbx = new List().*. public AFrame() { // dispaly setup setTitle("URL selection").html|JAVA http://www. the default browser is started with the selected HTML page as parameter.*.io.com/javadetails/java−0004.rgagnon. we initialize a Listbox from a file containing some URLs.*.29 Start the default browser from an application .com/javadetails/java−0001. java.java] import import import import import java.com/javadetails/java−0003.400).com/javadetails/. When we double click an item. java.

dll. // on NT.exe /c " + cmdLine.printStackTrace().29 Start the default browser from an application .getRuntime().dll. you need to start the // command interpreter // String cmdLine = "cmd. lbx. setVisible(true).rgagnon. } public void actionPerformed (ActionEvent ae) { String theUrl = url[lbx.exit(0).open(File) 6.exec(cmdLine).System. you need to start cmd.FileProtocolHandler " + theUrl).htm for rundll32 url.StringTokenizer st = new java. } } ).com/howto.Desktop.rgagnon.readLine())) { java. // lbx.nextToken()).getSelectedIndex()].add(st. } catch (Exception e) { e.nextToken()).getRuntime().addItem(st.exec ("rundll32 url. All you need is to replace the last m with %6D.StringTokenizer(aLine. try { String aLine = "".2 } } catch(Exception e) { e.txt")). You may have difficulty to open a URL ending with .exe because start is not // an external command but internal.6 has java. BufferedReader in = new BufferedReader(new FileReader("urlList.printStackTrace(). } } } Another way on Windows platform to start the default browser is . } } public void initLbx() { int i = 0.nextToken(). // start the default browser (Win95 platform) // on listbox double click String cmdLine = "start " + theUrl. "|").htm.ht%6D JDK1.FileProtocolHandler http://www. url[i++] = st. while(null != (aLine = in.util. try { Process p = Runtime.awt. like rundll32 url. Runtime. in JDK1.com/howto.FileProtocolHandler http://www.dll.util.

*.showMessageDialog (null.lnk) . import java.4 and later. JOptionPane. 6. e.com/javase/6/docs/api/java/awt/Desktop.ERROR_MESSAGE).com/javadetails/."Oups".dev. } catch (MalformedURLException e1) { e1. try { Runtime.getRuntime().xox file type.html A Shortcut is stored in a file with the extension lnk. } See also this HowTo. // we assume that the ./javadetails/java−0592.getCanonicalPath().See http://java. First the java program to be associated with the . } catch (Exception e){ JOptionPane. } catch (DesktopException e2) { e2.html JDIC provides the equivalent API for 1. } 6.30 Execute a Windows Shortcut (.html In this example.com").lnk").lnk is in the current directory String currentDir = new File(".").lnk) Current version of this HowTo : http://www./javadetails/java−0571.30 Execute a Windows Shortcut (.io.net try { Desktop.xox will be defined and associated with a java program (display the first 10 lines of selected .java.rgagnon. public static void main(String args[]) throws Exception{ 6.exec ("cmd /c start " + currentDir + "/viewLog.rgagnon.sun. public class Head { static final int MAX_LINES = 10...com/javadetails/. a file with the extension .xox file).31 Create a file association with a Java program Current version of this HowTo : http://www.rgagnon. See https://jdic.printStackTrace().printStackTrace().getMessage().browse(new URL("http://www.

two commands are used to define a file association.in)).JS.lnk) . In this example..0\bin\java −cp c:\dev\work Head %1 Now. The assoc command sets up an association between a file name extension and a file type. System. i++. the classpath to load the Head. You need to execute these commands from an account with Administrator privilege.xox. and a string to be used to execute it. To know more about these commands.5.xox file and the associated program will be launched with that file as a parameter. >assoc . FileInputStream fin = new FileInputStream(args[0]).readLine()...WSH then you will be able. a Dos shell is opened. int i = 0 .xox=Xoxfile . assoc and ftype.JSE..WSF..xox file type.. 6.").print("*** Press any key.String line = null. } } With Windows. First we define the .COM.5..xox=Xoxfile Then we specify which program is used to handle the Xoxfile type of file..xox extension. from a Dos shell. See also this HowTo. to type only the name of . the Head class is launched with the clicked filename as a parameter and the first 10 line are displayed. BufferedReader myInput = new BufferedReader (new InputStreamReader(fin)).. you define the environment variable PATHEXT to include the .CMD.VBS.xox file).XOX.VBE.out. input. we specify the Java JVM to be used. if (i == MAX_LINES) break.EXE. >set pathext=.. while ( (line = myInput.println(line).30 Execute a Windows Shortcut (. } BufferedReader input = new BufferedReader(new InputStreamReader(System. The ftype command sets up an association between a file type name.xox extension. type assoc /? or ftype /? .out.0\bin\java −cp c:\dev\work Head %1 Xoxfile=C:\Program Files\Java\jre1. >ftype Xoxfile=C:\Program Files\Java\jre1. if you double−click on a file with .class plus the parameter (the selected .%pathext% PATHEXT=...readLine()) != null) { System.BAT. To make the file association works from a command line.

6.32 Capture the output from a VBS
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0576.html This HowTo query the Windows Registry for a specific key. The VBS prints the result and from Java, we capture this output. Since we need the output, we must use the VBS interpreter for the console mode (CSCRIPT.EXE).
import import import import java.io.BufferedReader; java.io.File; java.io.FileWriter; java.io.InputStreamReader;

public class VBSUtils { private VBSUtils() { } public static String readWindowRegistry(String key) { String result = ""; try { File file = File.createTempFile("realhowto",".vbs"); file.deleteOnExit(); FileWriter fw = new java.io.FileWriter(file); String vbs = "Dim WSHShell \n" + "Set WSHShell = WScript.CreateObject(\"WScript.Shell\") \n" + "WScript.Echo _ \n" + "WSHShell.RegRead(\"" + key + "\") \n" + "Set WSHShell = Nothing \n"; fw.write(vbs); fw.close(); Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath()); BufferedReader input = new BufferedReader (new InputStreamReader(p.getInputStream())); String line; while ((line = input.readLine()) != null) { result += line; } input.close(); } catch(Exception e){ e.printStackTrace(); } return result.trim(); }

public static void main(String[] args){ // // DEMO // String result = ""; msgBox("Get the path of Acrobat reader from the registry"); result = readWindowRegistry ("HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\AcroRd32.exe\\");

6.32 Capture the output from a VBS

msgBox("Acrobat Reader is located in " + result); } public static void msgBox(String msg) { javax.swing.JOptionPane.showConfirmDialog((java.awt.Component) null, msg, "VBSUtils", javax.swing.JOptionPane.DEFAULT_OPTION); } }

6.33 Get a return code from a VBS
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0575.html You can't detect directly if Windows service is running or not in Java. However, it's easy to do from a VBS. You execute the script from Java, wait for its completion and capture the return code. Obviously, this is useful only on the Windows plateform.
import java.io.File; import java.io.FileWriter; public class VBSUtils { private VBSUtils() { } public static boolean isServiceRunning(String serviceName) { try { File file = File.createTempFile("realhowto",".vbs"); file.deleteOnExit(); FileWriter fw = new java.io.FileWriter(file); String vbs = "Set sh = CreateObject(\"Shell.Application\") \n" + "If sh.IsServiceRunning(\""+ serviceName +"\") Then \n" + " wscript.Quit(1) \n" + "End If \n" + "wscript.Quit(0) \n"; fw.write(vbs); fw.close(); Process p = Runtime.getRuntime().exec("wscript " + file.getPath()); p.waitFor(); return (p.exitValue() == 1); } catch(Exception e){ e.printStackTrace(); } return false; }

public static void main(String[] args){ // // DEMO // String result = ""; msgBox("Check if service 'Themes' is running (should be yes)"); result = isServiceRunning("Themes") ? "" : " NOT "; msgBox("service 'Themes' is " + result + " running ");

6.33 Get a return code from a VBS

msgBox("Check if service 'foo' is running (should be no)"); result = isServiceRunning("foo") ? "" : " NOT "; msgBox("service 'foo' is " + result + " running "); } public static void msgBox(String msg) { javax.swing.JOptionPane.showConfirmDialog((java.awt.Component) null, msg, "VBSUtils", javax.swing.JOptionPane.DEFAULT_OPTION); } }

6.34 Execute a CMD file stored in a JAR
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0600.html In this example, a CMD file is stored a JAR file. The Java code extracts the file as a ressource, launch a Windows CMD Shell and write the content to the stdin without any temporary file. In this How−to, the CMD included is used to trigger the default Windows screen saver.
scrnsave.scr /s import java.io.*; public class StartScreenSaver { public static void main(String args[]) throws IOException { new StartScreenSaver().doit(); } public void doit() throws IOException{ String line; OutputStream stdin = null; InputStream stderr = null; InputStream stdout = null; try { // that our CMD file in our JAR InputStream is = getClass().getResource("/screensaver.cmd").openStream(); BufferedReader brCmdLine = new BufferedReader(new InputStreamReader(is)); // launch CMD and grab stdin/stdout and stderr Process process = Runtime.getRuntime ().exec ("cmd"); stdin = process.getOutputStream (); stderr = process.getErrorStream (); stdout = process.getInputStream (); // "write" the CMD file into stdin while ((line = brCmdLine.readLine()) != null) { line += "\n"; stdin.write(line.getBytes() ); } stdin.flush(); stdin.close(); // clean up if any output in stdout

6.34 Execute a CMD file stored in a JAR

BufferedReader brCleanUp = new BufferedReader (new InputStreamReader (stdout)); while ((line = brCleanUp.readLine ()) != null) { //System.out.println ("[Stdout] " + line); } brCleanUp.close(); // clean up if any output in stderr brCleanUp = new BufferedReader (new InputStreamReader (stderr)); while ((line = brCleanUp.readLine ()) != null) { //System.out.println ("[Stderr] " + line); } brCleanUp.close(); } catch (IOException e) { e.printStackTrace(); } finally { stdout.close(); stderr.close(); } } }

Get the JAR here.

6.35 Read the content of a file
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0052.html This following example is for an application. On the command line, give the filename to be displayed.
import java.io.*; public class Cat { public static void main (String args[]) { String thisLine; for (int i=0; i < args.length; i++) { try { FileInputStream fin = new FileInputStream(args[i]); // JDK1.1+ BufferedReader myInput = new BufferedReader (new InputStreamReader(fin)); while ((thisLine = myInput.readLine()) != null) { System.out.println(thisLine); } } catch (Exception e) { e.printStackTrace(); } } } }

6.35 Read the content of a file

With an Applet, we can only open file on the same server that the Applet is coming from.

import java.applet.*; import java.net.*; import java.io.*; public class MyApplet extends Applet { public void init() { readFile("mydatafile.txt"); } public void readFile(String f) { try { String aLine = ""; URL source = new URL(getCodeBase(), f); BufferedReader br = new BufferedReader (new InputStreamReader(source.openStream())); while(null != (aLine = br.readLine())) { System.out.println(aLine); } br.close(); } catch(Exception e) { e.printStackTrace(); } } }

The next Applet reads a data file and inserts the data in a Choice component.

import import import import

java.applet.*; java.awt.*; java.net.*; java.io.*;

public class ReadDataInChoice extends Applet { Choice myChoice; public void init() { myChoice = new java.awt.Choice(); add(myChoice); readFile("dataforchoice.txt"); } public void readFile(String f) { try { String anItem = ""; URL source = new URL(getCodeBase(), f); BufferedReader in = new BufferedReader(new InputStreamReader(source.openStream())); while(null != (anItem = in.readLine())) { myChoice.add(anItem); } in.close(); } catch(Exception e) { e.printStackTrace(); } } }

6.35 Read the content of a file

[dataforchoice.txt]
item item item item item ITEM 1 2 3 4 5 6

Try it here.

The following method read a data file and return the content as a String. We use a StringBuffer to optimize string concatenation operations.
private static String readFile(String filename) throws IOException { String lineSep = System.getProperty("line.separator"); BufferedReader br = new BufferedReader(new FileReader(filename)); String nextLine = ""; StringBuffer sb = new StringBuffer(); while ((nextLine = br.readLine()) != null) { sb.append(nextLine); // // note: // BufferedReader strips the EOL character // so we add a new one! // sb.append(lineSep); } return sb.toString(); }

See this HowTo to read a File which is inside a JAR.

6.36 Read a text file from a jar
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0077.html
import java.io.*; import java.util.*; public class FileUtils{ public static List<String> readTextFromJar(String s) { InputStream is = null; BufferedReader br = null; String line; ArrayList<String> list = new ArrayList<String>(); try { is = FileUtils.class.getResourceAsStream(s); br = new BufferedReader(new InputStreamReader(is)); while (null != (line = br.readLine())) { list.add(line); } } catch (Exception e) { e.printStackTrace();

6.36 Read a text file from a jar

} finally { try { if (br != null) br.close(); if (is != null) is.close(); } catch (IOException e) { e.printStackTrace(); } } return list; } public static void main(String args[]) throws IOException{ List<String> list = FileUtils.readTextFromJar("/datafile1.txt"); Iterator<String> it = list.iterator(); while(it.hasNext()) { System.out.println(it.next()); } list = FileUtils.readTextFromJar("/test/datafile2.txt"); it = list.iterator(); while(it.hasNext()) { System.out.println(it.next()); } } }

Create 2 datafiles. datafile1.txt in the same directory as FileUtils.class (in the root) and datafile2.txt in a subdirectory called test [datafile1.txt]
datafile1 datafile1 datafile1 datafile1 datafile1 line line line line line 1 2 3 4 5

[/test/datafile2.txt]
datafile2 datafile2 datafile2 datafile2 datafile2 line line line line line 1 2 3 4 5

Create the jar with
>"C:\Program Files\Java\jdk1.5.0\bin\jar" −cf MyJar.jar FileUtils.class datafile.txt test/datafile.txt

Try it :
C> java −cp MyJar.jar FileUtils

The output should be like : 6.36 Read a text file from a jar

datafile1 datafile1 datafile1 datafile1 datafile1 datafile2 datafile2 datafile2 datafile2 datafile2

line line line line line line line line line line

1 2 3 4 5 1 2 3 4 5

Get the JAR here With an Applet, it's the same technique
import java.applet.*; import java.io.*; public class ReadFromJar extends Applet{ public void init(){ readTextFromJar("datafile1.txt"); readTextFromJar("test/datafile2.txt"); } public void readTextFromJar(String s) { String thisLine; try { InputStream is = getClass().getResourceAsStream(s); BufferedReader br = new BufferedReader (new InputStreamReader(is)); while ((thisLine = br.readLine()) != null) { System.out.println(thisLine); } } catch (Exception e) { e.printStackTrace(); } } }

Create the JAR
>"C:\Program Files\Java\jdk1.5.0\bin\jar" −cf MyJarApplet.jar ReadFromJar.class datafile1.txt test/datafile2.txt

The html
<HTML><HEAD></HEAD><BODY> <APPLET CODE=ReadFromJar.class width=1 height=1 archive=MyJarApplet.jar> </APPLET> See java console for output</BODY></HTML>

Try it here

6.36 Read a text file from a jar

6.37 Extract a file from a Jar
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0429.html The following snippet extract a file (mydb.mdb) from a jar.
import java.io.*; import java.util.jar.*; import java.util.zip.*;

public class ExtractFromJAR { public void extractMyMDBromJAR(String dest){ try { String home = getClass().getProtectionDomain(). getCodeSource().getLocation().toString(). substring(6); JarFile jar = new JarFile(home); ZipEntry entry = jar.getEntry("mydb.mdb"); File efile = new File(dest, entry.getName()); InputStream in = new BufferedInputStream(jar.getInputStream(entry)); OutputStream out = new BufferedOutputStream(new FileOutputStream(efile)); byte[] buffer = new byte[2048]; for (;;) { int nBytes = in.read(buffer); if (nBytes <= 0) break; out.write(buffer, 0, nBytes); } out.flush(); out.close(); in.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String args []){ new ExtractFromJAR().extractMyMDBFromJAR("."); } }

Grab this auto−run Jar if you want to try it. To create an auto−run JAR, first create a manifest.mft
Manifest−Version: 1.0 Classpath: .\mydb.jar Main−Class: ExtractFromJAR

Create the JAR
C:\jdk141\bin\jar cvfm mydb.jar manifest.mft ExtractFromJAR.class mydb.mdb

6.37 Extract a file from a Jar

Run it ... and the mydb.mdb file should appear in the current directory.
java −jar mydb.jar

(A tip from Fred Hommersom) Your code reads:
String home = getClass().getProtectionDomain(). getCodeSource().getLocation().toString().substring(6);

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", " ");
If you find this article useful, consider making a small donation to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998−2005 [ home ]

6.38 Read a data file with floats
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0078.html [ReadingFloat.java]
public class ReadingFloat { public static float[] readFile(String file, String delimiter) throws Exception { return(readValues(new java.io.FileInputStream(file), delimiter)); } public static float[] readURL(String url, String delimiter) throws Exception { java.net.URL addr = new java.net.URL(url); return(readValues(addr.openStream(), delimiter)); } public static float[] readValues(java.io.InputStream in, String delimiter) throws java.io.FileNotFoundException, java.io.IOException, java.lang.NumberFormatException { String thisLine; java.io.BufferedInputStream s = new java.io.BufferedInputStream(in); java.io.BufferedReader myInput = new java.io.BufferedReader (new java.io.InputStreamReader(s)); int j = 0; float[] values = new float[10]; while ((thisLine = myInput.readLine()) != null) { // scan it line by line java.util.StringTokenizer st = new java.util.StringTokenizer(thisLine, delimiter); while(st.hasMoreElements()) values[j++] = Float.valueOf(st.nextToken()).floatValue();

6.38 Read a data file with floats

} return(values); } public static void main(String arg[]) { new ReadingFloat().demo(); } public void demo() { try { // we assume 10 floats (max)to be read float results [] = readFile("floatwithdelimitercolon.dat", ","); for(int i = 0; i < results.length; i++ ) { System.out.println(results[i]); } System.out.println(); results = readFile("floatwithdelimiterspace.dat", " "); for(int i = 0; i lt; results.length; i++ ) { System.out.println(results[i]); } } catch (Exception e) { e.printStackTrace(); } } }

[floatwithdelimitercolon.dat]
1.2,1.3,1.6,1.78,1.2345 2.2,2.3,2.6,2.78,2.2345

[floatwithdelimiterspace.dat]
1.2 1.3 1.6 1.78 1.2345 2.2 2.3 2.6 2.78 2.2345

6.39 Write to the end of a file
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0054.html [JDK1.0.2]
import java.io.*; public class appendtext { public static void main(String args[]){ try { PrintStream out = new PrintStream(new AppendFileStream("myfile")); out.print("A new line of text"); out.close(); } catch(Exception e) { System.out.println(e.toString()); } } }

6.39 Write to the end of a file

class AppendFileStream extends OutputStream { RandomAccessFile fd; public AppendFileStream(String file) throws IOException { fd = new RandomAccessFile(file,"rw"); fd.seek(fd.length()); } public void close() throws IOException { fd.close(); } public void write(byte[] b) throws IOException { fd.write(b); } public void write(byte[] b,int off,int len) throws IOException { fd.write(b,off,len); } public void write(int b) throws IOException { fd.write(b); } }

[JDK1.1]
FileOutputStream fos = new FileOutputStream("myfile", true);

to open in Append mode

6.40 Write "real" ascii file
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0058.html Java uses Unicode character encoding internally. To pass information to outside world, it may be necessary to use different encoding. For example, DOS application may use MS ISO−Latin 1(or Codepage 850) to represent french characters like é or à. Before writting to a file or in a database record it is necessary to change the default String encoding. This done via the InputStreamReader class for input and OutputStreamWriter for output. InputStreamReader converts from the specified input encoding to Unicode while the OutputStreamWriter converts from Unicode to the specified output encoding.
import java.io.*; import java.awt.*; public class DosString { public static void main(String args[]){ String javaString = "é \u00e9"; // Unicode for "é" try { // output : Unicode to Cp850 (MS−DOS Latin−1) FileOutputStream fos = new FileOutputStream("out.dat"); Writer w = new BufferedWriter(new OutputStreamWriter(fos, "Cp850")); w.write(JavaString);

6.40 Write "real" ascii file

w.flush(); w.close(); // input`: Cp850 to Unicode FileInputStream fis = new FileInputStream("out.dat"); BufferedReader r = new BufferedReader(new InputStreamReader(fis, "Cp850")); String dosString = r.readLine(); r.close(); Frame f = new Frame(); f.setSize(100,100); f.add(new Label(dosString)); f.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }
NOTE: When the character encoding is not specified, the default encoding is used. You can find out the current default encoding by looking at file.encoding property with System.getProperty("file.encoding"); .

6.41 Copy a file
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0064.html [Old technique (pre JDK1.4)]
import java.io.*; public class FileUtils{ public static void copyFile(File in, File out) throws Exception { FileInputStream fis = new FileInputStream(in); FileOutputStream fos = new FileOutputStream(out); try { byte[] buf = new byte[1024]; int i = 0; while ((i = fis.read(buf)) != −1) { fos.write(buf, 0, i); } } catch (Exception e) { throw e; } finally { if (fis != null) fis.close(); if (fos != null) fos.close(); } } public static void main(String args[]) throws Exception{ FileUtils.copyFile(new File(args[0]),new File(args[1])); } }

[JDK1.4 using the java.nio package (faster)]

6.41 Copy a file

import java.io.*; import java.nio.channels.*; public class FileUtils{ public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } public static void main(String args[]) throws IOException{ FileUtils.copyFile(new File(args[0]),new File(args[1])); } }
NOTE: In win2000 , the transferTo() does not transfer files > than 2^31−1 bytes. it throws an exception of "java.io.IOException: The parameter is incorrect" In solaris8 , Bytes transfered to Target channel are 2^31−1 even if the source channel file is greater than 2^31−1 In LinuxRH7.1 , it gives an error of java.io.IOException: Input/output error

ref : http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4643189 On the Windows plateform, you can't copy a file bigger than 64Mb, an Exception in thread "main" java.io.IOException: Insufficient system resources exist to complete the requested service is thrown. For a discussion about this see : http://forum.java.sun.com/thread.jspa?threadID=4396950 The workaround is to copy in a loop 64Mb each time until there is no more data. Replace
... try { inChannel.transferTo(0, inChannel.size(), outChannel); } ...

by
... try { // magic number for Windows, 64Mb − 32Kb) int maxCount = (64 * 1024 * 1024) − (32 * 1024); long size = inChannel.size(); long position = 0;

6.41 Copy a file

while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } ...

6.42 Use a "log file"
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0063.html
/** * Utilities log */ package rgagnon.utils; import java.io.*; import java.text.*; import java.util.*; public class SimpleLog { private static String logFile = "/msglog.txt"; private final static DateFormat df = new SimpleDateFormat ("yyyy.mm.dd private SimpleLog() { } public static void setLogFilename(String filename) { logFile = filename; new File(filename).delete(); try { write("LOG file : " + filename); } catch (Exception e) { System.out.println(stack2string(e)); } } public static void write(String msg) { write(logFile, msg); } public static void write(Exception e) { write(logFile, stack2string(e)); } public static void write(String file, String msg) { try { Date now = new Date(); String currentTime = Log.df.format(now); FileWriter aWriter = new FileWriter(file, true); aWriter.write(currentTime + " " + msg + System.getProperty("line.separator")); System.out.println(currentTime + " " + msg); aWriter.flush(); aWriter.close(); } catch (Exception e) {

hh:mm:ss ");

6.42 Use a "log file"

PrintWriter pw = new PrintWriter(sw).printStackTrace(pw).io. return "−−−−−−\r\n" + sw.toString() + "−−−−−−\r\n".deleteFiles("c:/test/".*. File dir = new File(directory).System.out. See also this HowTo and this one 6. String extension ) { ExtensionFilter filter = new ExtensionFilter(extension). public class FileUtils{ public static void main(String args[]) throws Exception { FileUtils. } public static void deleteFiles( String directory.endsWith(extension)).html Define a special FilenameFilter : import java.43 Delete files with a certain extension . ".*. } } private static String stack2string(Exception e) { try { StringWriter sw = new StringWriter().com/javadetails/. } } and then import java.rgagnon.println(stack2string(e)). String name) { return (name./javadetails/java−0072.io. 6. public ExtensionFilter( String extension ) { this.write("i am here"). } } } and then to use it SimpleLog. public class ExtensionFilter implements FilenameFilter { private String extension.gif")..43 Delete files with a certain extension Current version of this HowTo : http://www. e.extension = extension. } catch(Exception e2) { return "bad stack2string". } public boolean accept(File dir.

. you need to supply 3 arguments : the filename..html The only way to insert a line in a text file is to read the original file and write the content in a temporary file with the new line inserted. list[i]).String[] list = dir.Integer. 6. System.44 Insert a line in a file Current version of this HowTo : http://www.rgagnon.tmp"). i++) { //file = new File(directory + list[i]). String lineToBeInserted) throws Exception { // temp file File outFile = new File("$$$$$$$$.out". [JDK1. j./javadetails/java−0073. } } } } 6.com/javadetails/.printStackTrace().print(file + " deleted : " + file. a line number and the string to be inserted at the line number specified.delete()). int lineno.out 9 "HELLO WORLD" will insert the string "HELLO WORLD" at line number 9 in the file "test. } } public void insertStringInFile (File inFile. java JInsert test. // input FileInputStream fis = new FileInputStream(inFile). file = new File(directory. } catch (Exception e) { e.44 Insert a line in a file .list(filter). if (list.out.insertStringInFile (new File(args[0]). File file. of course you need more error checking. args[2]).length == 0) return.. for (int i = 0. BufferedReader in = new BufferedReader (new InputStreamReader(fis)).length.io. i < list. In this example. public class JInsert { public static void main(String args[]){ try { JInsert j = new JInsert(). Then we erase the original file and rename the temporary file to the original name.1] import java.parseInt(args[1]).*.

out.. while ((thisLine = in.com/javadetails/. 0.rgagnon./javadetails/java−0075. String thisLine = "".. Since our Queue extends the Vector class. } } 6.45 Read a file into a variable in one shot . in.io.close ().renameTo(inFile).html import java. String result = new String (b. in.close(). int i =1.println(thisLine). First the Queue class 6. i++.readLine()) != null) { if(i == lineno) out. b. } } } 6. /* */ System. in. out.class.println(lineToBeInserted).out.// output FileOutputStream fos = new FileOutputStream(outFile). inFile. PrintWriter out = new PrintWriter(fos). the methods needed to serialize the object are already done.rgagnon. } out.printStackTrace().45 Read a file into a variable in one shot Current version of this HowTo : http://www.com/javadetails/. We want to save the state of the Queue in a file.length. byte[] b = new byte[in. DataInputStream in = new DataInputStream (file). All we need is an input or output stream.available ()]. "Cp850").46 Serialize an object to a file Current version of this HowTo : http://www./javadetails/java−0074.flush().delete(). } catch (Exception e) { e. outFile.close(). public class ReadFullyIntoVar { public static void main(String argv[]){ try { FileInputStream file = new FileInputStream (argv[0]).println(result).readFully (b).*.html Suppose we have a class called Queue.

import java.println("serializing theQueue").out. theQueue.45 Read a file into a variable in one shot .printStackTrace().Vector. theQueue.dat"). } Object peek() { if (isEmpty()) return null.println(theQueue. theQueue.close(). 6. ObjectOutputStream oos = new ObjectOutputStream(fout). return o. theQueue = new Queue(). } } To serialize (save the Queue state to a file) : public static void main(String args[]) { Queue theQueue. return firstElement(). oos. oos.import java.put("element 1").writeObject(theQueue). } Object get() { if (isEmpty()) return null.out. theQueue. Object o = firstElement(). theQueue = new Queue(). try { FileOutputStream fout = new FileOutputStream("thequeue.put("element 4").put("element 3").put("element 2"). try { FileInputStream fin = new FileInputStream("thequeue.out. } } To unserialize (to load a previously saved Queue) : public static void main(String args[]) { Queue theQueue.println("unserializing theQueue"). public class Queue extends Vector { /* ** FIFO. } catch (Exception e) { e. System. // serialize the Queue System.dat"). removeElement(o). first in first out */ Queue() { super().util.*.toString()). // unserialize the Queue System.io. } void put(Object o) { addElement(o).

6.*.setOut( new PrintStream( new BufferedOutputStream( new FileOutputStream("OUTPUT.toString()). System. String s1 = "file1. public class FileTest { public static void main(String args[]) { File f = new File(args[0]).49 Check if a file exists Current version of this HowTo : http://www.ObjectInputStream ois = new ObjectInputStream(fin).html import java. File f1 = new File(s1)..exists()? " is found " : " is missing ")).html [JDK1.out.rgagnon. You may want to look at this How−to to redirect exception output to a Frame.48 Get the "last modified" date from a file Current version of this HowTo : http://www.com/javadetails/. String s2 = "file2. } System./javadetails/java−0061.out.dat".47 Redirect stdout to a file Current version of this HowTo : http://www.rgagnon.readObject()./javadetails/java−0068.lastModified() < f2.47 Redirect stdout to a file ..println(theQueue. } catch (Exception e) { e.rgagnon.dat". ois. File f2 = new File(s2).close().1] application only System.html Simply use the lastModified() method from a file object.com/javadetails/.out.io.. 6.printStackTrace().lastModified()) System. but the return value is system dependent and should only be used to compare with other values returned by last modified./javadetails/java−0070.com/javadetails/. It should not be interpreted as an absolute time. theQueue = (Queue) ois.println (f + (f. 6. } 6.DAT")))). if (f1.println((s1 + " IS OLDER THAN " + S2).

public class CurrentDir { public static void main (String args[]) { File dir1 = new File (".getProtectionDomain(). we mean the starting directory.out..out. File f = new File(u.getCodeSource().51 Get the "root" of an application Current version of this HowTo : http://www.printStackTrace().io.IOException.URL.rgagnon.getCanonicalPath()). } } Running from a regular class C:\Applications\dev\HowTo>java −cp . public class DummyApp { public static void main(String args[]) throws Exception{ DummyApp s = new DummyApp().getParent()).File..html import java.getCanonicalPath()).println(f. } } } 6.com/javadetails/.} } 6.toURI()). java.io. java. System."). java.io. s.getLocation().com/javadetails/.out.net.50 Get the current directory . } public void getRoot() throws IOException./javadetails/java−0581.html By root.50 Get the current directory Current version of this HowTo : http://www.File.URISyntaxException. java.net.URI..")./javadetails/java−0076.println ("Current dir : " + dir1.println ("Parent dir : " + dir2. File dir2 = new File (". } catch(Exception e) { e. DummyApp C:\Applications\dev Running from a jar 6.getRoot().rgagnon.net. try { System. URISyntaxException{ URL u = getClass(). System. import import import import import java.

String[] strs = dir. public Filter (String [] extensions) { extensionsSet = new TreeSet().io.io. import java.list() with the filter as a parameter. Here a version to support multiple filters./javadetails/java−0055.io. } } } ex. 6.util.toLowerCase()).io.FilenameFilter and then code the accept() method. for (int i = 0. } public boolean accept (File dir.list(nf).html First you create a class that implements java.toLowerCase(). // current directory File dir = new File (".rgagnon.* C:\Applications\dev\HowTo>java −cp DummyApp.jar DummyApp. java.FilenameFilter.*.out.println (strs[i]).util.52 Get the content of a directory with a Filter .err. public Filter (String str) { pattern = str.println ("usage: java Filter <pattern list> return."). } Filter nf = new Filter (args[0]). public class Filter implements FilenameFilter { protected String pattern.File.length.TreeSet. public class Filter implements FilenameFilter { protected Set extensionsSet.FilenameFilter.com/javadetails/. i++) { System.C:\Applications\dev\HowTo>jar cf DummyApp.52 Get the content of a directory with a Filter Current version of this HowTo : http://www. i < strs.length != 1) { System. java Filter java").jar DummyApp C:\Applications\dev\HowTo See these related HowTo's : 1 2 6.io. import import import import java. then call File.File. The returned array of strings has all the names that passed through the accept()filter. String name) { return name. java.*. } public static void main (String args[]) { if (args.endsWith(pattern. import java. java..

out. String[] strs = dir.next().iterator(). If multiple extensions are to be checked then a regular expression can be used. } Filter nf = new Filter(). import java.remove("").52 Get the content of a directory with a Filter .err. // current directory File dir = new File (".hasNext(). return. } Filter nf = new Filter (args)."). i < strs.list(nf).io.toString().toString())) { return true.jpg" } public static void main (String args[]) { if (args.list(nf). String name) { final Iterator exts = extensionsSet.next(). i < strs. i++) { System.) { extensionsSet.(jpg|jpeg|gif|png|bmp)". } public boolean accept (File dir. ext. // if only one extension to check : "\\.println ("usage: java Filter <pattern list> return.length. import java. for (int i = 0.println ("usage: java Filter <directory> ex.out.File.matches(". } public static void main (String args[]) { if (args.asList(extensions). String name) { return Pattern.length. } } } ex. } } 6.io.hasNext()) { if (name.toLowerCase().iterator().FilenameFilter.err. } } return false.util.println (strs[i]). java Filter c:\\temp").regex. for (int i = 0. import java. } extensionsSet.println (strs[i]). public class Filter implements FilenameFilter { public boolean accept (File dir.for (Iterator ext=Arrays. String[] strs = dir.trim()). java Filter java txt"). // current directory File dir = new File (args[0]).*\\. name). while (exts. i++) { System.add(ext.length < 1) { System.length < 1) { System.toLowerCase().endsWith(exts.*.

System.zip.exe. c:\zip\cc32d48.length. return Arrays. i++) result = result + "|" + recurseInDirFrom(dirItem + File. c:\zip\mp3.separatorChar + list[i]).out.exe. result.c:\zip\Shockwave_Insta 6.asList(_result). c:\zip\RealOneP layerV2GOLD. c:\zip\CODE_UPLOAD 148812122001.23−winfree.zip.23.io. c:\zip\mp3\TWMP3en coder.length > 0) { System.list().c:\zip\mp3\BonkEnc−1.isDirectory()) { list = file.html import java.*. _result[].exe.recurseDir(arg[0])).rgagnon. result = recurseInDirFrom(dir).println(DirUtils. result = dirItem. c:\zip\ok\j2sdk−1_4_1_02−windows−i58 6. if (file. i < list.exe.util. c:\zip\mp3\Tunchy1017full.zip. _result = result.txt. c:\zip\ok\T weakUiPowertoySetup.exe.com/javadetails/.EXE. c:\zip\o k\htmldoc−1. c:\zip\ok\jsref13. } private static String recurseInDirFrom(String dirItem) { File file.53 Get the content of a directory with subdirectories Current version of this HowTo : http://www. System. c:\zip\ok\CmdHerePowertoySetup.exe. } else { System.exe. c:\zi p\mp3\cdex_150b10_enu.out. c:\zip\mp3\hh_install.exe.zip. c:\zip\mp3\T PlayerSetup.split("\\|"). } public static void main(String arg[]) { if (arg.exe.println("recursive Dirs from " + arg[0]).exe. } return result.out.. file = new File(dirItem). c:\zip\ok. public class DirUtils { public static List recurseDir(String dir) { String result.exe.exe.53 Get the content of a directory with subdirectories .8. for (int i = 0. c:\zip\groups2.0−beta1. c:\zip\quickmail−2_1.println(" java DirUtils c:\temp"). c:\zip\httrack−3. } /* output: C:\Applications>java DirUtils c:\zip recursive Dir from c:\zip [c:\zip.zip. c:\zip\AutoIt. c:\zip\RESTorefile2514.out. import java.println("Usage :").exe. c:\ zip\mass20.*.zip. c:\zip\ok\jdk141−hh.} 6. String list[]./javadetails/java−0056.

c:\zip\xpAntiSpy./javadetails/java−0483.write(buf.exe. FileOutputStream fos = new FileOutputStream(args[1]). buf.com/javadetails/.FileOutputStream.rgagnon. consider making a small donation to show your support for this Web site and its content.. i++) { fos. (int)(n % buf. c:\zip\wolf\ok\kf_box.exe.rgagnon. public class CreateAFile { public static void main(String[] args) throws IOException { byte[] buf = new byte[8192].dat // import java.mkDir(). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 6.length. 0.html Use the following recursive method. long m = n / buf. for (long i = 0. c:\zip\wolf\ok.55 Create a fixed−length file Current version of this HowTo : http://www.io.ller_Full.io.length)).write(buf. c:\zip\winamp50_full. long n = Long.zip.zip.54 Make a directory Current version of this HowTo : http://www. c:\zip\wolf\sp_off lag_levels_1−4_final. } } If you find this article useful. td./javadetails/java−0057. } fos. not Applet! File td = new File("NewDirName").close(). 6.com/javadetails/. 0.54 Make a directory ..56 Delete a non−empty directory Current version of this HowTo : http://www. fos.rgagnon. i < m.html For application only.exe.. import java.com/javadetails/.html // // usage : java CreateAFile 2048 twokbytes.zip] */ } } 6.c:\zip\w olf.IOException. c:\zip\Water. 6./javadetails/java−0461.length).parseLong(args[0]).

Plus. in which case the suffix ". i++) { if(files[i].. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 6. (Javadoc) The prefix argument must be at least three characters long. } } } return( path.. If the prefix is too long then it will be truncated.. meaningful string such as "hjb" or "mail".html import java. but its first three characters will always be preserved.isDirectory()) { deleteDirectory(files[i]). . } } If you find this article useful. i<files.57 Create a temporary file .rgagnon.listFiles(). temp.length. the temporary file will be deleted when the virtual machine terminates.import java. File temp = File. Once these adjustments have been made the name of the new file will be generated by concatenating the prefix.io. The suffix argument may be null. consider making a small donation to show your support for this Web site and its content.io.howto"). It is recommended that the prefix be a short.delete().') then the period and the first three characters following it will always be preserved.deleteOnExit(). } else { files[i]. } static public boolean deleteDirectory(File path) { if( path. Creates an empty file in the default temporary−file directory. The location of the directory used to hold temporary files is defined by the property java./javadetails/java−0484.createTempFile("real".io.howto"). using the given prefix ("real") and suffix (".tmpdir.exists() ) { File[] files = path. but if it begins with a period character ('. The default value can be changed with the command line used to launch the JVM : 6. To create the new file. the prefix and the suffix may first be adjusted to fit the limitations of the underlying platform. five or more internally−generated characters.tmp" will be used.". If the suffix is too long then it too will be truncated.57 Create a temporary file Current version of this HowTo : http://www. Deletion will be attempted only for normal termination of the virtual machine.File.delete() ).File.com/javadetails/. for(int i=0. and the suffix. class DeleteDir { public static void main(String args[]) { deleteDirectory(new File(args[0])).

io.rgagnon.getProperty("file.io. public abstract class FileWatcher extends TimerTask { private long timeStamp.separator")./javadetails/java−0490.file = file. a thread is launched to check the lastModified value and compare it with the previous value.timeStamp = timeStamp.getProperty("java. private File file. import java. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 6. } } protected abstract void onChange( File file ).timeStamp != timeStamp ) { this. String tempdir = System.timeStamp = file.*.util.tmpdir do not include a trailing slash. } public final void run() { long timeStamp = file. if( this. consider making a small donation to show your support for this Web site and its content. the temporary directory returned by java.tmpdir=C:\mydir myClass or .io. if ( !(tempdir.endsWith("/") || tempdir. If you find this article useful.tmpdir"). public FileWatcher( File file ) { this.com/javadetails/.lastModified().java −Djava. import java. on Windows..io. } 6.58 Detect file modification Current version of this HowTo : http://www.html For a single file.endsWith("\\")) ) tempdir = tempdir + System.*. Win NT Win XP Solaris Linux −−> −−> −−> −−> C:\TEMP\ C:\TEMP /var/tmp/ /var/tmp It's not a bad idea to check if there is a trailing slash or not. this.58 Detect file modification .lastModified(). onChange(file). On some plateform. That is. you can set the environment variable TMP to a different value.

dfw = new DirFilterWatcher(filter). i <filesArray. public DirWatcher(String path) { this(path.58 Detect file modification . a thread is launched where we keep the Files in a Map. i < filesArray. // scan the files and check for modification/addition for(int i = 0.get(filesArray[i]).put(filesArray[i]. "add"). class FileWatcherTest { public static void main(String args[]) { // monitor a single file TimerTask task = new FileWatcher( new File("c:/temp/text. i++) { dir. 1000 ).listFiles(dfw). we check the current lastModifed value of a given file and compare it with the value stored in the Map.out. ""). // repeat the check every second timer. // transfer to the hashmap be used a reference and keep the // lastModfied value for(int i = 0. new Long(filesArray[i].length.add(filesArray[i]).txt") ) { protected void onChange( File file ) { // here we code the action on a change System.util.import java. filesArray = new File(path). import java. new Date().*. private DirFilterWatcher dfw.schedule( task .*.longValue() != filesArray[i]. String filter) { this. } public DirWatcher(String path.println( "File "+ file. Also a special check is made to detect if a File is deleted.put(filesArray[i]. filesArray = new File(path). public abstract class DirWatcher extends TimerTask { private String path.getName() +" have change !" ). private HashMap dir = new HashMap().path = path. private File filesArray []. import java.io.lastModified())). } } public final void run() { HashSet checkedFiles = new HashSet().lastModified()){ 6. if (current == null) { // new file dir.lastModified())). } } For a directory. i++) { Long current = (Long)dir. Timer timer = new Timer().io.*.length.*. } }. new Long(filesArray[i]. checkedFiles. onChange(filesArray[i]. import java. } else if (current.util.listFiles(dfw).

io.next(). "modify").put(filesArray[i].out. String action ). } class DirFilterWatcher implements FileFilter { private String filter. "txt" ) { protected void onChange( File file. } public DirFilterWatcher(String filter) { this. Iterator it = ref.58 Detect file modification . 1000 ).lastModified())). onChange(deletedFile. class DirWatcherTest { public static void main(String args[]) { TimerTask task = new DirWatcher("c:/temp". new Date(). 6. onChange(filesArray[i]. } } // now check for deleted files Set ref = ((HashMap)dir.removeAll((Set)checkedFiles).filter = "".hasNext()) { File deletedFile = (File)it. import java. new Long(filesArray[i].println ( "File "+ file. } return (file.*.keySet().endsWith(filter)).clone()). ref. dir.iterator(). } }.getName() +" action: " + action ). } } See also this related howto.equals(filter)) { return true.filter = filter. Timer timer = new Timer().getName(). public DirFilterWatcher() { this. } } import java. } } protected abstract void onChange( File file.remove(deletedFile). while (it.util. "delete").// modified file dir. } public boolean accept(File file) { if ("". String action ) { // here we code the action on a change System.schedule( task .*. timer.

io.Charset.println( new java.println("dir : " + f.encoding")). consider making a small donation to show your support for this Web site and its content./javadetails/java−0505. If you find this article useful.60 Parse a pathname Current version of this HowTo : http://www. public class ParsePathname { public ParsePathname() { } public static void main(String[] args) throws Exception { File f = new File ("c:/program files/adobe/Acrobat 5. System.OutputStreamWriter( new java.println(System.nio.name())./javadetails/java−0514.io.com/javadetails/. System.println("file : " + f.out.ByteArrayOutputStream()).getProperty("file. consider making a small donation to show your support for this Web site and its content.html public class Hello { public static void main(String args[]) throws Exception{ // not crossplateform safe System.exe").4 System. System.getParent()).charset. } } Output example (winXP) >java Hello Cp1252 Cp1252 windows−1252 See also java encoding table for the encoding sets supported.println("ext : " + getFileExtension(f.rgagnon.0/Reader/acrord32.defaultCharset().getName()). 6.If you find this article useful.println(java.59 Get the default character set of the JVM Current version of this HowTo : http://www. // jdk1.out.com/javadetails/.getName())). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 6.File.io.5 System.out... // jdk1. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 6.getEncoding() ).59 Get the default character set of the JVM .out.out.rgagnon.out.html import java.

toURL()).println("uri : " + f. if (i > 0 & i < f.out. Any operating system which can run a Java virtual machine can both process and deliver Excel spreadsheets. 6.io. Example : output an Excel file from a Servlet import java.com/javadetails/. } return ext.lastIndexOf('.html There are many solutions to read or write Excel spreadsheets from Java. import java.63 JExcel Java Excel API is a java API enabling developers to read.IOException. consider making a small donation to show your support for this Web site and its content. /* output : dir : c:\program files\adobe\Acrobat 5.out. 6. 6.toLowerCase().62 JDBC−ODBC Excel driver This solution lets you access your Excel worksheet with SQL SELECT statement. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 6.System. The required ODBC driver is included in a regular Windows installation and the JDBC−ODBC bridge is used to access the Excel DSN./javadetails/java−0516.0\Reader file : acrord32. } } If you find this article useful..exe */ } public static String getFileExtension(String f) { String ext = "".toURI()).exe ext : exe url : file:/c:/program files/adobe/Acrobat 5.length() − 1) { ext = f. System.0/Reader/acrord32. and modify Excel spreadsheets dynamically.io.rgagnon.61 Handle Excel files Current version of this HowTo : http://www.'). One nice thing about JExcelApi is that it has no dependencies on any third party libraries. See this HowTo for an example.0/Reader/acrord32.OutputStream. write.61 Handle Excel files .exe uri : file:/c:/program%20files/adobe/Acrobat%205. int i = f.println("url : " + f.substring(i+1). This HowTo is only about OpenSource (and free) solutions.

setCellValue("HelloWorld").write. jxl. FileOutputStream fileOut = new FileOutputStream("workbook.setHeader ("Content−Disposition".WritableWorkbook. javax. public class Sample extends HttpServlet { public void doGet (HttpServletRequest request.write(). w. modify. HttpServletResponse response) throws ServletException.xls").createRow((short)0).net/ 6.HttpServletResponse.64 POI .addCell(new Label(0. wb. HSSFRow row = sheet.getOutputStream()). w. jxl.servlet..ms−excel"). "attachment. WritableSheet s = w.64 POI The POI project consists of APIs for manipulating various file formats based upon Microsoft's OLE 2 Compound Document format using pure Java. Example : create an Excel file HSSFWorkbook wb = new HSSFWorkbook(). } finally{ if (out != null) out. } catch (Exception e){ throw new ServletException("Exception in Excel Sample Servlet".import import import import import import import import javax.sourceforge.http.WritableSheet.createWorkbook(response. HSSF is the POI Project's pure Java implementation of the Excel '97(−2002) file format and it provides a way to read spreadsheets create. javax. javax.ServletException.write(fileOut).setContentType("application/vnd. 0. POI is your Java Excel solution as well as your Java Word solution. s..xls"). WritableWorkbook w = Workbook.write.etc. filename=sampleName. HSSFSheet sheet = wb.createSheet("new sheet"). Since it's Jakarta project. POI has a dependencies with other JARs (commons.close(). } } } See http://jexcelapi.servlet.Label.HttpServletRequest.log4j.servlet. read and write XLS spreadsheets. try { response. 6. e). jxl.write.servlet.createCell((short)0).HttpServlet.http.Workbook. response. jxl.close().createSheet("Demo". row. "Hello World")). IOException { OutputStream out = null. 0).).http.

30)). You can export XLS to XML or SQL INSERT statements. 35.65 JXLS jXLS is a project that allows creation of extremely complex Excel reports just in several lines of code. 3000.put("employee".org/poi/ 6. The name was originally an acronym for "Poor Obfuscation Implementation" (ref: Wikipedia).payment} ${employee.00% 1500 15. xlSQL includes its own "zero−admin" mySQL database. Map beans = new HashMap().66 xlSQL xlSQL is a JDBC Driver for Excel and CSV data sources. Example : The XLS Template Employees Name ${employee. XLSTransformer transformer = new XLSTransformer().bonus} $[SUM(@employee. formulas etc using specific notation to indicate placement of data and then write a couple lines of code to invoke jXLS engine passing XLS template and the exported data as parameters. staff. 0.payment@)] with the code Collection staff = new HashSet(). staff.net/ 6.65 JXLS .name} Age Payment Bonus ${employee. beans.close(). destFileName).00% 4500 See http://jxls. Documents can be read and written with SQL as if they were tables in a database.transformXLS(templateFileName.add(new Employee("Derek".fileOut. beans. With jXLS. 1500. See http://jakarta.age} ${employee.sourceforge.net/ 6. 0.sourceforge. The documentation is minimal at this time. all you need is to create XLS template file with all required formatting. See http://xlsql.15)). It is based on Jakarta POI.apache. staff).add(new Employee("Elsa". 28. transformer. gives the result Employees Name Age Derek 35 Else 28 Payment Bonus 3000 30.

// if already started.out. ExcelWorkbook xlBook = xlBooks.6.println("EXCEL startup.Item(2.so_net. With JCOM you can call a COM object from Java as if it were a Java object without having to deal with the internals of JNI. Example : import import import import jp. i<filenames..out.Item(1).1). System. xlRange.ga2. java.*.1).Item(1.out.Value( file.canWrite()?"Yes":"No" ).Value()). jp. } String expression = "=Sum(B2:B"+(filenames.println(file). xlRange. excel.Workbooks().out.Item(7.no_ji. class TestExcel { public static void main(String[] args) throws Exception { ReleaseManager rm = new ReleaseManager(). The documentation is minimal (in Japanese!). xlRange.67 JCOM .println("UserName="+excel. xlRange.Value( file.Value( (int)file.."). for(int i=0.out. xlRange. ExcelWorkbooks xlBooks = excel.Value("can write"). calculate sum of filesize: "+expression).").Item(4. xlRange.ne. xlRange.no_ji. System. xlRange.Version()).Value( new Date(file.out.Item(7.1). System.*.list().1).1).so_net.jcom. try { System.Value( file. xlRange.i+2).println("Caption="+excel.isFile()?"Yes":"No" ).canRead()?"Yes":"No" ).Visible(true).i+2). // create new book // enumurate all files System.Item(2.ga2. String[] filenames = path.Cells().. ExcelWorksheet xlSheet = xlSheets.i+2).util. xlRange.Item(6.Worksheets().1).Item(1. System.getName() ). xlRange. 6. System.Add(). xlRange.println("Version="+excel. // display any information System.excel8.Item(5.Value("filename" ).Item(3.67 JCOM JCOM is a Java to COM bridge library.i+2).jcom.out.length+1)+")".Value( file.File.Date. ExcelRange xlRange = xlSheet.Value("is file").ne.Caption())..Value( file. xlRange. open new window ExcelApplication excel = new ExcelApplication(rm).Value("last modified time")./").i+2).isDirectory()?"Yes":"No" ).i+2).println ("set infomation of files in current directory to cell .UserName()).println ("embed equation.Value("is directory"). File path = new File(".Item(3. i++) { File file = new File(filenames[i]).length() ).1).Value("can read").Item(4.i+2).lastModified()) ).println("Value="+excel.io.length.Value("size" ). ExcelWorksheets xlSheets = xlBook. java. xlRange.Item(6.out.Item(5.

..xls". See http://www.length+2). . // System.68 OpenXLS Java Spreadsheet SDK OpenXLS claims that it has the best compatibility with complex Excel files and able to handle any kind of Excel file out there without corrupting it.net/projects/jcom See also this HowTo for an alternative package to access a COM package from Java.println("thank you ."Sheet1"). excel.println("Successfully extracted: " + workingdir + "testImageOut_" + extracted[t]. String sheetname){ System.").out. xlBook. if no path.68 OpenXLS Java Spreadsheet SDK . // fit columns // comment out.png.com/estore/product_detail.length+2)..Columns().").Quit(). try{ sheet = tbo.filenames.xlRange. // xlSheet.release().getImages(). FileOutputStream outimg = new FileOutputStream (workingdir + extracted[t]. ..getType()).Item(2.out.xls").PrintOut(). create a new workbook with them) : doit("testImages.println ("save to file..getName()+". if book save to file." +extracted[t].out. xlRange. // output default printer. if print out.Formula(expression). // // // // // comment out. } } } See http://sourceforge. save to(My Documents) System. xlRange. } catch(Exception e) { e.Item(1.println("Begin parsing: " + workingdir + finpath).jpg ImageHandle[] extracted = sheet.AutoFit().length.. 6.xls").extentech. void doit(String finpath.gif.Value("sum"). xlBook. // extract and output images for(int t=0.filenames.getWorkSheet(sheetname).SaveAs("testExcel.t<extracted.t++) { System.getType()). // read images from sheet 1 −− . WorkBookHandle tbo = new WorkBookHandle(workingdir + finpath).false).Close(false. 6. System.printStackTrace().jsp?product_group_id=228 Example (extract 3 images from a workbook. .out. This open source effort is the result of over 6 years of development into it.println("print out.null.getName()+". (My Documents)\\testExcel.out." +extracted[t]. } finally { rm.

write(b.x++) { fin = new FileInputStream(workingdir + "testImages.round((float)((x * (Math. jpgy. } testWrite(tbo. String fout){ try{ java. sheet.IOException e){ System.io.add ("New workbook with 3 images: a gif.xls".flush().getBytes()). // add to sheet ImageHandle giffy = new ImageHandle(fin.err. a jpg. sheet = tbo. 400. pngy.0). // add to sheet ImageHandle pngy = new ImageHandle(fin.setY(200).setX(10). jpgy.png"). workingdir + "testImagesOut. // add to sheet for(int x=0.random()*10)))). sheet.flush(). } tbo = new WorkBookHandle(). sheet).jpg"). // set the random x/y coords of picture int ix = Math. giffy. bbout.write(outimg). jpgy.File(fout).setBounds(100. } catch (java.insertImage(pngy). and a png".io. 100. 6. sheet.println("Successfully read: " + newbook). "A1").x<100.getWorkSheet("Sheet1"). WorkBookHandle newbook = new WorkBookHandle (workingdir + "testImagesOut.setName("heart" + x). } catch(Exception e){ System.println("IOException in Tester. ImageHandle jpgy = new ImageHandle(fin.random()*10)))).setY(100 + ix). sheet). outimg.extracted[t].println("testImages failed: " + e. "+e).File f = new java. 200).68 OpenXLS Java Spreadsheet SDK .io.insertImage(jpgy).err.insertImage(giffy).close(). sheet). BufferedOutputStream bbout = new BufferedOutputStream(fos). FileOutputStream fos = new FileOutputStream(f). } public void testWrite(WorkBookHandle b. CellHandle a1 = sheet. bbout. // get gif image input stream FileInputStream fin = new FileInputStream (workingdir + "testImages. outimg.xls"). System.out. } // get png image input stream fin = new FileInputStream(workingdir + "testImages.round((float)((x * (Math.toString()).gif"). // set just the x/y coords of picture pngy. ix = Math.close().setX(100 + ix). fos.setName("giffy"). // set picture size and location in sheet giffy.

} } See also this HowTo for a way to create a simple XLS without any additional library.sourceforge. All kinds of CSV files can be handled.com/javadetails/.Ostermiller. XML−flat.69 Handle CSV file . etc. If you find this article useful.csvreader.70 com.org/utils/CSV.75 CSVFile A simple set of Java classes used to handle CSV http://sourceforge.rgagnon.util CSV Utils CSVPrinter/CSVParser/ExcelCSVPrinter/ExcelCSVParser http://ostermiller. flat−flat.net/ 6.71 opencsv A simple csv parser library for Java http://opencsv.73 Super CSV This CSV reader/writer makes it easy to read/write objects/maps/string lists with automatic type conversion and constraint checking.net/ 6.com/java_csv..sourceforge./javadetails/java−0591. Excel formatted.php 6. http://supercsv.html 6.net/projects/csvfile 6.sourceforge. Supported transformations : flat−XML. http://www.net/ 6. Written and compiled by Réal Gagnon ©1998−2007 [ home ] 6.74 csvreader Library for reading and writing CSV and plain delimited text files. and XML−XML http://servingxml.69 Handle CSV file Current version of this HowTo : http://www.72 ServingXML Framework for flat/XML data transformations. text qualified. consider making a small donation to show your support for this Web site and its content.html 6.

• Create a PDF import java.com/iText/ [ITEXT] .rgagnon.76 FlatPack Flat file parser that handles CSV.*.77 Create an Excel file Current version of this HowTo : http://www.text./javadetails/java−0586. From a server.com/javadetails/.. iText can deal with RTF and HTML file too.text. FlatPack provides a sorting mechanism for your flat files. remember to send the appropriate MIME TYPE : application/excel to the client..rgagnon.78 Create or process a PDF file Current version of this HowTo : http://www. public class HelloWorld { public static void main(String[] args) { System.lowagie. Nicely documented with many examples. an easy way to import data into Excel is to create an HTML file and embed the date into a TABLE tag. create a file named test.lowagie. 6.76 FlatPack .xls with this content <TABLE> <th><h4>Just testing</h4> <TR><TD width="20">1</TD><TD width="30">2</TD><TD width="40">3</TD></TR> <TR><TD>4</TD><TD>4</TD><TD>6</TD></TR> <TR><TD>7</TD><TD>8</TD><TD>9</TD></TR> <TR><TD>=SUM(A3:A5)</TD><TD>=SUM(B3:B5)</TD><TD>=SUM(C3:C5)</TD></TR> </TABLE> Now you can double click on the saved file to load it into Excel and the translation will be done.out. You give to the file the XLS extension and Excel will do the translation for you! With a text editor or from a program.com/javadetails/.io.net/ 6./javadetails/java−0523.IOException.PdfWriter.html A nice OpenSource is http://www. See also this HowTo 6. Export a DataSet to a fixed length or delimited format.FileOutputStream. http://flatpack.lowagie. import com. import java. This trick works with OpenOffice too.io.html While you can use specialized packages to create native Excel file.6.pdf.sourceforge.println("Hello World"). import com. fixed length and custom delimiters.

pdf. new FileOutputStream("HelloWorld.HashMap.getNumberOfPages().put("Author".pdf"). over.lowagie.Element.err.text. PdfContentByte under.jpg"). 30).showTextAligned 6. new FileOutputStream("watermark_pagenumbers. "Bruno Lowagie"). com.println(de.close().text. document.text. com. // watermark under the existing page under = stamp. over.createFont (BaseFont. // adding content to each page int i = 0.getMessage()).pdf.pdf.setAbsolutePosition(200. } document.getInstance(document. moreInfo.setTextMatrix(30. BaseFont.lowagie. document.setMoreInfo(moreInfo). try { PdfWriter.util.76 FlatPack . over.println(ioe. over.text.lowagie.err.lowagie.WINANSI.text.getMessage()).text. PdfContentByte over.text. } } • Add a watermark to an existing document.Image.PdfStamper. com.lowagie.setFontAndSize(bf. while (i < n) { i++. img.BaseFont.lowagie.PdfReader. com. // create a stamper that will copy the document to a new file PdfStamper stamp = new PdfStamper(reader. Image img = Image.setFontAndSize(bf. int n = reader.lowagie.open().Document document = new Document(). stamp.io. } catch (DocumentException de) { System.add(new Paragraph("Hello World")).PdfContentByte.out. import java. over. 400).EMBEDDED). // adding some metadata HashMap moreInfo = new HashMap(). } catch (IOException ioe) { System. BaseFont.PageSize. com.HELVETICA. // text over the existing page over = stamp.getUnderContent(i).FileOutputStream. over.pdf")).addImage(img). try { PdfReader reader = new PdfReader("ChapterSection. 32).println("Add watermarks and pagenumbers").getInstance("watermark.beginText().getOverContent(i). BaseFont bf = BaseFont. under. public class AddWatermarkPageNumbers { public static void main(String[] args) { System.showText("page " + i). import java. com.pdf. 18).pdf")). import import import import import import import com.

length != 2) { System.79 Convert OEM (DOS) file to Ansi (Windows) Current version of this HowTo : http://www. over = stamp.getOverContent(1). "DUPLICATE OF AN EXISTING PDF DOCUMENT". 430./javadetails/java−0524.io. over.insertPage(1. System.println( " note : codepage input Cp850 codepage output Cp1252" ).pdf"). System.com/javadetails/. over. PageSize. 230. 1.exit(1). 0. } // adding an extra page stamp.getUnderContent(1). 3). // closing PdfStamper will generate the new PDF file stamp. 600. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 6. "DUPLICATE".(Element. import java. over.printStackTrace(). 0. // adding a page from another document PdfReader reader2 = new PdfReader("SimpleAnnotations1.addTemplate (stamp.ALIGN_LEFT. consider making a small donation to show your support for this Web site and its content.A4).beginText(). } // input FileInputStream fis = new FileInputStream(args[0]).79 Convert OEM (DOS) file to Ansi (Windows) . 0.setFontAndSize(bf. 30.showTextAligned(Element.ALIGN_LEFT.out. Sybase).getImportedPage(reader2.println( "Usage : java OemToAnsi inputdosfile outputansifile" ). 0). Clipper. } catch (Exception de) { de. mySQL. under.. 45). 1. This can be useful when migrating data from a legacy database (ex.endText(). 0).out. 18). over.rgagnon. BufferedReader r = 6. public class OemToAnsi { public static void main(String args[]) throws Exception{ if (args. } } } If you find this article useful.html We are using an InputStreamReader which convert the specified input encoding to Unicode and an OutputStreamWriter which from Unicode to the specified output encoding.endText(). under = stamp. over.close().*. dBase) to newer DBMS (ex.

} finally { close(in1). 6.html You close them in the finally clause using a special method.read()). // output FileOutputStream fos = new FileOutputStream(args[1]). } } See also this related HowTo If you find this article useful. try { in1 = new BufferedInputStream(new FileInputStream(file1)).read(). Written and compiled by Réal Gagnon ©1998−2006 [ home ] 6. Writer w = new BufferedWriter(new OutputStreamWriter(fos. "Cp850")). in2 = new BufferedInputStream(new FileInputStream(file2)).exit(0).readLine()) != null) { w. while ( (oemString= r. } return false. close(in2). r. } while ( result && i != −1 ). } catch (IOException ex) { ex.printStackTrace().flush(). System. result = (i == in2.close(). File file2) { BufferedInputStream in1 = null.write(oemString). String oemString = "". do { i = in1. boolean result = true. "Cp1252")).80 Close a stream in a try/catch block Current version of this HowTo : http://www.new BufferedReader(new InputStreamReader(fis. consider making a small donation to show your support for this Web site and its content.80 Close a stream in a try/catch block . } w.com/javadetails/. int i.rgagnon.close(). w.. BufferedInputStream in2 = null. } catch (FileNotFoundException ex) { ex./javadetails/java−0539. return result. public static boolean compareFile(File file1.printStackTrace().

81 Rename a file extension Current version of this HowTo : http://www. public Html2Text() {} public void parse(Reader in) throws IOException { 6. if (i > 0 && i < f.swing.82 Remove HTML tags from a file to extract only the TEXT Current version of this HowTo : http://www. int i = f.} private static void close( InputStream is ) { if ( is != null ) { try { is.printStackTrace(). import javax.html.parser.').81 Rename a file extension . } } } 6." + newExtension. } else { target = source.text.*.toLowerCase().rgagnon.substring(i + 1). String currentExtension = getFileExtension(source)./javadetails/java−0424.lastIndexOf('.equals("")){ target = source + "." + currentExtension. String newExtension) { String target. } catch ( IOException ioe ) { ioe.length() − 1) { ext = f.rgagnon.text. if (currentExtension..html.. } return new File(source).*. import javax.renameTo(new File(target)).swing.com/javadetails/.html import java.replaceAll(". } 6. newExtension).io.*.html public static boolean renameFileExtension (String source. } public static String getFileExtension(String f) { String ext = "". } return ext.com/javadetails/.ParserCallback { StringBuffer s./javadetails/java−0541. public class Html2Text extends HTMLEditorKit.close().

activation. Html2Text parser = new Html2Text(). Mime types supported are defined in a ressource file inside the activation.com/products/javabeans/glasgow/jaf.1 Using javax. class GetMimeType { public static void main(String args[]) { File f = new File("gumby.io.rgagnon.append(text). Written and compiled by Réal Gagnon ©1998−2007 [ home ] 6..com/javadetails/. it can be downloaded from http://java.html.out. in.sun.TRUE).out.83. } } } If you find this article useful.MimetypesFileTypeMap activation.MimetypesFileTypeMap.println(parser.jar is required.gif is image/gif" } 6. } public static void main (String[] args) { try { // the HTML to convert FileReader in = new FileReader("java−new.toString().jar. parser. } catch (Exception e) { e.gif").parse(in. ParserDelegator delegator = new ParserDelegator().println("Mime Type of " + f.getText()). this.83 Get the Mime Type from a File Current version of this HowTo : http://www.activation. Boolean.printStackTrace().83 Get the Mime Type from a File . System.html 6. // expected output : // "Mime Type of gumby. The MimetypesFileMap class is used to map a File to a Mime Type.getContentType(f)). } public String getText() { return s. // the third parameter is TRUE to ignore charset directive delegator.parse(in).html")./javadetails/java−0487.getName() + " is " + new MimetypesFileTypeMap().s = new StringBuffer(). int pos) { s. } public void handleText(char[] text. import java. consider making a small donation to show your support for this Web site and its content.close(). System. import javax.File.

// output : text/plain } } 6. 6.default (usually found only in the activation. The result is very fast because only the extension is used to guess the nature of a given file.TXT")). type = uc. it searches MIME types files in the following order: 1. The file <java.2 Using java. Programmatically added entries to the MimetypesFileTypeMap instance.URL .URL Warning : this method is very slow!. } public static void main(String args[]) throws Exception { System. 5.} The built−in mime−type list is very limited but a mechanism is available to add very easily more Mime Types/extensions.types in the user's home directory. When requests are made to search for MIME types in the MimetypesFileTypeMap.mime.getMimeType("file://c:/temp/test. URL u = new URL(fileUrl).println(FileUtils. A more robust solution is possible with the JMimeMagic library.jar file).2 Using java. URLConnection uc = null.83.types. The file or resources named META−INF/mime.83.net.*. The MimetypesFileTypeMap looks in various places in the user's system for MIME types file entries. 6.home>/lib/mime. MalformedURLException { String type = null.3 Using JMimeMagic Checking the file extension is not a very strong way to determine the file type. 3. JMimeMagic is a Java library (LGLP licence) that retrieves file and stream mime types by checking magic headers.openConnection().out.net. // snippet for JMimeMagic lib // http://sourceforge. This method is interesting when you need to deal with incoming files with the filenames normalized.properties import java. The file or resource named META−INF/mimetypes.getContentType(). return type. 2.net/projects/jmimemagic/ Magic parser = new Magic() . The file . The mapping between the extension and the mime−type is defined in the file [jre_home]\lib\content−types.io.net. 4.types.IOException. uc = u. public class FileUtils{ public static String getMimeType(String fileUrl) throws java.83. Like the above method a match is done with the extension.

net/wiki/index.5 Using Droid DROID (Digital Record Object Identification) is a software tool to perform automated batch identification of file formats. a Java Swing GUI or a command line interface.getMagicMimeType(file). mail boxes • MIME type identification • Full−text and metadata extraction of various file formats • Opening of crawled resources For each of these parts.83.. This tool can detect using the file extension or the magic header technique. .net/Overview 6.net/projects/mime−util public static final String UNKNOWN_MIME_TYPE="application/x−unknown−mime−type".83.gif")).83. The nice thing about mime−util is that there is no dependency (with others Apache packages) so it is very lightweight. and DROID can be configured to automatically download updated signature files from the PRONOM website via web services.. websites.4 Using mime−util Another tool is mime−util.6 Aperture framework Aperture is an open source library and framework for crawling and indexing information sources such as file systems. New and updated signatures are regularly added to PRONOM. DROID uses internal and external signatures to identify and report the specific file format versions of digital files.getMagicMatch(new File("gumby.println(match. http://aperture.wiki.sourceforge. Thanks to Jean−Marc Autexier and sygsix for the tip! 6.// getMagicMatch accepts Files or byte[].php/Introduction 6. String mimeType = MimeUtil. // which is nice if you want to test streams MagicMatch match = parser. The Aperture code consists of a number of related but independently usable parts: • Crawling of information sources: file systems.4 Using mime−util . 6. // snippet for mime−util lib // http://sourceforge.sourceforge.out. websites and mail boxes. These signatures are stored in an XML signature file.83. generated from information recorded in the PRONOM technical registry.getMimeType()) . http://droid. a set of APIs has been developed and a number of implementations is provided. System. if(mimeType == null) mimeType = UNKNOWN_MIME_TYPE. It can be invoked from two interfaces.

import java.'/')).read(b)) != −1) { zout. print(e).zip.println(" (deflated 0%)").putNextEntry(e).*. } } else { err.println(" (stored 0%)"). if (size > 0) { long csize = e.closeEntry().zip ** */ import java.len). java Zip file. rename the old ZIP to a temporary filename. for(int i = 0. while((len=in.util. if (e.*. ZipEntry e = new ZipEntry(args[i].DEFLATED) { long size = e. } zout. class Zip { public static void main(String args[]) throws IOException { byte b[] = new byte[512].replace(File.out).separatorChar. ZipOutputStream zout = new ZipOutputStream(System. create the new ZIP.close(). To do so. } else { err. i < args. zout.getSize(). Expand the contents of the old ZIP../javadetails/java−0065. } zout. err.2 > file.print("added " + e.0. long ratio = ((size−csize)*100) / size. } } } NOTE: There no way to directly add or modify an entry to a ZIP file after its creation. 6.html /* ** a simple ZIP tool ** ** ex.write(b.6.err. int len=0.84 Create a compressed (ZIP) file .io.84 Create a compressed (ZIP) file Current version of this HowTo : http://www. i ++) { InputStream in = new FileInputStream(args[i]).1 file.println(" (deflated " + ratio + "%)").com/javadetails/. err. } public static void print(ZipEntry e){ PrintStream err = System.getMethod() == ZipEntry.length.rgagnon.getName()).getCompressedSize(). add the original contents plus the new files and delete the old ZIP when done.

getMethod() == ZipEntry. } err.DEFLATED) { err. } } hh:mm:ss").util. } zin.err. System. class ViewZip { public static void main(String args[]) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(args[0])). if (e. import java.text. } } else { err.zip ** */ import java.mm.print(ratio + "% "). import java.err.com/javadetails/. System.err.dd Date d = new Date(e. ZipInputStream zin = new ZipInputStream(in). ZipEntry e.getSize().print(e.println("−−−−\t −−−− −−−− −−−−−− −−−−− −−−−").format(d) + " ").print(" 0% ").io. DateFormat df = new SimpleDateFormat ("yyyy.println(" (stored 0 %"). err..rgagnon. print(e).*./javadetails/java−0066.getSize() + "\t").85 Display compressed (ZIP) file content . } err. long size = e.*. err.*.util.85 Display compressed (ZIP) file content Current version of this HowTo : http://www.close(). if (size > 0) { long csize = e.*.print("deflated ").print(df.getName()). long ratio = ((size−csize)*100) / size. import java.html /* ** a simple viewZIP tool ** ** ex. } public static void print(ZipEntry e) { PrintStream err = System. if (ratio < 10) { err. while((e=zin.zip.println("Size\t Date Time Method Ratio Name"). } else { err.getTime()). java ViewZip file.closeEntry().6.getCompressedSize(). 6.getNextEntry())!= null) { zin.println(e.write(' ').

zip.. } } unzip(zin. • Use an AU audio file For Java. ZipEntry e.util.86 Expand the compressed (ZIP) file .read(b))!= −1 ) { out.*.println("unzipping " + s). args[1]).*.length > 1) { if (e.io.zip class UnZip { public static void main(String args[]) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(args[0])).com/javadetails/. ZipInputStream zin = new ZipInputStream(in).text.getNextEntry())!= null) { if (args. while((e=zin.com/javadetails/. Any sample rate beyound that will not work. java UnZip file.rgagnon.. FileOutputStream out = new FileOutputStream(s).86 Expand the compressed (ZIP) file Current version of this HowTo : http://www.close().out.len). import java. } public static void unzip(ZipInputStream zin.util. import java.0.equals(args[1])) { unzip(zin. break.html There are three ways to emit a beep in Java. 6.87 Emit a beep Current version of this HowTo : http://www.*.rgagnon. } } 6./javadetails/java−0067.getName(). AU files need to be created at a sample rate of 8000. String s) throws IOException { System.close()./javadetails/java−0001. while ( (len=zin. to unzip file 1 from file.6.zip ** */ import java. int len = 0.write(b.zip file1 ** java UnZip file. } zin. See also this How−to.*. e.html /* ** a simple unZIP tool ** ** ex. import java.getName()). byte [] b = new byte[512].zip to unzip file. } out.

rgagnon. • Starting with JDK 1. System.getSourceDataLine(af). i++) { double angle = i / (SAMPLE_RATE / hz) * 2.• Print the ASCII Bell character to the console public class TestBeep { public static main(String args[]) { // ASCII bell System.awt.flush(). } } (Windows) The sound used is determined from the setting found in Control Panel/Sounds and Devices/Sounds/Sound Scheme/"Default Beep".sound. public class Beep { public static void main(String args[]) { Toolkit.true. for (int i=0.sound(1000.88 Emit a Tone Current version of this HowTo : http://www.sin(angle) * 110.println(lue). SourceDataLine sdl = AudioSystem. use the beep method in the Toolkit import java. sdl. } catch (LineUnavailableException lue) { System.88 Emit a Tone .100). } sdl.sampled.0 * Math. Tone.sound(5000.0)..3 public class Tone { public static float SAMPLE_RATE = 8000f.1000)./javadetails/java−0499.0.*. public static void sound(int hz. } public static void main(String[] args) { try { Tone. i<msecs*8.false).html import javax.getDefaultToolkit().8.print("\007").write(buf.1.stop(). If no sound file is selected then the beep() will be a silence.*.out.out.out.beep(). sdl. } } The buzzer on the motherboard is used.100).sound(100.drain(). int msecs) throws LineUnavailableException { byte[] buf = new byte[1].1). sdl.PI.start(). 6. Tone.close().1.open(af). } 6.com/javadetails/. AudioFormat af = new AudioFormat(SAMPLE_RATE. //jdk1. buf[0] = (byte)(Math. sdl. sdl.

consider making a small donation to show your support for this Web site and its content.sleep(5000). try{ AudioStream as = new AudioStream(new FileInputStream("aSound.audio. import java. .io. } } Since JDK1.sun. AudioPlayer.html With Applet.printStackTrace()./javadetails/java−0006.. So it may be possible to use it without an Applet (i.getResourceAsStream(args[0])..com/javadetails/.com/docs/books/tutorial/sound/playing.player. } To play a sound from a JAR file (the . in a regular Java application) with java.start(as). Java can play WAV directly..*.2.89 Play an audio file from an application Current version of this HowTo : http://www.au")).3. Another way is to use the undocumented sun.sound package.class. Note: Since JDK1.Applet.html. import sun.applet.*.AU file in the JAR must be accessible via the CLASSPATH of course!) : import java.getAudioClip(URLofMySound). .e.*. Thread. see http://java. public class AppAudio { public static void main(String args[]) throws Throwable { InputStream in = AppAudio.audio package. see this HowTo. you have also the javax.start(as).. the getAudioClip method() from the Applet package is used to play sound file. import sun. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 6. AudioStream as = new AudioStream(in).2.} } If you find this article useful.*. Starting with JDK1.89 Play an audio file from an application . } catch(IOException err){ err. AudioPlayer p=AudioPlayer.audio. 6. getAudioClip() is now a static method.net.rgagnon. p.player..

Written and compiled Réal Gagnon ©2007 real@rgagnon.rgagnon.89 Play an audio file from an application .com 6.com http://www.

*. stmt. you can't use it with JAVA Applet because ODBC requires some DLL on the client machine (forbidden for security reason). import java.getString("objet")). } rs. } finally { try { if (theConn != null) theConn.executeQuery(sql).out.html You have to keep in mind that the bridge JDBC−ODBC is only useful in an Application.2 Connect to a database via JDBC−ODBC Current version of this HowTo : http://www.close(). class JDBCapp { static Connection theConn.net.7 JDBC 7. while (rs.sql. rs = stmt. Statement stmt. public static void main (String args[]) { try { // connection to an ACCESS MDB theConn = MyConnection.createStatement(). import java.getConnection().rgagnon.close().com/javadetails/. stmt = theConn.close().URL.printStackTrace().next()) { System. } catch (Exception e) { e. } catch (Exception e) { } } } } class MyConnection { public static Connection getConnection() throws Exception { Driver d = (Driver)Class.1 java−jdbc 7. String sql.forName 7 JDBC .println(rs. ResultSet rs. sql = "select objet from Email"./javadetails/java−0107..

getText().setString(1. ResultSet rs.next().DBQ=c:/tech97. stmt = theConn.newInstance().rgagnon.close().mdb)}. if (found) System. prepstmt = theConn. /* To use an already defined ODBC Datasource : String URL = "jdbc:odbc:myDSN". "pwd").out. return c.executeQuery(). ResultSet rs. String sql.out.println("Customer " + id + " not found!"). "user". else System.getConnection( "jdbc:odbc:Driver={Microsoft Access Driver (*.prepareStatement ("select custName. rs = prepstmt.com/javadetails/.println(rs. boolean found = false.executeQuery().html Note:the MyConnection class was used to connect to the DB With a Prepared Statement (only 1 row) String id = cust_id.getString(1)).3 SELECT data from a table Current version of this HowTo : http://www.("sun. sql = "select custName from tCust where custName = " += "'" + name + "'". rs = stmt.getText(). found = rs. } With a Statement (many rows) String name = cust_name.getConnection(URL. Connection c = DriverManager. try { PreparedStatement prepstmt. CustAddr from tCust where custId = ?").mdb" ).odbc.printStackTrace(). 7./javadetails/java−0108. prepstmt. */ } } 7.jdbc. Connection c = DriverManager. id).3 SELECT data from a table . } catch (Exception e) { e..JdbcOdbcDriver").createStatement(). prepstmt. try { Statement stmt.

charAt(i)).close(). i < source. String sql.printStackTrace(). Before inserting data containing quotes. i++){ sb.close(). for(int i = 0. Even.out. 7. int rows. stmt = theConn.charAt(i)=='\'') sb. Thanks to Lawrence Angrave for the warning.executeUpdate(sql). This is especially when you in a Web application environnement.println(rs. } catch (Exception e) { e. rows = stmt. sql = + + + + + "INSERT INTO tCust " "(custId.rgagnon.html Note:the MyConnection class was used to connect to the DB Statement stmt.while (rs. then it is generally considered bad practice when prepared statements solve this problem more cleanly. String concatentation of this form can only be used if you first validate the fields to include only alphanumeric characters. Even..toString().4 INSERT data into a table Current version of this HowTo : http://www. String concatentation of this form can only be used if you first validate the fields to include only alphanumeric characters.commit(). } You need to be aware to the snippet above contains a SQL Injection vulnerability. stmt. then it is generally considered bad practice when prepared statements solve this problem more cleanly.append(source.com/javadetails/.createStatement().4 INSERT data into a table . } rs. theConn.length(). 7. custName. stmt. This is especially when you in a Web application environnement.close().next()) { System. custAddr) " "VALUES " "('" + custId + "'. You need to be aware to the snippet above contains a SQL Injection vulnerability.append('\'') } return sb.getString("custName"))." "('" + custAddr + "')". Thanks to Lawrence Angrave for the warning. public static String convertString(String source) { StringBuffer sb = new StringBuffer(). you may need to double them (so "Real's HowTo" −> "Real''s HowTo"). if(source.dbConn." "('" + custName + "'. You can use the following function to "prepare" your string./javadetails/java−0109.

5 MODIFY data in a table .commit().rgagnon. prepstmt. "Name with \" are permitted!").5 MODIFY data in a table Current version of this HowTo : http://www.out.printStackTrace(). try { sql = "INSERT INTO tCust" + "(custName) " + "VALUES " + "(?)". String sql./javadetails/java−0110.com/javadetails/.prepareStatement ("UPDATE tCust SET custName = ? "+ " WHERE custId = ?"). } catch (Exception e){ e. stmt = theConn. theConn. try { prepstmt = theConn. prepstmt. } catch (Exception e) { e.commit(). } The character "\" can be difficult to use in an INSERT statement since "\" is considered as an escape character in Java (and probably by the database also). System.. cust_id.executeUpdate().html Note:the MyConnection class was used to connect to the DB PreparedStatement prepstmt.printStackTrace(). stmt. theConn.setString(1.executeUpdate("INSERT INTO mytable VALUES('\\\\')").close()."Smith"). rows = stmt.executeUpdate("INSERT INTO mytable VALUES('\\')").setString(2. At the end.} Or you can use a PreparedStatement to insert data containing QUOTES PreparedStatement stmt = null. stmt. 7. may generate a SQL Exception even if the "\" is escaped for Java because you need to escape it again for the database.setString(1.close(). } 7. stmt. int rows.getText()). prepstmt. stmt. you need to use "\\\\" to INSERT a simple "\". prepstmt.executeUpdate().prepareStatement(sql).println(sql).

println("Record found").7 Test for an empty ResultSet Current version of this HowTo : http://www.7. prepstmt.commit().com/javadetails/.next()) { do { System.out. try { prepstmt = theConn. } catch (Exception e) { e.println("Record found").. } 7. } else { System.setString(1. prepstmt.html boolean found./javadetails/java−0116. } while (rs.cust_id. .close().next(). else System.out. A nicer way to do the same would be ResultSet rs.println("RECORD NOT FOUND").getText())..out. if (found) System. theConn. ResultSet rs. } 7.6 DELETE data in a table Current version of this HowTo : http://www. // execute the query and then found = rs..println("Record not found").prepareStatement ("DELETE FROM tCust "+ " WHERE custId = ?").6 DELETE data in a table .html Note:the MyConnection class was used to connect to the DB PreparedStatement prepstmt.printStackTrace().rgagnon.next())... if (rs.com/javadetails/. .rgagnon.out. prepstmt.executeUpdate()../javadetails/java−0111.

dbConn.selectFromEmp(). with only one field called "emp" and "long binary" or "blob" as data type.prepareStatement ("INSERT INTO EMPLOYEE (emp) VALUES(?)"). oos.bais.*.dbConn.executeQuery("SELECT emp FROM Employe"). "password")./javadetails/java−0117.writeObject(employee).insertIntoEmp().createStatement(). "username".io.sql. import java.8 Store and retrieve an object from a table . } public void insertIntoEmp() { Employee employee = new Employee(42. theConn. pstmt. something like emp_id.printStackTrace().connectToDB(). employeeAsBytes. j.7. try { ByteArrayOutputStream baos = new ByteArrayOutputStream(). import java.length). ResultSet rs = stmt.setBinaryStream(1.executeUpdate(). } } public void selectFromEmp() { boolean found. theConn. j. j. // loop through the result set while (rs. ByteArrayInputStream bais = new ByteArrayInputStream(employeeAsBytes). We want to insert an instance of the class "Employee" into the table "Employee". // bind our byte array to the emp column pstmt. PreparedStatement pstmt = theConn. 98000).next()) { 7. } public void connectToDB() { theConn = new MyConnection(). The object "Employee" will be serialized into the table "Employee" ( ideally the table "Employee" should have an index key. } catch(Exception e) { e.close(). // serialize the employee object into a byte array byte[] employeeAsBytes = baos.net.dbConn.rgagnon. pstmt. but for the example there is none)..html Assume that we have a table called "Employee".8 Store and retrieve an object from a table Current version of this HowTo : http://www. import java."Real Gagnon".commit().URL. try { Statement stmt = theConn.toByteArray(). class JDBCapp { static MyConnection theConn.*.connect("your_db_profile".com/javadetails/. public static void main (String args[]) { JDBCapp j = new JDBCapp(). ObjectOutputStream oos = new ObjectOutputStream(baos).

public Employee(int ID.out.8 Store and retrieve an object from a table . } catch (Exception e) { e.newInstance(). } } void disconnect() { try { dbConn. // byte[] st = aBlob.getBytes(1). (int) aBlob.JdbcOdbcDriver"). ByteArrayInputStream baip = new ByteArrayInputStream(st).salary = salary.printStackTrace(). // display the result for demonstration System.// fetch the serialized object to a byte array byte[] st = (byte[])rs.println(emp.name).close().name = name. this. String URL = "jdbc:odbc:" + db.readObject(). double salary) { this.getBytes(0. // or Blob aBlob = rs. rs.odbc. ObjectInputStream ois = new ObjectInputStream(baip). // re−create the object Employee emp = (Employee)ois.getBlob(1). this. double salary. String passw) { try { Driver d = (Driver)Class. String user. user. String name.printStackTrace(). passw). } } } class Employee implements Serializable { int ID. void connect(String db. // or byte[] st = rs.printStackTrace().jdbc.getObject(1). } stmt. } catch (Exception e) { e.getConnection(URL. } } class MyConnection { Connection dbConn = null. dbConn = DriverManager.length()).forName ("sun.close(). String name. } } } 7.ID = ID. } catch(Exception e) { e.close().

html File file = new File("myimage. import java.sql.prepareStatement("insert into images values (?. InputStream stream = rset.com/javadetails/.setString(1.(int)file. ps.com/javadetails/.write((char)a1).html Oracle Corporation has released a free 100% JAVA driver.close(). } myImage = Toolkit. ps.forName("oracle.html // column is column index in ResultSet containing the image. 7.10 Insert an Image Current version of this HowTo : http://www.*.rgagnon..fis.toByteArray()). } catch(Exception e){} 7. All you need is to include the required jar in the classpath.gif")..?)").. PreparedStatement ps = conn.rgagnon.setBinaryStream(2. // // or 7. SQLException { Class.rgagnon.com/javadetails/.createImage(output.OracleDriver").length()). fis./javadetails/java−0119.driver.executeUpdate().jdbc. ps. try { int a1 = stream. // we assume that the type is LONGVARBINARY Image myImage = null.getName())./javadetails/java−0118.read().read().file.close().9 Retrieve an Image .close(). It is available at their Web site. ps. while (a1 >= 0) { output.9 Retrieve an Image Current version of this HowTo : http://www. FileInputStream fis = new FileInputStream(file)./javadetails/java−0112. public class TestDBOracle { public static void main(String[] args) throws ClassNotFoundException.11 Connect to an Oracle database with JDBC Current version of this HowTo : http://www.getDefaultToolkit().getBinaryStream(column). output. ByteArrayOutputStream output = new ByteArrayOutputStream().7. a1 = stream.

wrapped in a logical connection.createStatement()."scott". An application turns the implicit connection cache on by invoking OracleDataSource. it's all built in the OracleDataSource with the implicit connection cache mechanism. a logical connection is returned wrapping the physical connection.println (rset. If a match is found.// DriverManager. If no physical connection match is found.setAutoCommit(false). 7.registerDriver // (new oracle.2) makes it very easy to use a connection pool. // jdbc:oracle:thin:@//host:port/service // or // String url = "jdbc:oracle:thin:@server.. Various parameters such as number of minimum connections.12 Connect to Oracle using a connection pool Current version of this HowTo : http://www. } stmt.12 Connect to Oracle using a connection pool . First a static class to manage the connection pool. the first connection request to the OracleDataSource transparently creates a connection cache. a new physical connection is created. A Connection Pool is a cache of database connections maintained in memory so that the connections can be reused when the database receives future requests for data. Statement stmt = conn.close().getConnection(url. } } See also this HowTo to connect using the Oracle Connection Pool.local:1521/prod". // jdbc:oracle:thin:@host:port:SID Connection conn = DriverManager. After you have turned connection caching on. 7. maximum connections and idle connections can be set to make sure the connection pool works well according to the environment it is deployed to work in.println ("Ok. "tiger"). whenever you retrieve a connection through an OracleDataSource.The getConnection() method checks if there are any free physical connections in the cache that match the specified criteria. the JDBC drivers check to see if a connection is available in the cache.driver. Each thread makes a connection but the login process is done only once. System.getConnection().out."). In this example.OracleDriver()).getString(1)).local:1521:prodsid".html The Oracle thin jdbc driver (v9. Connection pools are used to enhance the performance of executing commands on a database. and returned. ResultSet rset = stmt.jdbc.com/javadetails/.setConnectionCachingEnabled(true).next()) { System.executeQuery("select BANNER from SYS. we have a program with several threads.out. conn./javadetails/java−0545. while (rset. String url = "jdbc:oracle:thin:@//server. After implicit caching is turned on.rgagnon.V_$VERSION").

} } public static void listCacheInfos() throws SQLException{ OracleConnectionCacheManager occm = 7. import java.setProperty("MaxLimit".sql. "1").jdbc. } public static void closePooledConnections() throws SQLException{ if (ods != null ) { ods. ods. ods.pool.setPassword("tiger"). "true").setConnectionCachingEnabled(true).OracleDataSource. } } /** * private constructor for static class */ private JDBCUtils() { } public static Connection getConnection() throws SQLException { return getConnection("env. cacheProps.close(). ods. } public static Connection getConnection(String env) throws SQLException { System.setProperty("MinLimit". ods.local:1521/prod").setConnectionCacheProperties(cacheProps). try { ods = new OracleDataSource(). } catch (SQLException e) { e. cacheProps. import java.setURL("jdbc:oracle:thin:@//server.printStackTrace().*. "5"). ods.setUser("scott").setProperty("InitialLimit".jdbc.OracleConnectionCacheManager.setProperty("ValidateConnection". } return ods. import oracle."). unspecified").12 Connect to Oracle using a connection pool .setProperty("ConnectionWaitTimeout". public class JDBCUtils { private final static String CACHE_NAME = "MYCACHE".info("Initialisation du OracleDataSource").out. "1").util.pool. // caching parms ods.getConnection(). cacheProps. static { logger. Properties cacheProps = new Properties(). cacheProps.println("Request connection for " + env). private static OracleDataSource ods = null. "4").setConnectionCacheName(CACHE_NAME). cacheProps.Properties.import oracle. if (ods == null) { throw new SQLException("OracleDataSource is null.

} } then the working thread import java.URL. } catch (SQLException e) { e. stmt.V_$VERSION"). conn.*. JDBCUtils.close().sql.getConnectionCacheManagerInstance().net. ResultSet rset = stmt.12 Connect to Oracle using a connection pool .println (occm.setAutoCommit(false). conn.close().getNumberOfActiveConnections(CACHE_NAME) + " connections are active"). System.createStatement().next()) System.sleep(1000). " + noThread).out. Statement stmt = conn. System. while (rset.getConnection("env " + noThread). } public void run() { System.out.OracleConnectionCacheManager.getNumberOfAvailableConnections(CACHE_NAME) + " connections are available in cache " + CACHE_NAME).println ("Sleep.println ("Ok. } catch(Exception e) { } } } } } and finally. while (true) { try { Connection conn = JDBCUtils. import java.listCacheInfos(). 7.out.getString(1)).println (occm.println("Starting Thread " + noThread). public class TestDBOraclePool3Thread implements Runnable { private int noThread = 0.").*..executeQuery("select BANNER from SYS.sql. try { Thread.out.out. the main class import java.out.printStatckTrace() } finally { System.. TestDBOraclePool3Thread(int n) { noThread = n. System.println (rset.

start().Timestamp(today. new Thread( new TestDBOraclePool3Thread(6)).f ..14 Handle dates Current version of this HowTo : http://www.sql.Date sqlToday = new java.sql.start().start(). . new Thread( new TestDBOraclePool3Thread(3)). 7. java.util./javadetails/java−0113.Timestamp now = new java. you can use JDBC escape codes.13 Get JDBC driver for major database vendors .start().sql.html JDBC vendors list Intersolv plugin to access ODBC database through a browser 7.util.getTime()). new Thread( new TestDBOraclePool3Thread(7))./javadetails/java−0114. } } 7.f .rgagnon.util..Date today = new java.Date today = new java. java. . java.util.Date(today. new Thread( new TestDBOraclePool3Thread(2)).start().public class TestDBOraclePool3 { public static void main(String[] args) throws SQLException { new Thread( new TestDBOraclePool3Thread(1)).com/javadetails/.util.. Time or Timestamp in a query.Date(today.com/javadetails/. Date {d 'yyyy−mm−dd'} Time {t {'hh:mm:ss'} Timestamp {ts `yyyy−mm−dd hh:mm:ss. java.. a Statement with a Date will look like this java.Date().rgagnon.sql.Date today = new java.start().Date().html To get the current date in SQL format. new Thread( new TestDBOraclePool3Thread(5)).Date sqlToday = new java.sql.getTime()).Date(). it's the same idea java. For Timestamp.util. new Thread( new TestDBOraclePool3Thread(4)). is optional For example.sql.start().getTime()).13 Get JDBC driver for major database vendors Current version of this HowTo : http://www. To use a Date..'} note: the .

cs. or p. To INSERT PreparedStatement p = theConn.setDate(1.Date(today.15 Call a stored procedure Current version of this HowTo : http://www. // #2 is cs.Date instance must be 'normalized' by setting the hours. sqlToday). Types. p. java. ResultSet rs = p./javadetails/java−0115..registerOutParameter(2.?).setString(1.sql. p. Types.sql.toString() + "' }").theProcedure(?.executeUpdate().util. 1). seconds. the millisecond values wrapped by a java.prepareStatement ("insert into TableWithADateColumn values(?)").?.getTime()). java. PreparedStatement p = theConn.sql. the JDBC driver will do the job for you.executeUpdate ("insert into TableWithADateColumn values( { d '1999−12−31' } )").util.executeQuery().html We assume that the Connection is known as : Connection conn. INPUT INPUT OUTPUT OUTPUT // get the result from OUTPUT #2 7.Date sqlToday = new java.Date(). // #1 is cs.registerOutParameter(3. One thing to remember when using java.Date today = new java. "string parameter").setDate(1.rgagnon.String query = "select * from cust where purchase_date <{ d '" + sqlDate. // #3 is cs.prepareCall(query).".INTEGER). minutes. int output_parm2 = cs. and milliseconds to zero in the particular time zone with which the instance is associated. then String query = "begin thePackage. sqlToday).date is (according to the javadoc) : To conform with the definition of SQL DATE.getInt(2). 7.15 Call a stored procedure .INTEGER). With a PreparedStatement.sql.prepareStatement ("select * from cust where purchase_date <?"). end. you don't need JDBC escape codes. CallableStatement cs = conn.setInt(2.com/javadetails/. p.execute(). // and cs.

rgagnon. // get the result from OUTPUT #3 7.?.out.executeQuery(). public static int storedProcWithResultSet (String parms) throws Exception // Stored procedure to be called.com/javadetails/. cs. cs. int i = 0.?.CHAR). 0)..html Thanks to T.Types.getMetaData(). if ( rs == null) System. java.println( vResSet.registerOutParameter(5.getString(j).p_astoreproc (?.getColumnCount(). Vector vResSet = new Vector().println( "Record " + (i+1)).sql. int j = 1. java.println( "No resultSet!"). } } // Retrieving Strored Procedure OUTPUT parameters System.toString()). } i++.prepareCall ("{? = call mypackage.addElement(rs.setString(4.Types. // register input parameters cs.int output_parm3 = cs. j <= nbCol .elementAt(k).?. j++){ vResSet.registerOutParameter(7. else System.sql.setString(2.16 Stored procedure with Input/Output parms and a ResultSet . java.out. CallableStatement cs = conn.?. vResSet.out.getInt(3).setString(3.out.Types.insertElementAt(rs.registerOutParameter(6.getString(j)). ""). while (rs. parms).next ()) { System.?)}"). cs.?.CHAR).elementAt(k) != null) System. // putting the ResultSet columns in a vector for ( j = 1. int nbCol = rsmd.println( "return code of Stored procedure = : " 7.16 Stored procedure with Input/Output parms and a ResultSet Current version of this HowTo : http://www. // Procedure execution ResultSet rs = cs. "").sql. ResultSetMetaData rsmd = rs.CHAR).out. // regsiter ouput parameters cs. else { // To retrieve columns info./javadetails/java−0120. } // Reading vector to print ResultSet data for ( int k = 0 . // Note that you need to retrieve the ResultSet _before_ retrieving // OUTPUT parameters. cs. k++ ) { if ( vResSet. Guirado for the tips.println( "Column " + (k+1) + " Null"). k < nbColonnes .

close() .18 Get a record count with the SQL Statement Current version of this HowTo : http://www.next(). ResultSet. r. 7. 7.getModel().0 provides a way to retrieve a rowcount from a ResultSet without having to scan through all the rows or issue a separate SELECT COUNT(*).println( "parameter " + i + " : " + cs.html // TableModel definition String[] tableColumnsName = {"col 1".rgagnon.rgagnon.CONCUR_READ_ONLY).html Some JDBC driver have limit about how big returned records can be. count = r. r.17 Fix incomplete field returned by the ResultSet .getInt("rowcount") .19 Transfer a ResultSet to a JTable Current version of this HowTo : http://www. DefaultTableModel aModel = (DefaultTableModel) aTable. i <= 7. } 7.getString(i)). return cs.createStatement(). Then getMaxFieldSize() and setMaxFieldSize() from the Statement class to adjust if necessary the current maximum value. r."col 3"}. JDBC 2."col 2".getRow()..executeQuery("SELECT * FROM employee WHERE id_emp LIKE '1%'")./javadetails/java−0121.createStatement( ResultSet.last(). r.com/javadetails/./javadetails/java−0309.TYPE_SCROLL_INSENSITIVE.rgagnon.com/javadetails/.getInt(1).out. int ResultCount = r.getInt(1)).. First use the getMaxRowSize() and doesMaxRowSizeIncludeBlobs() from the DatabaseMetaData class to see what the maximum supported by the driver./javadetails/java−0292.+ cs. 7.executeQuery("SELECT COUNT(*) AS rowcount FROM MyTable"). i ++) System. ResultSet r = s.17 Fix incomplete field returned by the ResultSet Current version of this HowTo : http://www.com/javadetails/.beforeFirst().html Statement s = con. ResultSet r = s. Statement s = conn.. // Retrieving OUTPUT parameters for ( int i = 5 .

getColumnCount(). } catch (Exception e) { e. 7.aModel.getSchemas(). while(rs2.next()) tblnames += rs2.dbConn. int colNo = rsmd.col2. try { ResultSet rs1. } public void doit() { theConn = new MyConnection(). // the query ResultSet rs = statement. // tanks to umit ozkan for the bug fix! for(int i=0.doit(). public static void main (String args[]) { new JDBCapp().sql.null).println(tblnames). } aModel.com/javadetails/. rs2 = dmd.next()) { ss = rs1.next()){ Object[] objects = new Object[colNo]. String ss.println("Tables :"). while(rs1.. } aTable.out. tblnames = "". } } } class MyConnection { Connection dbConn = null.ResultSetMetaData rsmd = rs. System.executeQuery("select col1. } System. DatabaseMetaData dmd = theConn.connect("myDSN". theConn.getString(1)./javadetails/java−0317. ResultSet rs2.printStackTrace(). // Loop through the ResultSet and transfer in the Model java. while(rs.net.out. "password").getString(3) + " " + rs2.rgagnon.ss.html import java. import java.20 List tables in a database .getString(4) + "\n\r".getObject(i+1).setModel(aModel).getMetaData(). String user.getMetaData().sql.i<colNo.URL. rs1 = dmd.i++){ objects[i]=rs. String passw) { try { 7. class JDBCapp { static MyConnection theConn.addRow(objects).*.getTables(null.setColumnIdentifiers(tableColumnsName).20 List tables in a database Current version of this HowTo : http://www. "%".col3 from mytable"). void connect(String db. "user".

ResultSetMetaData rsmd = rs.sql. int columnCount = rsmd.next()) { rowCount++.println("<TH>" + rsmd.println("<TD>" + rs.getMetaData().getConnection(URL.jdbc.JdbcOdbcDriver").println("<TR>").. } catch (Exception e) { e. for (int i = 0.close(). for (int i = 0.io. java.21 Display ResultSet data in an HTML Table in Servlet .odbc. i++) { out. } out.printStackTrace(). out. return rowCount. // table header out. // the data while (rs.PrintWriter out) throws Exception { int rowCount = 0. } out. i++) { out.com/javadetails/. } catch (Exception e) { e. user. i < columnCount. out.getString(i + 1) + "</TD>")./javadetails/java−0378.println("<TR>"). } } void disconnect() { try { dbConn.println("<P ALIGN='center'><TABLE BORDER=1>").println("</TR>").println("</TR>").html private int dumpData(java. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 7.forName ("sun.ResultSet rs. // URL corresponding to the ODBC DSN String URL = "jdbc:odbc:" + db.newInstance(). i < columnCount. } out.rgagnon. } } } If you find this article useful.println("</TABLE></P>").Driver d = (Driver)Class.printStackTrace().21 Display ResultSet data in an HTML Table in Servlet Current version of this HowTo : http://www.getColumnLabel(i + 1) + "</TH>").getColumnCount(). consider making a small donation to show your support for this Web site and its content. // DB logon dbConn = DriverManager. passw). } 7.

Class Subclass 01 000 01 01 01 01 01 01 002 003 004 005 006 007 Success with warning Disconnect error−transaction rolled back Null value eliminated in set function String data.println ("SQLState: " + w.out. System. Warnings are silently chained to the object whose method caused it to be reported".println ("Message: " + w. Note that SQLException can be chained. but encounters a warning condition.println ("").println ("VendorCode: " + w. dbConn = DriverManager. it sets the SQLSTATE class field to "01".rgagnon. Depending on the vendor driver. This warning can be an ANSI or X/Open warning message (if supported by the driver) the subclass code in the range "000" to "006".println ("\n *** SQL Warning ***\n")."password"). } } } Error When an error occurs. informations (not only Warnings) can be found in the SQLWarning object. the warning messages are displayed.getConnection ("jdbc:odbc:YourDatabaseName".getSQLState ()).getWarnings().22 Detect SQL errors or warnings Current version of this HowTo : http://www. SQLWarning w = dbConn. a SQLException is thrown. w = w.getNextWarning ().out.out. right truncation Insufficient item descriptor areas Privilege not revoked PRIVILEGE NOT GRANTED The JDK API doc reveals that "The SQLWarning class provides information on a database access warnings.getMessage ()). System.getErrorCode ()).22 Detect SQL errors or warnings .out.html Warning When the database server executes an SQL statement successfully. So after DB operation./javadetails/java−0331.com/javadetails/. System. Also the driver can provide is own warning codes in the "01" class."username".. you ask the Connection object if there are any warnings.7. // You may have multiple warnings chained together if (w != null) { System. while (w != null) { System. The 7. // If a SQLWarning object was returned by the // Connection object. You can interrogate the SQLException object to know more details about the actual error.out. The subclass code then indicates the cause of the warning.

} catch (SQLException ignored) { //do nothing } } Check your DBMS manual for a full list of supported SQLState./javadetails/java−0345.getMessage() + ""). ex = ex. System. try { // .out.Exception ex) { // Some other type of exception occurred System.getErrorCode() + "").getNextException().JdbcOdbcDriver"). Thanks (works on some Windows installation while on other it does not!) It is possible to connect to a database without a User or System DSN.println ("Message: " + ex. let me know!.println ("SQLState: " + ex.out.jdbc. try { if (con != null) con. 2. while (ex != null) { System. String myDB = "jdbc:odbc:Driver={Microsoft Access Driver (*. A "SQLState" string.html This HowTo seems broken.out."". This is used as the Java Exception message.println(""). 7.odbc. // For Access Class.mdb)}.23 Using DSN−less connection .DBQ=C:/data/month.. which follows the XOPEN SQLState conventions..SQLException object contains : 1.23 Using DSN−less connection Current version of this HowTo : http://www. 7. System.com/javadetails/. // There could be multiple error objects chained together System.getConnection(myDB.println ("*** SQLException caught ***").getMessage()+ "").rgagnon. 3. available via the getMessage method."").out. An integer error code that is specific to each vendor.close().out. if anyone know what is problem.getSQLState () + "").lang.. some SQL operations } catch (SQLException ex) { // SQLException occured. A string describing the error. Not all JDBC driver support this feature.println("*** Exception caught ***").println(ex.out. System. } finally { // Close the database connection.println ("Vendor ErrorCode: " + ex. } } catch (java.out. System.MDB".out. This is useful if you don't have easy access to a client registry to define the required DSN. DBConn = DriverManager.forName("sun.

System."". } id : " + id).odbc.*. public static void main(String[] args) throws ClassNotFoundException.jdbc. try { con = DriverManager./javadetails/java−0362.*. firstname.getInt(3). java.out."").getString(1).close().com/javadetails/." + "DriverID=22.forName(DRIVER_NAME).io. Connection con = null. id from [Sheet1$]")..24 Read data from Excel worksheet Current version of this HowTo : http://www.forName("sun.sql.JdbcOdbcDriver".getConnection(DATABASE_URL). Define an ODBC datasource (system DSN) named "employee_xls" that points to that worksheet.getString(2).jdbc.html Let's assume we have a worksheet like this LASTNAME Reiser Ricci Gugliuzza FIRSTNAME Beth Dylan Brian ID 102 111 116 To access this data. DriverManager.createStatement().executeQuery ("select lastname.odbc. we can use the JDBC−ODBC bridge.getConnection(myDB.DBQ=c:/data/month. String myDB = "jdbc:odbc:Driver={Microsoft Excel Driver (*. java. Statement stmt = con. public class EmployeeReader{ public static final String DRIVER_NAME = "sun. String fname = rs.close(). java. Thanks to R. 7. stmt. Hibberd for the tip.xls. example 1 import import import import java. while (rs.xls)}.println(fname + " " + lname + " } rs. ResultSet rs = stmt.24 Read data from Excel worksheet .READONLY=false". int id = rs.util.// For Excel Class.net. SQLException{ Class. public static final String DATABASE_URL = "jdbc:odbc:employee_xls".*.rgagnon.next()) { String lname = rs. Microsoft provides an ODBC driver to Excel worksheet. 7.JdbcOdbcDriver").*.

ResultSetMetaData rsmd = rs.close().print("Exception: ").25 Handle Excel files Current version of this HowTo : http://www.out..out.getMessage()).rgagnon. This HowTo is only about 7.odbc.getMetaData().print(columnValue). } rs. System.close().out.getConnection( "jdbc:odbc:employee_xls" ).getString(i). i++) { if (i > 1) System. } } } example 2 import java. i <= numberOfColumns. Statement st = con. public class EmployeeReader{ public static void main(String[] args){ Connection connection = null.*.executeQuery( "Select * from [Sheet1$]" ). System.getColumnCount(). } System.25 Handle Excel files .close(). } } } If you find this article useful. try{ Class.close().html There are many solutions to read or write Excel spreadsheets from Java. } finally { con. System./javadetails/java−0516.io.err. ResultSet rs = st.*.err. "). st. import java. int numberOfColumns = rsmd.createStatement(). Connection con = DriverManager.sql.println("").print(".forName("sun.JdbcOdbcDriver"). } catch(Exception ex) { System. ).next()) { for (int i = 1.jdbc.println(ex.finally { if (con != null) con.println ( "No of cols "+numberOfColumns while (rs. consider making a small donation to show your support for this Web site and its content. String columnValue = rs. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 7.out.com/javadetails/.

"attachment.26 JDBC−ODBC Excel driver This solution lets you access your Excel worksheet with SQL SELECT statement.setHeader ("Content−Disposition". IOException { OutputStream out = null. } catch (Exception e){ throw new ServletException("Exception in Excel Sample Servlet". The required ODBC driver is included in a regular Windows installation and the JDBC−ODBC bridge is used to access the Excel DSN.WritableSheet.write. "Hello World")).write.io.WritableWorkbook.servlet.setContentType("application/vnd. One nice thing about JExcelApi is that it has no dependencies on any third party libraries.addCell(new Label(0. WritableSheet s = w.createSheet("Demo". jxl. public class Sample extends HttpServlet { public void doGet (HttpServletRequest request.write.close(). and modify Excel spreadsheets dynamically. jxl.servlet.Workbook.HttpServletResponse.HttpServlet. write.ServletException.HttpServletRequest.OpenSource (and free) solutions.close().ms−excel"). 7. response. 0. See this HowTo for an example.getOutputStream()). } finally{ if (out != null) out.io. e). w. javax. 0).http.write().createWorkbook(response.http. HttpServletResponse response) throws ServletException. 7.IOException.xls"). filename=sampleName. Example : output an Excel file from a Servlet import java. Any operating system which can run a Java virtual machine can both process and deliver Excel spreadsheets. } } } 7.servlet. import java. WritableWorkbook w = Workbook. s.servlet.Label. try { response.27 JExcel Java Excel API is a java API enabling developers to read.http. jxl. javax. javax. w. jxl.26 JDBC−ODBC Excel driver . import import import import import import import import javax.OutputStream.

It is based on Jakarta POI. staff.30)). Map beans = new HashMap().close(). 3000. destFileName). 7. The name was originally an acronym for "Poor Obfuscation Implementation" (ref: Wikipedia). POI has a dependencies with other JARs (commons..createSheet("new sheet"). fileOut. modify. 0. See http://jakarta.15)).put("employee"..setCellValue("HelloWorld"). transformer. Since it's Jakarta project.org/poi/ 7. staff.age} ${employee. HSSFSheet sheet = wb. staff). beans.bonus} $[SUM(@employee.payment@)] with the code Collection staff = new HashSet(). 35. POI is your Java Excel solution as well as your Java Word solution.createRow((short)0).add(new Employee("Elsa". FileOutputStream fileOut = new FileOutputStream("workbook. HSSF is the POI Project's pure Java implementation of the Excel '97(−2002) file format and it provides a way to read spreadsheets create. HSSFRow row = sheet.28 POI The POI project consists of APIs for manipulating various file formats based upon Microsoft's OLE 2 Compound Document format using pure Java.xls"). read and write XLS spreadsheets. 1500.createCell((short)0).transformXLS(templateFileName. row.log4j.29 JXLS jXLS is a project that allows creation of extremely complex Excel reports just in several lines of code.See http://jexcelapi.write(fileOut). formulas etc using specific notation to indicate placement of data and then write a couple lines of code to invoke jXLS engine passing XLS template and the exported data as parameters.). With jXLS. 0.add(new Employee("Derek".payment} ${employee.28 POI . XLSTransformer transformer = new XLSTransformer(). beans.etc. Example : The XLS Template Employees Name ${employee.net/ 7. 28. wb. Example : create an Excel file HSSFWorkbook wb = new HSSFWorkbook(). all you need is to create XLS template file with all required formatting.name} Age Payment Bonus ${employee.sourceforge.apache.

Workbooks().println ("set infomation of files in current directory to cell .gives the result Employees Name Age Derek 35 Else 28 Payment Bonus 3000 30. 7.sourceforge.out.Item(1).println("Value="+excel.Cells().Add().out. ExcelWorkbooks xlBooks = excel.println("Caption="+excel.00% 1500 15.*.out. The documentation is minimal (in Japanese!). ExcelWorkbook xlBook = xlBooks.Visible(true).ne.Date.30 xlSQL xlSQL is a JDBC Driver for Excel and CSV data sources. xlSQL includes its own "zero−admin" mySQL database. System. With JCOM you can call a COM object from Java as if it were a Java object without having to deal with the internals of JNI.. Documents can be read and written with SQL as if they were tables in a database. class TestExcel { public static void main(String[] args) throws Exception { ReleaseManager rm = new ReleaseManager(). try { System.util..sourceforge. ExcelRange xlRange = xlSheet.out. System. See http://xlsql.Worksheets().jcom.ga2. You can export XLS to XML or SQL INSERT statements. // display any information System.").").ne.io. The documentation is minimal at this time.File. java. // create new book // enumurate all files System.so_net.excel8.net/ 7.00% 4500 See http://jxls.UserName()).so_net.println("Version="+excel.31 JCOM JCOM is a Java to COM bridge library. jp. // if already started.30 xlSQL .jcom.no_ji.println("UserName="+excel..out.. Example : import import import import jp. System.out.println("EXCEL startup.net/ 7. open new window ExcelApplication excel = new ExcelApplication(rm).Version()). ExcelWorksheet xlSheet = xlSheets. java.ga2. excel.no_ji. ExcelWorksheets xlSheets = xlBook.Caption()).Value()).*.

i+2).false).Item(4.filenames. xlRange.xlRange.length.canWrite()?"Yes":"No" ).Columns().filenames.. i++) { File file = new File(filenames[i])."). } finally { rm.i+2).i+2). xlRange. xlRange.Value("is file").xls").. xlRange.Item(5.i+2). for(int i=0. (My Documents)\\testExcel.out.println(file). i<filenames.Quit(). } } } See http://sourceforge.println ("embed equation.1).Item(6.Item(2. xlRange. // fit columns // comment out. calculate sum of filesize: "+expression).Item(4.println("thank you .Value("can write").out.Value("is directory"). xlRange.Value( file.Value("sum").Value( file./").length+2).Item(2.i+2).length+1)+")".Item(1.1).i+2).lastModified()) ).release(). // System.com/estore/product_detail.printStackTrace(). xlRange. xlRange.getName() ).SaveAs("testExcel.1). xlRange. if book save to file.Item(1.32 OpenXLS Java Spreadsheet SDK .isFile()?"Yes":"No" ). // output default printer. // xlSheet. xlRange. xlRange. if no path.length() ).Value( file.Item(2.Item(3. xlBook. xlRange.Item(1. excel. xlRange.Value("filename" ).println("print out. // // // // // comment out.out.extentech. } String expression = "=Sum(B2:B"+(filenames.32 OpenXLS Java Spreadsheet SDK OpenXLS claims that it has the best compatibility with complex Excel files and able to handle any kind of Excel file out there without corrupting it. xlRange. save to(My Documents) System.Value("can read"). } catch(Exception e) { e.Item(3.list()..out."). xlRange.Value( file.AutoFit().Value("size" ).Value( (int)file.1).1). xlBook.Item(6. System.isDirectory()?"Yes":"No" ).println ("save to file. See http://www.jsp?product_group_id=228 7.Formula(expression).net/projects/jcom See also this HowTo for an alternative package to access a COM package from Java. This open source effort is the result of over 6 years of development into it. System.Value( file.out.i+2).Value("last modified time").Item(7.null..Item(7. System.length+2).1).Close(false.1).Value( new Date(file.PrintOut(). if print out.xls").Item(5. 7. File path = new File(".canRead()?"Yes":"No" ). String[] filenames = path. xlRange.

sheet. } tbo = new WorkBookHandle().gif. 7.getImages(). CellHandle a1 = sheet.x++) { fin = new FileInputStream(workingdir + "testImages." +extracted[t].. jpgy.setBounds(100.getType()). . void doit(String finpath. sheet). WorkBookHandle tbo = new WorkBookHandle(workingdir + finpath).out. String sheetname){ System. . create a new workbook with them) : doit("testImages.setX(10).println("Successfully extracted: " + workingdir + "testImageOut_" + extracted[t]. a jpg.setName("heart" + x).Example (extract 3 images from a workbook.length. ix = Math.random()*10)))). jpgy.png").png. 100. // add to sheet for(int x=0. // set picture size and location in sheet giffy.insertImage(giffy). outimg. . sheet." +extracted[t].t<extracted. and a png".random()*10)))).getWorkSheet("Sheet1").32 OpenXLS Java Spreadsheet SDK .setName("giffy").write(outimg).getWorkSheet(sheetname).. sheet)."Sheet1").gif").close().setX(100 + ix).jpg ImageHandle[] extracted = sheet. outimg. // add to sheet ImageHandle pngy = new ImageHandle(fin.jpg"). 400.flush(). // extract and output images for(int t=0. // set just the x/y coords of picture pngy.t++) { System. jpgy.setY(100 + ix).round((float)((x * (Math.getName()+".xls". // add to sheet ImageHandle giffy = new ImageHandle(fin. extracted[t]. // set the random x/y coords of picture int ix = Math. sheet). ImageHandle jpgy = new ImageHandle(fin. // get gif image input stream FileInputStream fin = new FileInputStream (workingdir + "testImages.out. sheet = tbo.round((float)((x * (Math. "A1").getName()+". } // get png image input stream fin = new FileInputStream(workingdir + "testImages. giffy.getType()). // read images from sheet 1 −− .insertImage(jpgy).println("Begin parsing: " + workingdir + finpath).add ("New workbook with 3 images: a gif. 200). FileOutputStream outimg = new FileOutputStream (workingdir + extracted[t].x<100. try{ sheet = tbo.

33 Specify a CharSet when connecting to a DBMS .xls").util.println("testImages failed: " + e.setY(200).Properties prop = new java. password).34 Get current date using JDBC Current version of this HowTo : http://www.File(fout).xls".err.io.. "iso−8859−7").html With most DBMS.html Class. BufferedOutputStream bbout = new BufferedOutputStream(fos). Written and compiled by Réal Gagnon ©1998−2007 [ home ] 7.33 Specify a CharSet when connecting to a DBMS Current version of this HowTo : http://www. workingdir + "testImagesOut. } } See also this HowTo for a way to create a simple XLS without any additional library.io. fos.0). } catch (java.io. sheet.jdbc.getBytes()). If you find this article useful. bbout. username). } public void testWrite(WorkBookHandle b. } catch(Exception e){ System. bbout.Properties().write(b./javadetails/java−0371.getConnection(url.insertImage(pngy). prop).flush(). WorkBookHandle newbook = new WorkBookHandle (workingdir + "testImagesOut.put("charSet".com/javadetails/. System. FileOutputStream fos = new FileOutputStream(f).close().toString()).pngy./javadetails/java−0383. JDBC function escape sequence can be used : 7.odbc. "+e). 7. consider making a small donation to show your support for this Web site and its content.forName(sun. // Connect to the database con = DriverManager.rgagnon.rgagnon. // setup the properties java.err. } testWrite(tbo. // for example. prop.JdbcOdbcDriver) . prop. String fout){ try{ java.println("Successfully read: " + newbook).out.com/javadetails/.put("user".IOException e){ System..put("password".println("IOException in Tester..util.File f = new java.. prop.

connect("EAS Demo DB V3".dbConn.getString(3) "\n " + rs.sql.next()) System. "sql").net.35 Enable JDBC logging Current version of this HowTo : http://www.html [JDK1. " + {t '10:30:29' }. theConn.executeQuery(sql).println("results: "\n " + rs. try { prepstmt = theConn. } 7. prepstmt.*. PreparedStatement prepstmt. import java. class JDBCapp { static MyConnection theConn.close().getString(4) " + rs.SELECT {fn curdate() } SELECT {fn curtime() } SELECT {fn now() } for current date for current hour for current date and hour for Oracle..out.doit(). 7. " + {ts '1997−05−24 10:30:29.prepareStatement ("SELECT emp_id FROM employee" ). you add the from dual SELECT {fn curdate() } FROM dual SELECT {fn curtime() } FROM dual SELECT {fn now() } FROM dual for current date for current hour for current date and hour Example : // for Oracle String sql = "select {fn " " " " dayname ({fn now()})}. public static void main (String args[]) { new JDBCapp().123'}" + from dual" .rgagnon." + {d '1997−05−24'}.com/javadetails/. ResultSet rs = stmt. import java. "dba".35 Enable JDBC logging .getString(1) + + + ). prepstmt. } public void doit() { theConn = new MyConnection().execute(). while (rs.getString(2) "\n " + rs.2] Take the following program./javadetails/java−0411.URL.

odbc. String passw) { try { Driver d = (Driver)Class. szSqlStr=SELECT emp_id FROM employee Number of parameter markers (SQLNumParams). hDbc=185334988 hStmt=184290392 Setting statement option (SQLSetStmtOption).printStackTrace().close Free statement (SQLFreeStmt). } } class MyConnection { Connection dbConn = null. hStmt=184290392 Number of result columns (SQLNumResultCols).jdbc. java. } } void disconnect() { try { dbConn. dbConn = DriverManager.getConnection(URL.printStackTrace().io. hStmt=184290392.odbc.JdbcOdbcPreparedStatement@19ee1ac *Connection. fOption=0 Executing (SQLExecute).JdbcOdbcDriver").JdbcOdbcPreparedStatement@19ee1ac *PreparedStatement. } catch (Exception e) { e. user.prepareStatement (SELECT emp_id FROM employee) Allocating Statement Handle (SQLAllocStmt). DriverManager.io.odbc. String user.35 Enable JDBC logging . hStmt=184290392. Setting statement option (SQLSetStmtOption).close 0 Statement(s) to close Disconnecting (SQLDisconnect).forName("sun.jdbc. passw). hStmt=184290392 value=0 Registering Statement sun.out)).execute Free statement (SQLFreeStmt).newInstance().PrintWriter (new java.io. hDbc=185334988 Closing environment (SQLFreeEnv). fOption=1 deregistering Statement sun. String URL = "jdbc:odbc:" + db. } catch (Exception e) { e. void connect(String db. hDbc=185334988 Closing connection (SQLFreeConnect).disconnect(). hStmt=184290392 value=1 *PreparedStatement. Preparing (SQLPrepare). hStmt=184290392.setLogWriter(w). hStmt=184290392.close().printStackTrace(). } theConn. hEnv=185334828 7.jdbc. } } } And the output at the console will look like this : *Connection.catch (Exception e) { e.PrintWriter w = new java.OutputStreamWriter(System.

w3c.w3c. java.sql.. public static void main (String args[]) { ResultSet rs = null. javax.sql. "employee".37 Convert a ResultSet to XML Current version of this HowTo : http://www. Statement stmt = null.dom.dom.rgagnon. String sql.getMetaData().Element.parsers.html import import import import import import import import import import import import import java. try { DocumentBuilderFactory factory = DocumentBuilderFactory./javadetails/java−0485. javax.Document.getTables(null.DriverManager.com/javadetails/.sql. null). doc.xml.36 Detect if a table exists Current version of this HowTo : http://www.appendChild(results).com/javadetails/. DatabaseMetaData dbm = c.Connection./javadetails/java−0511.sql. DocumentBuilder builder =factory. java. Document doc = builder.ResultSet. java. javax. { class JDBCapp static Connection con.rgagnon.next()) { // Table exists } else { // Table does not exist } If you find this article useful.xml.xml. java. consider making a small donation to show your support for this Web site and its content.transform.transform.newDocumentBuilder(). org.stream.Driver.xml.newInstance().transform. java. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 7. javax.36 Detect if a table exists ..Statement.sql.dom..ResultSetMetaData.. 7.newDocument(). null.sql.*.parsers. org.*.html Connection c = .DocumentBuilderFactory. if (rs. Element results = doc.xml.createElement("Results").7.DocumentBuilder.*. javax. // check if "employee" table is there ResultSet tables = dbm.

rs = stmt. sr). // java. // we want to pretty format the XML output // note : this is broken in jdk1. results."ISO−8859−1").appendChild(row). ii++) { String columnName = rsmd.INDENT.io.close().println(getDocumentAsXml(doc)). TransformerFactory tf = TransformerFactory.apache.StringWriter(). transformer. Object value = rs. "yes"). //transformer. ii <= colCount.appendChild(node). } } System. for (int ii = 1. "xml").setOutputProperty(OutputKeys.toString(). node. } finally { try { if (con != null) con.setOutputProperty(OutputKeys. } catch (Exception e) { } } } public static String getDocumentAsXml(Document doc) throws TransformerConfigurationException. return sw.OMIT_XML_DECLARATION.executeQuery(sql).appendChild(doc.forName 7.getMetaData(). transformer. transformer.next()) { Element row = doc.setOutputProperty ("{http://xml.getConnection().createElement("Row").io. if (rs != null) rs.// connection to an ACCESS MDB con = AccessCon. "4").getObject(ii).close(). row. while (rs.getColumnCount().METHOD. sql = "select objet from Email". stmt = con. int colCount = rsmd. StreamResult sr = new StreamResult(sw).5 beta! transformer. Element node = doc. } } class AccessCon { public static Connection getConnection() throws Exception { Driver d = (Driver)Class.org/xslt}indent−amount".StringWriter sw = new java.close(). TransformerException { DOMSource domSource = new DOMSource(doc).ENCODING.printStackTrace().createTextNode(value.transform(domSource.setOutputProperty(OutputKeys.createStatement()."yes").setOutputProperty(OutputKeys.getColumnName(ii).newTransformer().out.36 Detect if a table exists .toString())). if (stmt != null) stmt.newInstance().createElement(columnName). } catch (Exception e) { e. Transformer transformer = tf. transformer. ResultSetMetaData rsmd = rs.

*/ } } If you find this article useful.JdbcOdbcDriver").executeQuery ("SELECT value FROM vendors WHERE value LIKE '%one/%word' {escape '/'} "). /* To use an already defined ODBC Datasource : String URL = "jdbc:odbc:myDSN". return c. 7. rs = st.getConnection ("jdbc:odbc:Driver={Microsoft Access Driver (*.getConnection(URL.newInstance().jdbc.DBQ=c:/tech97.createStatement().38 Escape special character in a LIKE clause Current version of this HowTo : http://www.mdb"). Searching for "one_word" st = con. consider making a small donation to show your support for this Web site and its content.createStatement().("sun.executeQuery ("SELECT value FROM vendors WHERE a LIKE '%=_' {escape '='}").createStatement()..executeQuery ("SELECT value FROM vendors WHERE value LIKE '$%%' {escape '$'}"). rs = st.odbc.com/javadetails/.rgagnon. Find all rows in which a ends with the character "_" st = con. The escape sequence must be at the end of the SQL statement.mdb)}. "pwd"). "user".executeQuery ("SELECT value FROM vendors WHERE value LIKE 'one/_word' {escape '/'}").createStatement()./javadetails/java−0554. Find all rows in which a begins with the character "%" st = con. Searching for strings ending with "one%word" st = con. rs = st.38 Escape special character in a LIKE clause .html Your JDBC driver may support the {escape 'escape character'} syntax for using LIKE clause wildcards as literals. rs = st. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 7. Connection c = DriverManager. Connection c = DriverManager.

rgagnon./javadetails/java−0602. 7.com/javadetails/.html It's good idea to use the JDBC escape function instead of using a specific DBMS function.com/javadetails/.41 Plain JDBC Logging See this HowTo.39 Insert the current date Current version of this HowTo : http://www..sourceforge.html 7." "'" + custPhone + "'" + ".39 Insert the current date . This way.net/ Written and compiled Réal Gagnon ©2007 real@rgagnon. Download at http://proxool." " {fn now() } )".com http://www. 7.40 Log the SQL Statements Current version of this HowTo : http://www. It provides really nice logging facilities with the SQL statement and the running time. your code will be portable..com 7.43 Proxool Proxool is a Java connection pool.42 P6Spy P6Spy is an open source framework for applications that intercept and optionally modify database statements.rgagnon./javadetails/java−0567. Download at http://p6spy.com/ 7. sql = + + + "INSERT INTO CUSTOMERS VALUES(" "'" + custName + "'" + ".rgagnon. The log file format is current time|execution time|category|statement SQL String|effective SQL string P6Spy is especially useful with an application server.7.

cpp source. jobject obj) { 8 JNI . 8./javadetails/java−0283.sayHello()).java class JavaHowTo { public native String sayHello().dll in the same directory as the java program. jobject obj) { return env−>NewStringUTF("Hello world").h in your project header files • In the Tools − Options menu.rgagnon./javadetails/java−0284. They are located in [jdk dir]\include and [jdk dir]\include\win32 directories • In the javahowto.h" JNIEXPORT jstring JNICALL Java_JavaHowTo_sayHello (JNIEnv *env. add the JavaHowTo.com/javadetails/.loadLibrary("javahowto").8 JNI 8. set the include directories to include the Java JNI headers files. } • Select the Release configuration and build the project..println(jht.rgagnon. add #include "JavaHowTo..3 Pass a string to/from Java to/from C Current version of this HowTo : http://www. create a new Win32 DLL project (simple) and call it javahowto.h header file.out. • Copy the javahowto. } } • Compile and execute.html To Java from C (as seen from the previous How−to) : #include "JavaHowTo.html • With MSVC6. • Create this new java program public class JNIJavaHowTo { public static void main(String[] args) { JavaHowTo jht = new JavaHowTo(). } } • Compile the Java program and use javah utility to generate the JavaHowTo.1 java−jni 8. static { System. • In the same directory create a java source called JavaHowTo.com/javadetails/. System.h" JNIEXPORT jstring JNICALL Java_JavaHowTo_sayHello (JNIEnv *env.2 Use native code through JNI Current version of this HowTo : http://www. javah −jni JavaHowTo • In MSVC6.

} } then from C. constructorID). // call the sayHello() method jstring s = (jstring) env−>CallObjectMethod (myclass_object."). jclass myclass_class =(jclass) env−>NewGlobalRef (env−>FindClass ("MyClass")). From Java to C : Suppose we have a Java Class public class MyClass { public String sayHello(){ return "Hello world From Java". str).loadLibrary("javahowto"). to use it public class JNIJavaHowTo { public static void main(String[] args) { JavaHowTo jht = new JavaHowTo(). } } And finally. static { System. // instanciate a MyClass object jobject myclass_object = env−>NewObject (myclass_class. } The Java JNI wrapper would be class JavaHowTo { public native void sayHello(). "()V"). we want to call the Java sayHello() method which returns a String : JNIEXPORT void JNICALL Java_JavaHowTo_sayHello (JNIEnv *env.sayHello(). "sayHello". jobject obj) { const char *str. methodID).return } env−>NewStringUTF("Hello world"). 0). jht. } } 8 JNI . env−>ReleaseStringUTFChars(s. "". // we need the MyClass constructor jmethodID constructorID = env−>GetMethodID (myclass_class. printf("%s" . str). // convert the Java String to use it in C str = env−>GetStringUTFChars(s. "()Ljava/lang/String. // and the sayHello() method jmethodID methodID = env−>GetMethodID (myclass_class.

GetLocalTime( st. jobject. // this example will set the system at 10h21 using the Windows API // SetLocalTime. we need its signature. the method long myMethod (int n.rgagnon. short minutes = 21.wMinute = minutes.4 Set the computer clock Current version of this HowTo : http://www. String s.setSystemTime(hour. jshort. } } 8. int[] arr). static { System.. } } And finally. st.5 Determine the signature of a method Current version of this HowTo : http://www.8. short minutes).html Before calling a Java object's method from JNI. minutes).loadLibrary("javahowto").com/javadetails/./javadetails/java−0286./javadetails/java−0285. jshort). the JNI function JNIEXPORT void JNICALL Java_JavaHowTo_setSystemTime (JNIEnv *env.. jshort minutes) { SYSTEMTIME st.rgagnon. For example. to use it public class JNIJavaHowTo { public static void main(String[] args) { short hour = 10. SetLocalTime( } The Java JNI wrapper would be class JavaHowTo { public native void setSystemTime( short hour. // set the time at 10h21 jht.com/javadetails/.wHour = hour. 8.html Define the following prototype in the header file JNIEXPORT void JNICALL Java_JavaHowTo_setSystemTime (JNIEnv *. jobject obj.4 Set the computer clock . jshort hour. JavaHowTo jht = new JavaHowTo().

*/ protected java.String text.[I)J There are two parts to the signature. /* (Ljava/lang/String. the "L" is followed by the object's class name and ends with a semi−colon. */ public synchronized void setAlignment(int).lang.awt.java public class java.4 Set the computer clock .String. /* (Ljava/lang/String.lang.Label Compiled from Label.awt.is seen from JNI with the signature (ILJAVA/LANG/STRING.awt. The first part is enclosed within the parentheses and represents the method's arguments.lang.I)V */ public void addNotify(). /* Ljava/lang/String. /* I */ public static final int RIGHT.)V */ 8. /* I */ static {}. /* ()Ljava/lang/String.awt.int).String).awt. /* ()Ljava/lang/String. */ int alignment.)V */ public java.Label(java. /* I */ public static final int CENTER.' .Label extends java.lang. /* ()V */ public java.String getText().String constructComponentName().lang. The mapping between the Java type and C type is Type boolean byte char double float int long object short void array Chararacter Z B C D F I J L S V [ Note that to specify an object. The javap utility (included with the JDK) is very useful to show the signature to be used in JNI. /* ()V */ java. X:\>javap −s java.awt. /* ()I */ public java. '.lang. /* (Ljava/lang/String.lang.Label(). /* I */ java.String paramString().Label(java. /* (I)V */ public void setText(java.String). */ public int getAlignment(). /* ()V */ public java. The second portion follows the closing parenthesis and represents the return type. /* ()Ljava/lang/String.Component { public static final int LEFT.

html JNI provides special functions (relative to the type) to access Java arrays. it's possible to fetch directly from the class the array.com/javadetails/. jobject jtab. } The Java wrapper class JavaHowTo { public static native int max(int [] t). i=1. body. This example returns the maximum of an int array. 9. jclass obj. 0. if (fid == 0) return. 0). tab = env−>GetIntArrayElements(jtab. "[I").. 0). env−>ReleaseIntArrayElements(arr. i <len. jclass cls = env−>GetObjectClass(obj). Without passing the array directly to the JNI function. fid). } } The test program class JNIJavaHowTo { public static void main(String[] args) { int [] myArray = {4. 5.* or your own classes. 1}. jint *body = env−>GetIntArrayElements(arr. 0). jintArray arr) { int i.The javap utility can be used on the java.max(myArray)). jsize len = env−>GetArrayLength(arr. i++) if (max <body[i]) max = body[i]. int i.6 Use arrays Current version of this HowTo : http://www. JNIEXPORT jint JNICALL Java_JavaHowTo_max (JNIEnv * env. 7. } } This following how−to is currently broken. len = env−>GetArrayLength(jtab).. static { System.out. System. jsize len.println(JavaHowTo.6 Use arrays . 2. "myArray". return max. jclass obj) { jfieldID fid. jtab = env−>GetObjectField(obj.rgagnon. 8. 8. for (max = body[0].loadLibrary("javahowto"). max = −1. JNIEXPORT jint JNICALL Java_JavaHowTo_printArray (JNIEnv * env.. fid = env−>GetFieldID(cls./javadetails/java−0287.

asp . tab[i]).rgagnon. jdouble.rgagnon.path=c:/temp JNIJavaHowTo 8. If the DLL is not in the CLASSPATH then you need to specify the PATH. 8.com/javadetails/.com/javadetails/. jobject.2 (or better).getRuntime(). for (i = 0.7 Load a DLL Current version of this HowTo : http://www. jdouble).dll") In JDK1.dll"). 8. i <len .html [pre JDK1. Next version (JDK1.rgagnon.load("d:/directoryX/subDirY/MyDll. the JNI function JNIEXPORT jdouble JNICALL Java_JavaHowTo_divide 8..2] System. or specify through the JVM command line the location where to find the JNI DLL to be loaded java −Djava.loadLibrary("d:\\directoryX\\subDirY\\MyDll.8 Use the MouseWheel Current version of this HowTo : http://www. you need some JNI functions.com/javadetails/.html Define the following prototype in the header file JNIEXPORT jdouble JNICALL Java_JavaHowTo_divide (JNIEnv *. i++) printf("%d printf("]\n").4) may provide this functionality but for now. if the DLL is in the CLASSPATH then you don't need to specify a PATH./javadetails/java−0318. Runtime. } ".printf("int [] : [").7 Load a DLL .library./javadetails/java−0323.com/java/mousewheel. See this link http://www..html Current JDK don't support scrolling via the MouseWheel./javadetails/java−0314.. Do something like this instead.codeproject.9 Throw an Exception (from JNI code) Current version of this HowTo : http://www.

rgagnon.divide(9. the JNI function JNIEXPORT void JNICALL Java_JavaHowTo_triggerException (JNIEnv *env. env−>ThrowNew(Exception. } } 8.0..0)).divide(9.com/javadetails/.").0)). System. jobject).0) { jclass Exception = env−>FindClass("java/lang/Exception"). } The Java JNI wrapper would be class JavaHowTo { public native double divide(double d1. jobject obj) { jclass MyOwnException = env−>FindClass("MyOwnException"). } } And finally.println("division 1 : " + jht.10 Throw my own Exception (from JNI code) Current version of this HowTo : http://www."Exception triggered from JNI routine.(JNIEnv *env. System. } return d1/d2. } } the prototype in the header file JNIEXPORT void JNICALL Java_JavaHowTo_triggerException (JNIEnv *. jdouble d1.out. to use it public class JNIJavaHowTo { public static void main(String[] args) { JavaHowTo jht = new JavaHowTo(). jdouble d2) { if (d2 == 0. double d2).loadLibrary("javahowto"). 0. env−>ThrowNew(MyOwnException. 3."Can't divide by zero.").html The MyOwnException class public class MyOwnException extends Exception { public MyOwnException(){} public MyOwnException(String txt) { super(txt).10 Throw my own Exception (from JNI code) .println("division 2 : " + jht. static { System./javadetails/java−0322. } The Java JNI wrapper would be class JavaHowTo { 8. jobject obj.out.0.

static { System. consider making a small donation to show your support for this Web site and its content. JNIEXPORT jint JNICALL Java_JavaHowTo_getHwnd (JNIEnv *env. using the javah utility (from the root of the package) : javah com. If you have a Java native method in a class called MyClass like this: public native void myMethod().html First you need the handle of the Window.rgagnon. } } And finally. jobject). jht.public native void triggerException(). jobject). compile the JNI class in the package then. to use it public class JNIJavaHowTo { public static void main(String[] args) { JavaHowTo jht = new JavaHowTo().html JNI requires that the function names follow a specific format.rgagnon. jclass obj./javadetails/java−0353. } } 8. When you put the class into a package (say com.. Call this JNI function with Window Title. you need to include the package information in the native function name like this: JNIEXPORT void JNICALL Java_com_rgagnon_MyClass_myMethod(JNIEnv *.12 Make a Window "stay on top" Current version of this HowTo : http://www.loadLibrary("javahowto")./javadetails/java−0348..11 JNI from a package Current version of this HowTo : http://www.MyClass If you find this article useful. To generated the proper header.triggerException().com/javadetails/.rgagnon. jstring title){ 8.11 JNI from a package .rgagnon).com/javadetails/. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 8. the native function must look like this: JNIEXPORT void JNICALL Java_MyClass_myMethod(JNIEnv *.

JavaVMInitArgs vm_args. jclass obj.rgagnon.com/javadetails/. JNIEnv *env.0. const char *str = NULL.str). } jstring argString = env−>NewStringUTF(""). } 8. env−>FindClass("java/lang/String").h> #include <stdio.0.)V"). options[0].SWP_NOMOVE|SWP_NOSIZE). return (jint) hwnd.HWND_TOPMOST. vm_args. title. 0).0. else SetWindowPos((HWND) hwnd.options = options.nOptions = 1./javadetails/java−0354.0. vm_args.0.path=c:/myclasses". jobjectArray args. jstring jstr.optionString = "−Djava.ignoreUnrecognized = 1. title. jint hwnd. hwnd = FindWindow(NULL. exit(1). JavaVMOption options[1]. //empty arg list jobjectArray args = env−>NewObjectArray(1.0. } jmethodID mid = env−>GetStaticMethodID(cls.class. return. (*env)−>ReleaseStringUTFChars(env. vm_args.0. str = (*env)−>GetStringUTFChars(env.13 Start a JVM from C . if (mid == 0) { printf("main() method not found\n").version = JNI_VERSION_1_2.h> int main() { JavaVM *vm.SWP_NOMOVE|SWP_NOSIZE). vm_args.html #include <jni.HWND hwnd = NULL. 8. "main". jstr). exit(1). jint res = JNI_CreateJavaVM((void **) if (res < 0) { printf("Can't create Java VM\n").HWND_NOTOPMOST. "([Ljava/lang/String. // in c:/myclasses if (cls == 0) { printf("HelloWorld class not found\n").. } Then you pass the handle to this function JNIEXPORT void JNICALL Java_JavaHowTo_setWindowAlwaysOnTop (JNIEnv *env. } jclass cls = env−>FindClass("HelloWorld"). str). jboolean flag){ if (flag) SetWindowPos((HWND) hwnd.13 Start a JVM from C Current version of this HowTo : http://www.0. exit(1).

static { System. name) . the getenv() method was removed from the JDK. 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.loadLibrary("jni2"). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 8. (jboolean *)NULL) . consider making a small donation to show your support for this Web site and its content./javadetails/java−0460.15 Get the PID Current version of this HowTo : http://www.5 (see this HowTo). If you find this article useful. exit(1). const char *value = getenv(name) . jname. return value ? (*env)−>NewStringUTF(env.html class JavaHowTo { public native long getCurrentProcessId(). (*env)−>ReleaseStringUTFChars(env. value) : NULL .if (args == 0) { printf("Out of memory\n"). } } public class JNIJavaHowTo { public static void main(String[] args) { JavaHowTo jht = new JavaHowTo(). jclass c. See also this HowTo. 8.rgagnon. } const char *name = (*env)−>GetStringUTFChars(env. Rumors is that a mechanism to retrieve an environment will be back in JDK1. } env−>CallStaticVoidMethod(cls.rgagnon. jname. return 0. args). jstring jname){ if ( jname == NULL ) { return NULL ./javadetails/java−0467.html For some odd reasons.14 Retrieve environment variable (JNI) .14 Retrieve environment variable (JNI) Current version of this HowTo : http://www.. mid. But for now. } NOTE : This is fine if the environment variable contains only regular 7−bit ASCII characters. } 8.com/javadetails/.com/javadetails/..

return getpid().println(jht.").h" #include <process.io.getCurrentProcessId()).dll).cpp : Defines the entry point for the DLL application.h" BOOL APIENTRY DllMain( HANDLE hModule.BufferedReader(new java.System. public static final short BACKGROUND_GREEN = 0x20.readLine().io.out. public static final short BACKGROUND_BLUE = 0x10. FOREGROUND_GREEN = 0x2. } JNIEXPORT jlong JNICALL Java_JavaHowTo_getCurrentProcessId (JNIEnv *. class JavaHowTo { public public public public public public static static static static static static final final final final final final short short short short short short FOREGROUND_BLACK = 0x0.h> #include "JavaHowTo.java) to provide an interface to the JNI DLL (jni3. DWORD ul_reason_for_call..println("Press Any key.} catch (Exception e) { e. set color and cursor position (JNI) Current version of this HowTo : http://www. set color and cursor position (JNI) .BufferedReader input = new java.in)).16 Clear the console. } } // jni2. } You can download the whole thing here. FOREGROUND_RED = 0x4. LPVOID lpReserved ) { return TRUE. 8.rgagnon. consider making a small donation to show your support for this Web site and its content.com/javadetails/. If you find this article useful.} System. java.html [Windows only] First you need this Java stub (JavaHowTo.InputStreamReader(System. FOREGROUND_BLUE = 0x1. // #include "stdafx.io.out.. FOREGROUND_WHITE = 0x7.. try { input. jobject) { // return GetCurrentProcessId().printStackTrace(). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 8. FOREGROUND_INTENSITY = 0x8.16 Clear the console./javadetails/java−0469.

DWORD ul_reason_for_call. FillConsoleOutputCharacter(hConsole. Home. // #include "stdafx.Y = 0. strConsoleInfo.dwSize. } } Compile and generate an header with javah JavaHowto. Home. unsigned long * hWrittenChars = 0. hConsole = GetStdHandle(STD_OUTPUT_HANDLE). CONSOLE_SCREEN_BUFFER_INFO strConsoleInfo.public static final short BACKGROUND_RED = 0x40. static unsigned char EMPTY = 32. // system("cls").loadLibrary("jni3"). Home.h" int originalColors. Don't forget to include the folders %JAVAHOME%\include and %JAVAHOME%\include\win32 to have access to the JNI header files. jobject obj.16 Clear the console.X * strConsoleInfo. jshort x. short background). COORD Home.. LPVOID lpReserved ) { return TRUE. short y). // and so on. I'm using VisualStudio v6.cpp : Defines the entry point for the DLL application.X. static { System. Next we built a DLL. will do the same as the above! } JNIEXPORT void JNICALL Java_JavaHowTo_setCursorPosition (JNIEnv *env. set color and cursor position (JNI) . jshort y) { 8. the result is a file called JavaHowTo.X = 0. // jni3.h.the definition for the other colors is // left as an exercise :−) public native void cls(). jobject obj) { HANDLE hConsole. GetConsoleScreenBufferInfo(hConsole.h> #include "JavaHowTo. public native void setColor( short foreground. hWrittenChars). EMPTY.. } JNIEXPORT void JNICALL Java_JavaHowTo_cls (JNIEnv *env. Home). SetConsoleCursorPosition(hConsole. BOOL APIENTRY DllMain( HANDLE hModule. public native void setCursorPosition( short x. public native void keepColors().h" #include <stdlib. public native void restoreColors().dwSize. public static final short BACKGROUND_INTENSITY = 0x80.

foreground + background). jobject obj. // set the cursor at line 10 column 20 jht.X = x.cls(). // set the cursor at line 15 column 20 jht. Here an example how to use the DLL. GetConsoleScreenBufferInfo(hConsole. // clear the screen jht.wAttributes. jobject obj) { HANDLE hConsole.BACKGROUND_BLUE). coordScreen.setCursorPosition((short)20. } JNIEXPORT void JNICALL Java_JavaHowTo_keepColors (JNIEnv *env.FOREGROUND_WHITE.(short)10). System.dll. the result is jni3.rgagnon.Y = y.setCursorPosition((short)20. coordScreen ). 8. System. } Build the DLL (target Release). } JNIEXPORT void JNICALL Java_JavaHowTo_setColor (JNIEnv *env.HANDLE hConsole.out. } JNIEXPORT void JNICALL Java_JavaHowTo_restoreColors (JNIEnv *env. SetConsoleTextAttribute(hConsole. set color and cursor position (JNI) . // keep the current colors jht.com"). hConsole = GetStdHandle(STD_OUTPUT_HANDLE).print("Real's HowTo").jht. SetConsoleTextAttribute(hConsole.out. jshort background) { HANDLE hConsole. public class JNIJavaHowTo { public static void main(String[] args) { JavaHowTo jht = new JavaHowTo(). COORD coordScreen.(short)15). hConsole = GetStdHandle(STD_OUTPUT_HANDLE). originalColors).16 Clear the console. jshort foreground. jobject obj) { HANDLE hConsole. originalColors = ConsoleInfo. CONSOLE_SCREEN_BUFFER_INFO ConsoleInfo. hConsole = GetStdHandle(STD_OUTPUT_HANDLE). coordScreen.setColor(jht.print("http://www. SetConsoleCursorPosition( hConsole.keepColors(). // set the color as WHITE on BLUE jht. hConsole = GetStdHandle(STD_OUTPUT_HANDLE).

FALSE }). Boolean.txt".*.// restore the orginal colors jht. IntCall ic = new IntCall("CopyFileA").17 Call Windows API (Open source solution) .rgagnon./javadetails/java−0497. ic. // set the cursor at line 20 column 0 jht. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 8. If you find this article useful.txt".nativecall.com http://www.rgagnon.setCursorPosition((short)0. "test_copy.html NativeCall NativeCall is a Java toolkit that lets you call operating system methods from whithin Java without JNI code. ic. Written and compiled by Réal Gagnon ©1998−2005 [ home ] Written and compiled Réal Gagnon ©2007 real@rgagnon..com 8. consider making a small donation to show your support for this Web site and its content.restoreColors().com/javadetails/.executeCall(new Object[] { "test. } } You can download a zip with everything here.17 Call Windows API (Open source solution) Current version of this HowTo : http://www. NativeCall. See http://johannburkard.init().destroy(). consider making a small donation to show your support for this Web site and its content. // copying a file to a new one using the Windows API import com.eaio.de/software/nativecall/ If you find this article useful.(short)20).

k. [JAVA APPLET] import java.html. 9 Javascript interaction . boolean okToChrono = false. thanks to A. long j. we want to start an applet (here a simple chronometer). The LiveConnect package is included with the Java plugin too.awt. The official documentation for the various versions can be found at http://java.html The examples in these How−to's are tested with Netscape 7 (or better) on Windows. The LiveConnect package is included with IE4/5 (Win version). the Applet should stop. Thanks to Neil English for the tip 9. String currentTime = "0".9 Javascript interaction 9.2 * Read me * Current version of this HowTo : http://www. The JSObject package is included with Netscape 6 preview but it is broken but should be fixed for the release version! Mac To use the LiveConnect packages on the Mac you will need to install the latest MRJ available from the Apple website and then goto the Mozilla website and download the MRJ Plugin.com/javadetails/. Zisowsky for the tip). and when the mouse leave the image. import java. l.com/javadetails/.sun.*..com/products/plugin/reference/docs/index. public class JavaChrono extends Applet { String previousTime = "0" .html When moving the mouse over an image.rgagnon.3 Wake−up a Java applet Current version of this HowTo : http://www. Unix/Linux But it seems that there is a LiveConnect−SDK for Unix. The only other thing then is to change the <applet> tags to <embed> tag (more info on this is on the Mozilla site).rgagnon..applet./javadetails/java−0168.1 java−js 9.*. It's based on N3 but works on N4 (at least on Solaris and Linux./javadetails/java−0169.

10.sleep(1000).Color b. g. public void init() { b = getBackground(). } public void stopChrono() { okToChrono = false. g.currentTimeMillis(). l = k−j. } public void paint(Graphics g) { if (okToChrono) { g.currentTimeMillis().stopChrono()" > <IMG SRC="whatever.start(). public MyThread(JavaChrono a) { theApplet = a.applets[0].setColor(b). MyThread tm = new MyThread(this). } } } class MyThread extends Thread { JavaChrono theApplet.drawString(currentTime. f = getForeground().toString(l/1000).drawString(previousTime.gif" WIDTH=100 HEIGHT=100> </A> /BODY/HTML 9 Javascript interaction .30). previousTime = currentTime.repaint(). } public void startChrono() { j = System. this. f. tm.10.setColor(f). } catch(InterruptedException e) { } } } } [HTML] <HTML><HEAD></HEAD><BODY> <APPLET CODE=JavaChrono. } public void run() { while (true) { try { theApplet.startChrono()" onMouseOut="document. okToChrono = true.applets[0]. currentTime = Long.30).class WIDTH=150 HEIGHT=150> </APPLET> <A HREF="" onMouseOver="document. g. k = System.

html You call a Java method by giving its fully qualified name.showFrame()"> <INPUT TYPE="button" VALUE="Stop the Applet" onClick= "if (document.*. } } public void disposeFrame() { if (f != null) { f. In the next example. the first example calls the method in the Toolkit to retrieve the screen resolution.Try it here.disposeFrame()"> /FORM/BODY/HTML [JAVA APPLET] import java.myApplet. 9.com/javadetails/./javadetails/java−0170. f = null. f.setVisible(true).applets[0]. 9.rgagnon.100).add(new Label("Hello World")).awt.4 Call a Java method from Javascript .*.isActive()) document.class" HEIGHT=1 WIDTH=1></APPLET> <FORM> <INPUT TYPE="button" VALUE="Start the Applet" onClick= "if (document. [HTML] <HTML> <HEAD></HEAD> <BODY> <APPLET NAME="myApplet" CODE="MyApplet.applet.setSize(100. f. In the following snippet.dispose(). public class MyApplet extends Applet { Frame f = null. f. we tell the applet to open or close a frame. calls a method in our Applet. when we click on a FORM's button. public void init() { } public void showFrame() { if (f == null) { f = new Frame().4 Call a Java method from Javascript Current version of this HowTo : http://www. The second example.isActive()) document.myApplet. import java. } } } Try it here.applets[0]..

wrap the java. } } [Javascript and HTML (Netscape)] <HTML><HEAD></HEAD><BODY> <SCRIPT> function getScreenDimension() { alert("Screen Dimension\n" + " width:" + java.*.drawString("Hello from JAVA!".awt.awt.Applet) but don't have a general access to other java classes .*. 10).*. import java.sayHello()"> </FORM> <INPUT type="button" value="call Java method direct" onClick = "getScreenDimension()"> <APPLET CODE="InJava.applet.getDefaultToolkit().4 Call a Java method from Javascript . public class InJava extends Applet{ public void sayHello() { Graphics g = getGraphics(). IE javascript can only access the public methods of an applet (a class derived from java.getDefaultToolkit().NOTE: On IE4 or better.getScreenSize().applet.* call in a public method of a "dummy" Applet.awt.awt. 10. } </SCRIPT> <FORM> <INPUT type="button" value="call Java Applet method" onClick = "document.* methods directly from Javascript or Jscript.getDefaultToolkit(). g.width + " height:" + java.getScreenSize().applet.class" NAME="myApplet" HEIGHT=100 WIDTH=100> </APPLET> /BODY/HTML Try it here import java.getScreenSize(). // (IE and Netscape ok) public class InJava2 extends Applet{ public int getScreenWidth() { return Toolkit. [Java applet] import java.width.height.*.getScreenSize().getDefaultToolkit(). } public int getScreenHeight() { return Toolkit. you can't call java.myApplet. import java.height).Toolkit. So the solution is simple. } } [Javascript and HTML (IE and Netscape)] <HTML><HEAD></HEAD><BODY> 9.Toolkit.

rgagnon. There is no need for a Java Applet! NOTE: The first time. the variable must be declared as "public".getScreenHeight() ).myApplet. there is a delay because the Applet need to load and initialize.5 Calling Java applets methods using DOM and JavaScript .html [IE4 or better] <OBJECT ID="myApplet" .getScreenWidth() + " height:" + document. </OBJECT> [in your script] document. 9.com/javadetails/.. On N4 or IE4.. To be compatible Netscape AND MSIEv4.com/javadetails/.class" NAME="myApplet" HEIGHT=100 WIDTH=100> </APPLET> /BODY/HTML Try it here NOTE: This for demonstration only. In Java. This Sun's document describes how Java to Javascript communication works when using the Java Plug−in..> .6 Access Java variables from Javascript Current version of this HowTo : http://www.myApplet. 9. the preferred way is to use special "access method" to read Java variables (only String or integer)./javadetails/java−0171..myApplet.height and screen.rgagnon..<SCRIPT> function getScreenDimension() { alert("Screen Dimension\r\n width:" + document.... } </SCRIPT> <FORM> <INPUT type="button" value="call JAVA" onClick = "getScreenDimension()"> </FORM> <APPLET CODE="InJava2. 9. it's better to use screen.all.html Java variables can be used by giving the fully qualified name.width properties directly.5 Calling Java applets methods using DOM and JavaScript Current version of this HowTo : http://www.myMethod() You use the scriptable parameter if you call Java method from Javascript./javadetails/java−0346. <PARAM NAME="scriptable" value="true"> <PARAM NAME="mayscript" value="true"> . You use the mayscript parameter if you call Javascript function from Java.

9.html Netscape only.7 Call Javascript from a Java applet .rgagnon.applet.myApplet./javadetails/java−0172. you have to create a method in your applet class that calls the other class's method. import java.awt. import java.class" NAME="myApplet" HEIGHT=0 WIDTH=0> /APPLET/BODY/HTML Try it here Remember that IE4 can access only attributes and methods from a class derived from java.*.myApplet. If you want to call a method or use an attribute in another class.[Java applet] import java. using the javascript: protocol A Javascript function is called from Java by using the showDocument method. public String sJava = "String from JAVA".com/javadetails/. public class InJava3 extends Applet{ public int iJava = 123. } } [Javascript and HTML] <HTML><HEAD></HEAD><BODY> <SCRIPT> function JavaSays() { alert("Java says\n the value of iJava is :" + document.applet. public class InJava4 extends Applet{ public void init(){ String msg = "Hello from Java (using javascript alert)".getIntJava() + "\n" + "and sJava is :" + document. public int getIntJava() { return iJava.net. 9. } public String getStringJava() { return sJava.Applet. [Java applet] import java.*.applet. } </SCRIPT> <FORM> <INPUT type="button" value="Java says" onClick = "JavaSays()."> </FORM> <APPLET CODE="InJava3.getStringJava()).7 Call Javascript from a Java applet Current version of this HowTo : http://www.. A URL is needed with "javascript:" as the protocol.*.*.

Or you can execute function defined on the same page as the Applet.7 Call Javascript from a Java applet . C:\Program Files\Java\jre1.event. } </SCRIPT> <APPLET CODE="InJava4.*. you type in the TextField a Javascript function and press the button to execute the function.4.class" NAME="myApplet" MAYSCRIPT HEIGHT=10 WIDTH=10> </APPLET> </BODY> /HTML Try it here Netscape and IE ok. It can be found in the lib directory of your JRE installation. netscape. add(t). For example. public void init() { t = new TextField(20).4.showDocument (new URL("javascript:doAlert(\"" + msg +"\")")).awt. public class InJava5 extends Applet implements ActionListener { Button b.2 and later: add plugin.4.1: use jaws. b = new Button("execute Javascript"). using the netscape. e.g.*. import import import import java.*.try { getAppletContext().5. TextField t.javascript.javascript. The Applet must contains the MAYSCRIPT parameter to be able to use JSObject. java.jar to your classpath. Netscape and IE Ok. In the following example.0\lib\plugin.jar For Java 1.addActionListener(this).JSObject package How to compile when using the netscape.JSObject package ? For Java 1.jar (same directory). try alert('Hello from JAVA').awt.0/1.applet.*. add(b). } catch (MalformedURLException me) { } } } [Javascript and HTML] <HTML><HEAD></HEAD><BODY> <SCRIPT> function doAlert(s) { alert(s).javascript. b. java. } 9.

} if (success) System. /* JavaScript command */ String jsresult = null.length.getName().compareTo("getWindow") == 0) getw = ms[i].out.toString().*..getTargetException().getName(). else jsresult = result.getWindow(this). if (result instanceof String) jsresult = (String) result. } catch (Exception e) { jsresult = "" + e. Object result = eval. Class c = Class.7 Call Javascript from a Java applet . } } Object a[] = new Object[1]. Object jswin = null. i < ms. for (int i = 0.getText()). // Somewhere in the applet class . else if (ms[i].compareTo("eval") == 0) eval = ms[i]. eval = null. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 9. boolean success = false.. a[0] = this.lang.println("eval succeeded. consider making a small donation to show your support for this Web site and its content.reflect. If you find this article useful.println("eval failed with error " + jsresult).close()".javascript. else System.invoke(jswin. i++) { if (ms[i].public void actionPerformed(ActionEvent ae) { if (ae. } } } Try it here Another way is to use the Reflection API.eval(t. /* does it in IE too */ Method ms[] = c.. a).. String jscmd = "window. win. /* this is the applet */ jswin = getw. // posted by C Werner on the realhowto list import java..out.getSource() == b) { JSObject win = (JSObject) JSObject. That way you don't need to modify your CLASSPATH for compilation or even import the netscape.forName("netscape.jsobject package. a)..getMethods(). } catch (InvocationTargetException ite) { jsresult = "" + ite.invoke(c. /* this yields the JSObject */ a[0] = jscmd. success = true. try { Method getw = null. result is " + jsresult). .JSObject"). .

public class HtmlFromJava extends Applet implements ActionListener { Button aButton.document.awt. win. JSObject win = (JSObject)JSObject.write(s).1 Netscape/IE4 (win) OK] import import import import java. aButton.close(). netscape.com/javadetails/./javadetails/java−0173.open("about:"). } } } [Javascript and HTML] <HTML><HEAD></HEAD><BODY> <SCRIPT> function createHTML(s) { win = window.javascript.").document.getWindow(this). win.class MAYSCRIPT WIDTH=150 HEIGHT=150> /APPLET/BODY/HTML Try it here 9.* included with Netscape browser and IE4 (Win version). } public void actionPerformed(ActionEvent ae) { if (ae. } </SCRIPT> <APPLET CODE=HtmlFromJava.*. add(aButton).awt. java. java. See also this HowTo to learn how to compile with this package.rgagnon. [Java applet JDK1. HTML += "</BODY></HTML>".*.*.getSource() == aButton){ String HTML = "<HTML><HEAD></HEAD><BODY>". win. aButton = new Button("create HTML").applet..html We can use the netscape. public void init(){ setLayout(new FlowLayout()).eval("createHTML(\"" + HTML +"\"). HTML += "<TABLE BORDER=1><TR><TD>Hello world</TD></TR></TABLE>".8 Create dynamic HTML from a Java applet .event.9.8 Create dynamic HTML from a Java applet Current version of this HowTo : http://www.javascript.*.addActionListener(this).

import java.event.rgagnon.fromOtherFrame(a).f1.app2.fromOtherFrame(a).html You can use a Javascript function as a bridge between the 2 frames.9 Have Applets on different frames communicates with each other Current version of this HowTo : http://www.document. import java.app1.html" NAME="f2"> </FRAMESET> </HEAD> [frame 1 HTML (interframe1.*.class" NAME="app1" MAYSCRIPT HEIGHT=200 WIDTH=200> <PARAM NAME="target" VALUE="f2"> </APPLET></BODY></HTML> [frame 2 HTML (interframe2.f2.9. else parent.html)] <HTML><HEAD></HEAD> <BODY> <APPLET CODE="InterFrameDemo. target) { if (target == "f1") parent.java)] import java.awt.class" NAME="app2" MAYSCRIPT HEIGHT=200 WIDTH=200> WIDTH=200> <PARAM NAME="target" VALUE="f1"> </APPLET></BODY></HTML> [Java applet (InterFrameDemo.awt.document. [main HTML (interframe0.html)] <HTML><HEAD></HEAD> <SCRIPT> function toOtherFrame(a.*"> <FRAME SRC="interframe1. } </SCRIPT> </HEAD> <BODY> <APPLET CODE="InterFrameDemo. 9..html)] <HTML><HEAD></HEAD> <FRAMESET COLS="50%.com/javadetails/.*.*./javadetails/java−0174.html" NAME="f1" > <FRAME SRC="interframe2.applet.9 Have Applets on different frames communicates with each other .

b = new Button("To other frame").b).10 Send a message from an Applet to another Applet on a different page Current version of this HowTo : http://www.html decodes the search section and dynamically creates a new page containing the APPLET tag for SecondApplet and a PARAM with the message coming from FirstApplet.net. import netscape.toOtherFrame(\"" + tf. } } Try it here For a JAVA−only solution check this Java How−to 9.html FirstApplet encodes the message for SecondApplet in the search (or query) section of SecondApplet./javadetails/java−0181.getText() + "\". A simple script in SecondApplet. tf = new TextField(20).rgagnon.eval(js). FirstApplet. } public void actionPerformed(ActionEvent ae) { if (ae.10 Send a message from an Applet to another Applet on a different page . add("South".\"" + target + "\")". JSObject win = (JSObject) JSObject.import java.html URL.getSource() == b) { String js = "parent. Button b.html <HTML><HEAD></HEAD><BODY> <APPLET CODE="FirstApplet. tf).addActionListener(this).setText(s).com/javadetails/. } } public void fromOtherFrame(String s) { tf.getWindow(this). public class InterFrameDemo extends Applet implements ActionListener { TextField tf.javascript. win. b. public void init() { target = getParameter("target"). String target.*.println("to Javascript:" + js).out.f1.. add("North". System.class" HEIGHT=100 WIDTH=300> /APPLET/BODY/HTML 9.URL. setLayout(new BorderLayout()).

' ') // replace encoded chars by decoded chars if any theMessage = unescape(theMessage) html = '<APPLET CODE="SecondApplet. } strlen = document.html?" + "message=" + URLEncoder.substring(i + t. "SecondApplet.getSource() == b) { try { getAppletContext(). u) { i = s.length <s.search.strlen) // replace all '+" by space theMessage = replace(theMessage.*. public class FirstApplet extends Applet implements ActionListener { Button b. } } } } SecondApplet.10 Send a message from an Applet to another Applet on a different page .encode(t.substring(1 + 'message='.java import import import import java.showDocument (new URL(getCodeBase().*. s.substring(0. public void init() { add(new Label("Message to 2nd applet :")). '+'. java. r = "".class"' html += ' HEIGHT=100' html += ' WIDTH=400> ' 9.event. return r.location.length) r += replace(s. b. if (i == −1) return s. add(t= new TextField(20)).indexOf(t).addActionListener(this).printStackTrace().awt. if ( i + t.html <HTML><HEAD></HEAD><BODY> <SCRIPT> // from Javascript How−to general part 3.length if (strlen > 0) { theMessage = document. // replace all occurrence of token by another // in a string.getText()))).i) + u.*.awt.length.length).net. } catch (Exception e) { e. t. u). r += s. java. TextField t.location. java. } public void actionPerformed(ActionEvent ae) { if (ae. function replace(s.search // strip the "message header" theMessage = theMessage. add(b = new Button("Load 2nd applet")). t.FirstApplet.applet.length.*.

String s = getParameter("Message").myApplet. [InitHTMLForm.11 Retrieve values from a Java applet for HTML form (CGI) Current version of this HowTo : http://www. return true.*.applet.value = document.rgagnon. take a look at this Java How−to. add(tf).com/javadetails/.*. TextField tf = new TextField( 50 ). you have TextField in your Applet and // you want to transert its content to the HTML FORM // return myTextField. add (l).Applet { public String getFirstName() { // in real life. public class SecondApplet extends Applet { public void init() { Label l = new Label("Message from 1st Applet").11 Retrieve values from a Java applet for HTML form (CGI) .write(html) document.setText(s). tf.myForm.open() document.getFirstName().q. return "Real's HowTo".java import java. } } [HTML and Javascript] <HTML><HEAD> <SCRIPT> function getValueFromApplet(){ document.html += '<PARAM NAME="Message" VALUE="' + theMessage + '"> ' html += '</APPLET>' document.html Retrieve the value with a Javascript function called via the onSubmit event of the form./javadetails/java−0175.java] public class InitHTMLForm extends java. } } You can try it here! This method is useful when you need to pass the message to the SecondApplet via PARAM tag. 9.getText().close() document.applet. But if you don't need the PARAM tag. import java.awt.close() } </SCRIPT> /BODY/HTML SecondApplet. } 9..

To execute a Javascript only when an Applet is ready : <SCRIPT> function waituntilok() { if (document../javadetails/java−0176. <BODY onLoad="waituntilok().... } </SCRIPT> <FORM> <INPUT TYPE=button VALUE="Check applet" onClick="if (!isAppletReady(document.</SCRIPT> <BODY> <APPLET CODE="InitHTMLForm.12 Detect if an Applet is ready .rgagnon.google.html <SCRIPT> function isAppletReady(a) { return a.applets[0])) alert("not ready")..isActive().. } </SCRIPT> .class" NAME="myApplet" HEIGHT=0 WIDTH=0> </APPLET> <FORM ACTION="http://www."> .ca/search" NAME="myForm" onSubmit="return getValueFromApplet()"> <INPUT TYPE="hidden" VALUE="" NAME="q"> <INPUT TYPE="submit" VALUE="Submit" > </FORM> /BODY/HTML Try it here 9.5000) } } function doit() { .isActive()) { doit()."> /FORM An Applet is ready when it's loaded and its init() method is done..12 Detect if an Applet is ready Current version of this HowTo : http://www.. /BODY 9.myApplet. } else { settimeout(waituntilok()..com/javadetails/.

JSObject win = (JSObject)JSObject. // false if not loaded // in NS: isActive returns true if loaded.getMember("value"). value + " new stuff").eval("document.forms[0]. in Netscape.getWindow(this). Here a "browser friendly" solution from N.elements[0]"). Witteman to check if an Applet can be loaded (or found).By calling the javascript function from the BODY onLoad handler. PrivilegeManager.isActive) // in IE: isActive returns an error if the applet IS loaded. consume(). an error if not loaded. Like this..rgagnon. JSObject inputText = (JSObject) win. we can assume that the Applet is loaded. // stops further processing of the error } </SCRIPT> </HEAD> <BODY onLoad = appLoaded().javascript.html [Netscape AND IE4 compatible] The netscape.> <APPLET code=someClass. // so never reaches the next statement alert("IE: Applet could not be loaded"). <HTML> <HEAD> <SCRIPT LANGUAGE="JavaScript"> onError = errHandler.applets[0].setMember("value" . } function errHandler() { alert("NS: Applet could not be loaded"). you must PrivilegeManager. initiated and started.class codeBase=someURL height=50 width=300><PARAM NAME="bgcolor" VALUE="FFFFFF"> </APPLET> </BODY> /HTML 9.13 Read/Write HTML field values from JAVA Current version of this HowTo : http://www.enablePrivilege("UniversalBrowserWrite"). // read form value inputText. because we don't want IE // to do this./javadetails/java−0177. String value = (String)inputText.enablePrivilege("UniversalBrowserRead"). 9. // write form value But this action requires a signed applet.13 Read/Write HTML field values from JAVA . function appLoaded() { if (!document. only NS does.com/javadetails/.* (LiveConnect) package provides facilities to directly manipulate HTML FORM components. // Without he parentheses.

} if (ae. public class JSjava extends Applet implements ActionListener { Button b1. win. b2.forms[0]. tf. b2 = new Button("from FORM"). But there is a workaround. } } } [JSjava. b1 = new Button("to FORM").*.elements[0]. simply pass the informations through Javascript functions! [JSjava.elements[0]. } function setHTMLInputText(s){ document.*.awt. public void init(){ setLayout(new FlowLayout()).13 Read/Write HTML field values from JAVA .awt. java.*.addActionListener(this).getSource() == b2) { // receive FROM FORM JSObject win = (JSObject)JSObject.setText((String)win.add(b2). java. add(tf).javascript.getWindow(this).event.eval("getHTMLInputText().class MAYSCRIPT WIDTH=200 HEIGTH=200> /APPLET/BODY/HTML 9. TextField tf.addActionListener(this). b1. } </SCRIPT></HEAD><BODY> <FORM> <INPUT TYPE=text SZIE=20> </FORM> <APPLET NAME="JS" CODE=JSjava.")).value = s.").eval("setHTMLInputText('"+tf. tf = new TextField(10).getWindow(this).html] <HTML><HEAD> <SCRIPT> function getHTMLInputText(){ return document.value. JSObject win.forms[0].getSource() == b1) { // send TO FORM JSObject win = (JSObject)JSObject.applet.b2.getText()+"').before using an JSObject related to an HTML document. netscape.java] import import import import java.add(b1).*. } public void actionPerformed(ActionEvent ae) { if (ae.

rgagnon.event.rgagnon. } Someone at Netscape suggests a better way to check : function isJava11Available(){ if (java. else return false. 9. for reasons related to the fact that there's no way to tell if something is a valid package... check this How−to 9./javadetails/java−0180.1 (with event delegation) is available Current version of this HowTo : http://www.03).14 Detect if Java is enabled Current version of this HowTo : http://www.html This Applet uses the package netscape./javadetails/java−0178.16 Access Cookies from a Java Applet Current version of this HowTo : http://www.15 Detect if Java 1. To compile such program.1 is reported as the Java version.javaEnabled() ).html On some version of Netscape (eg./javadetails/java−0179. even if the JDK1.html from Javascript : function isJavaAvailable(){ return ( navigator.javaEnabled &navigator.zip for the Microsoft Internet Explorer.event.For best result.com/javadetails/. Here how you can detect if the patch has been applied.JSObject.awt.com/javadetails/.com/javadetails/. } because Unknown Java classes are reflected as JavaPackages.4.awt. you need to apply a special patch to upgrade to the event delegation model. Compile with something like 9. function isJava11Available() { if (java. you have to include in the CLASSPATH the file java40.14 Detect if Java is enabled .rgagnon. return false. never use LiveConnect JSObject in Applet's init() method.MouseEvent) return true.MouseEvent == "[JavaClass java/awt/event/MouseEvent]") return true.jar if you have the Netscape Communicator v4 installed or classes.javascript. } For an HTML solution. 9..

java.awt. %classpath% testcookie. b3. c.util.. java. add(b3).Calendar c = java. b3 = new Button("Delete Coookie").java NOTE: The netscape. good for 1 month */ java.add(java. java.MONTH. add(b2). public class TestCookie extends Applet implements ActionListener { TextField tf1. b1.util. add(b1). Button b1. tf2.applet.html)] <HTML><HEAD></HEAD><BODY> <APPLET CODE=TestCookie. b2. add(tf1).getInstance().*. b1 = new Button("Write Cookie"). expires=" + c.* package is now included in %JRE_HOME%\lib\jaws.java)] import import import import netscape. tf2 = new TextField(20). [HTML file (testCookie. } public void actionPerformed(ActionEvent ae) { if (ae.addActionListener(this).getTime().Calendar.jar file.util.*.event. 1).addActionListener(this). b2 = new Button("Read Cookie").*.javac −classpath .javascript.class MAYSCRIPT HEIGHT=150 WIDTH=200> /APPLET/BODY/HTML [Java applet (TestCookie.awt.14 Detect if Java is enabled .Calendar.*. add(tf2).toString(). "\program files\netscape\communicator\program\java\classes\java40. 9.println(s1).out.getText() + expires. System.addActionListener(this). String expires = ".javascript. public void init() { tf1 = new TextField(20).jar". b2. b3. String s1 = tf1. setLayout(new FlowLayout()).getSource() == b1) { /* ** write a cookie ** computes the expiration date.

println("Did not find cookie: "+name).indexOf(".getWindow(this).length() > 0) { int offset = myCookie.getSource() == b2) { /* ** read a cookie */ tf2.util. JSObject myDocument = (JSObject) myBrowser. if (myCookie.getText() + expires. myDocument.add(java. if (offset != −1) { offset += search. if (myCookie. expires=" + c. if (end == −1) end = myCookie.getMember("document").JSObject myBrowser = JSObject.length() > 0) return myCookie. s1). set the expiration in the past */ java. String search = name + "=".getInstance(). 9. s1).length(). String s1 = tf1. } return "?".Calendar c = java. return myCookie. String myCookie = (String)myDocument.getMember("document"). JSObject myDocument = (JSObject) myBrowser. int end = myCookie. JSObject myBrowser = JSObject.MONTH.util.length(). offset). } catch (Exception e){ e.setText(getCookie()). −1). String expires = ".toString(). ** not used in this Applet but can be useful */ String myCookie = getCookie(). JSObject myDocument = (JSObject) myBrowser.getWindow(this). } if (ae.". } public String getCookie(String name) { /* ** get a specific cookie by its name.setMember("cookie".getSource() == b3) { /* ** delete a cookie.util.setMember("cookie". parse the cookie.substring(offset.getMember("document").getWindow(this). } } public String getCookie() { /* ** get all cookies for a document */ try { JSObject myBrowser = (JSObject) JSObject. myDocument.14 Detect if Java is enabled .out. } if (ae.indexOf(search). c.printStackTrace().getTime().end).Calendar. } else System.Calendar.getMember("cookie").

class" HEIGHT=100 WIDTH=400> <PARAM NAME="first" VALUE="&{jsVar}. 9.} return "". See this text file with some useful Javascript functions for cookies handling."> <param name="second" value="&{jsFnct()}. add(new Label(getParameter("third"))).com/javadetails/. the MyApplet class import java. } } NOTE: Javascript entities are not supported in IE.awt. add(new Label(getParameter("second"))). javascript "entities" can be used to set calculated VALUES./javadetails/java−0182.html PARAM VALUE can't be changed ar run−time but during layout time. public class MyApplet extends Applet { public void init() { add(new Label(getParameter("first")))."> </APPLET> /BODY/HTML For demonstration purpose.17 Set Applet PARAM VALUE from javascript .*. VALUES are coming from a javascript variable. function jsFnct() { return "Hello World from jsFnct". Check this How−to to detect if Cookies are enabled or not. <HTML><HEAD></HEAD><BODY> <SCRIPT> var jsVar = "Hello World from jsVar".17 Set Applet PARAM VALUE from javascript Current version of this HowTo : http://www.. See this How−to for an example. a javascript function and a javascript expression.toUpperCase() + ' from js Expression'}.applet. } } You can try it here. In this How−to."> <param name="third" value="&{'hello world'. } </SCRIPT></HEAD><BODY> <<APPLET CODE ="MyApplet. 9.*. The workaround is to use the document.rgagnon. import java.write() method to customize the APPLET PARAM during layout time.

rgagnon. s = javaArray[0]. } public String getJavaArrayAsAString() { // you need more error checking here. NOTE : Reading a Java array from Javascript may crash your browser for some unknown reason.18 Pass an Array between Java and Javascript . The third button will modify the Java array.18 Pass an Array between Java and Javascript Current version of this HowTo : http://www.awt. } return s.util. the first button is used to read directly the Java array. i < k.*. } public void putJavaArray(String arrayAsAString) { int i = 0.. of course.html Javascript can read directly a Java Array but the other way don't seem be true./javadetails/java−0183. String s. "array 3" }.hasMoreTokens()){ javaArray[i++] = st. A Javascript array is transformed with the function join() and on the Java−side. i++) { s += "|" + javaArray[i] . a StringTokenizer will do the rest. then the Javascript function split() is used to retrieve the array.. The second button call a Java method which to transform the array as a string.com/javadetails/.*. int k. for (int i= 1 . "array 2" .nextToken(). "|"). In the following example. k = javaArray. So it's safer to use the next technique! A safe and simple way is to transform the Array as a big String with a known character used a separator. From there. } } } [HTML and Javascript] 9. import java. public String [] getJavaArray() { return javaArray. StringTokenizer st = new StringTokenizer(arrayAsAString.*. import java.9. [Java applet] import java. public class TestJavaArray extends Applet{ public String javaArray [] = { "array 1".applet.length. String s = "". it's trivial to do some manipulations to retrieve the array. while(st..

these functions won't work with IE (only with Netscape).lang.getJavaArray(). } function getJavaArrayAsAString() { var arrayAsAString = document. "ARRAY 3"). realJsString = arrayAsAString + "".copyJava(javaArray) // fill a javaArray with the elements from jsArray cast as java. } function putJavaArray() { arrayFromJs = new Array("ARRAY 1". Here an interesting piece of code submitted by M.join("|").length + "\r\n" + "element 2 is " + arrayFromJava[1]).copyJava() 9. Note the use of regular expressions to keep the code short and compact.myApplet. Since java classes are called directly by javascript."> </FORM> <APPLET CODE="TestJavaArray. } </SCRIPT> <FORM> <INPUT type="button" value="get JAVA array" onClick = "getJavaArray().String var javaArray2 = jsArray.<HTML><HEAD></HEAD><BODY> <SCRIPT> function getJavaArray() { arrayFromJava = document.getJavaArrayAsAString().length + "\r\n" + "element 2 is " + arrayFromJava[1])."> <INPUT type="button" value="get JAVA array (as a string)" onClick = "getJavaArrayAsAString(). "ARRAY 2". /* COPYJAVA (by Mike Caetano) Array prototype method to transfer array elements between javascript and java java array arg fills this empty js array with elements from java array empty js array assigns its elements to string cast java array Use: // fill empty jsArray with the elements from the java array as strings var jsArray = []."> <INPUT type="button" value="put JAVA array" onClick = "putJavaArray().18 Pass an Array between Java and Javascript .myApplet. arrayAsAString = arrayFromJs. jsArray.myApplet. alert("Java Array length = " + arrayFromJava.split("|").class" NAME="myApplet" HEIGHT=0 WIDTH=0> /APPLET/BODY/HTML Try it here. alert("Java Array length = " + arrayFromJava. arrayFromJava = realJsString. document. Caetano which does basically the same thing.putJavaArray(arrayAsAString).

length ) { temp[i] = ''+this[i++]. } return temp. The mypage. } // else invalid cast } // else invalid args } 9. even with the latest Netscape version.javascript. On IE3. something like showDocument("mypage.rgagnon.html?HelloJavascriptFromJava". typeof( [object Layer] ) => netscape. the LiveConnect package is not available. for example.Array.forName(type).charCodeAt(0)<91 ? 'java.Class.lang.this.' + type_: type_. On Mac.html Java−Javascript interaction is not possible on many browsers or platforms. return ( new java.. the interaction is very limited too. while ( i < this./javadetails/java−0184. } } else { if ( /^\bobject\b$/i. var size = !isNaN(Number(size_)) ? Number(size_) : 1. var i=0.lang.JSObject − for now just don't call copyJava on an array of objects −−−−−−−−−−−−−−−−−−−−−−−−−−−− */ function copyJava(arg_) { if ( /^\bnull\b$|^\bundefined\b$|^\s?$/i.size) ).reflect.size_) { if ( !/^\bnull\b$|^\bundefined\b$|^\s?$/i. } } } } } function makeJavaArray(type_.test(typeof(arg_)) ) { if ( this.test(arg_) ) { if ( this.test(type_) ) { var type = type_.19 Interaction without LiveConnect . "hiddenframe").newInstance (java.html page contains a javascript script to extract the parameter received in the URL (using the 9. } else { return null. while ( i < len ) { this[i] = ''+arg_[i++]. without LiveConnect or scripting support.19 Interaction without LiveConnect Current version of this HowTo : http://www.lang.length).length == 0 ) { var len = java. var i=0.getLength(arg_).com/javadetails/.Array.length > 0 ) { var temp = makeJavaArray('String'.test(type_) ) { if ( /boolean|byte|int|long|short|double |float|char|void|String|Object|Class|Thread/. From Java you do a showDocument() with a particuliar page passing the message as parameter to the hidden frame.javascript.Note: doesn't include cast for netscape. Java to Javascript One way to pass information from Java to Javascript.JSObject − that requires a more stringent type checking ie.lang. is to have an hidden frame acting as a bridge.reflect.

length > 0) { // replace all '+" by space theMessage = replace(theMessage.length) r += replace(s.i) + u. define the frameset with an invisible frame. And then the parameter extracted is send to another javascript function in the visible frame. r = "".parent. t.search property). [SimpleApplet."> </BODY></HTML> and finally the Applet (a JDK102 style. press a Button to send a string to a javascript to do an alert() with the TextField content. First. s.indexOf(t).Applet. '+'. if ( i + t.substring(i + t.showMessage(unescape(theMessage)) } } </SCRIPT> </HEAD><BODY onLoad="getAndSendMessage(). if (i == −1) return s.html contains the function to extract the parameter and call the showMessage() function in the visible frame. [SimpleJ2JS.html" border=0> <FRAME NAME="scriptFrame" SRC="invisiblepage.search. import java. r += s.document. <HTML><HEAD> <SCRIPT> function replace(s.length). return r.html" border=0> </FRAMESET> visiblepage.class WIDTH=150 HEIGHT=150> </APPLET></BODY></HTML> invisiblepage.awt. since we want to be friendly to older browsers). ' ') window.applet. The idea is to type something in a TextField. 9.19 Interaction without LiveConnect .substring(0.substring(1.java] import java.255) if (theMessage. u) { i = s. u).length < s. t. } function getAndSendMessage() { theMessage = document.html] <HTML><HEAD> <SCRIPT> function showMessage(s) { alert(s) } </SCRIPT> </HEAD><BODY><H1>Simple Java to Javascript interaction</H1><P> <APPLET CODE=SimpleApplet.location.HTML] <FRAMESET ROWS="100%.*"> <FRAME NAME="mainFrame" SRC="visiblepage.*.html contains the Applet and a javascript function.length. [visiblepage.mainFrame.

value } </SCRIPT> </HEAD><BODY><H1>Simple Javascript to Java interaction</H1> <FORM> <INPUT TYPE=input NAME=FromJs WIDTH=50 VALUE="HelloWorld"> 9.*"> <FRAME NAME="visibleFrame" SRC="visiblepage2.URLEncoder. sendButton = new Button("Send to Javascript").equals(sendButton)) { try { getAppletContext().location = "invisiblepage2. } public boolean action(Event e.html" border=0> <FRAME NAME="invisibleFrame" SRC="invisiblepage2. } } return true.html] <HTML><HEAD> <SCRIPT> function send2Java() { // you may need to encode the value with the escape() function parent. } } Try it here.getText())).net.URL (getCodeBase(). public void init() { aMessage = new TextField(20).html" border=0> </FRAMESET> The visible page [visiblepage2.html] <FRAMESET ROWS="100%.FromJs.encode(aMessage.showDocument (new java. "scriptFrame"). add(aMessage).printStackTrace(). "invisiblepage. Javascript to Java The idea here is to have an invisible Applet in an invisible frame that will receive a message (from Javascript in the visible frame) through the search part of its URL.invisibleFrame. Object o) { if (e.19 Interaction without LiveConnect .html?"+ java.forms[0]. the invisible Applet pass the message to the visible Applet by calling the appropriate function. } catch (Exception ex) { ex.target.public class SimpleApplet extends Applet { TextField aMessage.net.html?" + document. Then via a static pointer to the visible Applet. add(sendButton). Button sendButton. Frames definition [SimpleJS2J.

public class InvisibleApplet extends Applet { public void init() { String completeURL = getDocumentBase(). 9.indexOf("?"). public void init() { add(new Label("Message from Javascript ")). // put a pointer to this Applet in a static // variable which can be shared with the InvisibleApplet SimpleAppletRegistered. System. } public void setMessage(String msg) { aMessage. This pointer will be used by the InvisibleApplet.java] import java.class WIDTH=300 HEIGHT=150> </APPLET></BODY></HTML> The class to hold a static pointer to SimpleApplet2.awt. } } And finally the invisible page and InvisibleApplet [invisiblepage2.19 Interaction without LiveConnect . import java.<INPUT TYPE=button VALUE="Send to JAVA" onClick="send2Java().println("URL received : " + completeURL).*. [SimpleApplet2.java] public class SimpleAppletRegistered { static SimpleApplet2 sa.Applet.toString().java] import java.class WIDTH=1 HEIGHT=1> </APPLET> </BODY></HTML> [InvisibleApplet.html] <HTML><HEAD> </HEAD> <BODY> <APPLET CODE=InvisibleApplet. } The SimpleApplet2 is TextField which will be used to display the message type in the HTML FORM.Applet. aMessage = new TextField(20).setText(msg).applet. [SimpleAppletRegistered.out.sa = this. int i = completeURL.applet."> </FORM> <APPLET CODE=SimpleApplet2. add(aMessage). public class SimpleApplet2 extends Applet { TextField aMessage.

browse..substring(completeURL. Then the array is passed to a Java method.com/realhome/images shows a directory listing of the files in the images directory.master.sa. by doubleclicking on a line in the List. // call SimpleApplet via the static pointer // you may to decode the string here with // java. The listing is actually a real HTML page build on the fly.htm or default. NOTE: To send a message containing spaces and other special characters like &or ?.. With IE./selector. The invisible one will contains the directory listing. The directory doesn't contain a default page like index.href = ". In a browser.html. 2 visibles and 1 invisible. Frame visible #1 is for the Applet. The web server allows directory exploration.20 Directory listing on the Web server in a Java Applet . Links in a page are listed in the document property called links. SimpleAppletRegistered. 9.location./javadetails/java−0185.URLDecoder.html <HTML><HEAD> <SCRIPT> function reload_master() { window. Frames definitions Note that the 2 visibles frames are initially loaded with a "blank. } } } Try it here. For example.setMessage(msg). This property can be easily transform into a String array by a Javascript function. the corresponding images will be displayed in frame visble #2.decode() method.if (i > −1) { String msg = completeURL.html". 2. But here a way to do it with some help from Javascript. loading a URL with no file specified will return a directory listing under the following conditions : 1.html There is no way for an Applet to retrieve a directory contents without the help of server side process(servlet/CGI). Our applet will extract the links in this page and present them in a List.html" to allow the third frame (the invisible one) to be loaded with the directory content (here ".tactika. The Applet is very simple and can be customized to display more useful descriptions or filter some entries. We have 3 frames.20 Directory listing on the Web server in a Java Applet Current version of this HowTo : http://www.rgagnon. default. 9./images").html. you need to run this sample through a Web server.indexOf("?") + 1). the URL http://www.com/javadetails/.net. you will need to encode the message from Javascript (with the escape function) and decode the message in Java.

join("|").awt.contents.html <HTML<<HEAD><TITLE </TITLE></HEAD><BODY> </BODY></HTML> When all pages are loaded. java.} </SCRIPT></HEAD> <FRAMESET ROWS="35%. the selector. we trigger a Javascript function to transfer the Array to the Applet.65%. java. Javascript extracts links to the an Array.applet.document. } function putLinksIntoApplet() { AllTheLinksAsString = AllTheLinksAsArray. } </SCRIPT></HEAD> <BODY onLoad ="putLinksIntoApplet()"> <P ALIGN="center">Doubleclick to view <APPLET CODE=Selector.contents.*. AllTheLinksAsArray[i] = s. That page contains the Applet.awt.insertData(AllTheLinksAsString).html page is loaded into the first visible frame. java.Selector.html" NAME="detail"> <FRAME SRC=".List l. document.window./images" NAME="contents" NORESIZE> </FRAMESET> /HTML blank.event.class HEIGHT=100 WIDTH=400 NAME=Selector> <PARAM NAME="targetFrame" VALUE="detail"> </APPLET> </BODY> /HTML Selector. 9.length var AllTheLinksAsArray = new Array() // start at the second link because // we dont want the root directory for (var i = 1.net.*.awt.util. public class Selector extends Applet implements ActionListener { java.java import import import import import java. selector.20 Directory listing on the Web server in a Java Applet .links. java.*. i < LinksLength .html <HTML><HEAD> <SCRIPT> var LinksLength = parent.*..*.links[i]. i++) { s = parent.*" onLoad="reload_master()"> <FRAME SRC="blank. During layout time.html" NAME="master"> <FRAME SRC="blank. Via the BODY onLoad event handler.window.document.

21 Have a Java button close the browser window Current version of this HowTo : http://www.org 9.*. add(l = new java.setActionCommand("CLOSE")./javadetails/java−0282. l.hasMoreTokens()){ s = st. public class WinClose extends Applet implements ActionListener{ Button wc = new Button("Close me").addItem(s).awt. targetFrame = getParameter("targetFrame").*.javascript. String targetFrame = "".*. wc. String s. } public void actionPerformed(ActionEvent ae) { if (okToDisplay) { try { URL urlToDisplay = new URL(ae.awt. NOTE: This How−to is inspired by an article by Martin Webb on http://www.html import import import import java. add(wc).out. "|"). public void init() { wc.List(5).com/javadetails/.irt.showDocument(urlToDisplay. while(st. java.nextToken(). "Center"). java. l. public void init() { setLayout(new BorderLayout()). } 9. } catch (Exception e) { e.add(s).getActionCommand()).awt. targetFrame). getAppletContext().boolean okToDisplay = false..addActionListener(this).*. System. } } } public void insertData(String arrayAsAString) { int i = 0. // or l. StringTokenizer st = new StringTokenizer(arrayAsAString.printStackTrace().applet.21 Have a Java button close the browser window .event. netscape. } } You can try it here.rgagnon. } okToDisplay = true.addActionListener(this).println(s).

write("<APPLET CODE='MyApplet.rgagnon.awt. win.write(" <PARAM NAME='okToCookie' document. The value is passed to a Java Applet by create dynamically the APPLET tag.html] <HTML><HEAD></HEAD><BODY> <SCRIPT> document.close(). consider making a small donation to show your support for this Web site and its content. </SCRIPT> </BODY></HTML> VALUE=" + cookieOk + ">")./javadetails/java−0303.22 Detect if cookies are enabled Current version of this HowTo : http://www.22 Detect if cookies are enabled .cookie document. import java.java] import java.cookie. // check if cookie are enabled cookieBackup = document.html The detection is made by trying to write a cookie and reading it back.cookie = "cookie=yep" cookieOk = document.getWindow(this)..indexOf("cookie=yep") > −1 document. if (command.applet. public class MyApplet extends Applet { public void init() { add(new Label("Cookie enabled :")). [testcookie.getActionCommand().write("</APPLET>"). add(new Label(getParameter("okToCookie"))).com/javadetails/.equals("CLOSE")) { JSObject win = (JSObject) JSObject. } } If you find this article useful.cookie = cookieBackup document. [MyApplet.class' HEIGHT=100 WIDTH=400>").public void actionPerformed(ActionEvent e) { String command = e.*. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 9.").eval("self. } } } Try it here 9.*.

com http://www.visibility="visible" else document..all) mypage. </DIV> </BODY> </HTML> Written and compiled Réal Gagnon ©2007 real@rgagnon.html Place your page completely in a DIV tag. the DIV visibility attribute is set to true.com 9.23 Display a page after all applets are loaded .com/javadetails/. When the page is completely loaded...visibility="visible" } </SCRIPT></HEAD> <BODY onLoad="doIt().mypage./jsdetails/js−0071."> <DIV name=mypage style="visibility:hidden" > .rgagnon.9.rgagnon. Initially the visible attribute is false.style.23 Display a page after all applets are loaded Current version of this HowTo : http://www. <HTML> <HEAD> <SCRIPT> function doIt() { if (document.

*.servlet. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10 Servlet/JSP .rgagnon. HttpServletResponse res) { doPost(req.1 java−jsp 10. import javax.*.servlet.com/javadetails/.html You may to take a look to these related How−to's in the EAServer/Jaguar section..println("</body></html>").getWriter(). public class MyServlet extends HttpServlet { public void doPost(HttpServletRequest req. out. java. out.2 Read me Current version of this HowTo : http://www. out. res.10 Servlet/JSP 10.PrintWriter out = res.3 Get parameters passed to a servlet Current version of this HowTo : http://www. 10.println("the value is : " + valuePassed). consider making a small donation to show your support for this Web site and its content.rgagnon.getParameter("someValue").com/javadetails/. HttpServletResponse res) { // note : if "someValue" is missing a null is returned String valuePassed = req.io.html <HTML> <HEAD></HEAD> <BODY> <FORM METHOD=POST ACTION="/servlet/MyServlet"> value : <INPUT TYPE="TEXT" NAME="someValue"> </FORM> </BODY> </HTML> import javax./javadetails/java−0379. res)./javadetails/java−0357. } } If you find this article useful. } public void doGet(HttpServletRequest req.setContentType("text/html").http.println("<html><head></head><body>")..

println(" <INPUT TYPE=SUBMIT VALUE='Ok'>"). out.com/javadetails/.getParameterNames().getParameter(parm) + "<BR>"). out.getParameterNames().size().println("<BODY>").println("<BODY>"). if (!request.println(parm + " = " + request.hasMoreElements()) { String parm = (String)paramNames. out. HttpServletResponse response) throws ServletException.hasMoreElements()) { String parm = (String)paramNames. out. out.getWriter().4 Detect no argument condition in a Servlet Current version of this HowTo : http://www. consider making a small donation to show your support for this Web site and its content.println("<H1>Servlet</H1>"). out.html Servlet 2.println(" Subject<INPUT TYPE=INPUT NAME=subject>"). while(paramNames.. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10.getParameterNames(). java. out. IOException { PrintWriter out = response. out.nextElement().println(" Recipients<INPUT TYPE=INPUT NAME=to>")./javadetails/java−0341.nextElement().println("<FORM METHOD='GET' ACTION='Servlet1'>"). response.println("<HTML>").println("</BODY></HTML>").println("<HEAD><TITLE>MyServlet (with args)</TITLE></HEAD>").10. if (i = 0) { // no arguments } else { Enumeration paramNames = req.println("<HEAD><TITLE>MyServlet (no args)</TITLE></HEAD>"). out. // do something with this parm } } Previous version of the Servlet API protected void doGet (HttpServletRequest request.Enumeration paramNames = request.hasMoreElements()) { // no arguments out. } else { out.println("<H1>MyServlet</H1>").4 Detect no argument condition in a Servlet .util. out.println(" Message<INPUT TYPE=INPUT NAME=message>"). } out. while(paramNames. out. out. } } If you find this article useful.3 int i = req.setContentType( "text/html" ).getParameterMap().rgagnon.println(" </FORM>").

i<cookies. import javax.*. "mycookie_value")).6 Read a Cookie from a servlet Current version of this HowTo : http://www. import javax. consider making a small donation to show your support for this Web site and its content./javadetails/java−0358. HttpServletResponse res) { doPost(req. res). 10.*. if (theCookies != null) { java.servlet. i++) { Cookie aCookie = theCookies[i]. } } If you find this article useful.servlet.getWriter(). } } If you find this article useful.println ("Name : " + aCookie.html import javax.com/javadetails/.length.5 Set a Cookie from a servlet Current version of this HowTo : http://www.rgagnon./javadetails/java−0359.io. } } } public void doGet(HttpServletRequest req.PrintWriter out = res..http.getCookies(). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10. public class MyServlet extends HttpServlet { public void doPost(HttpServletRequest req.*.com/javadetails/.getValue()).getName() + " Value: " + aCookie.rgagnon. HttpServletResponse res) { doPost(req. HttpServletResponse res) { Cookie[] theCookies = request. res).*.servlet.5 Set a Cookie from a servlet . } public void doGet(HttpServletRequest req.html import javax.addCookie(new Cookie("mycookie_name". HttpServletResponse res) { res. public class MyServlet extends HttpServlet { public void doPost (HttpServletRequest req.10. consider making a small donation to show your support for this Web site and its content. for (int i =0.http.servlet.. out.

} then the browser will popup a dialog for username/password 10.setStatus(response.servlet.8 Ask for a password from a Servlet Current version of this HowTo : http://www.*.*. "theCookieValue").http. response.setMaxTime( 0 ). res)./javadetails/java−0360.rgagnon.setHeader("WWW−Authenticate".html import javax.html public void askPassword(HttpServletResponse response) { response../javadetails/java−0342.7 Delete (or expire) a Cookie from a servlet .servlet.com/javadetails/.7 Delete (or expire) a Cookie from a servlet Current version of this HowTo : http://www.setMaxTime( 300 ). HttpServletResponse res) { Cookie cookie = new Cookie ("myCookie". } } If you find this article useful.rgagnon.SC_UNAUTHORIZED). consider making a small donation to show your support for this Web site and its content.setMaxTime( −1 ). // Expire right now // cookie. "BASIC realm=\"protected−area\""). HttpServletResponse res) { doPost(req.Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10. import javax. // Expire in five minutes (5 * 60) cookie. public class MyServlet extends HttpServlet { public void doPost(HttpServletRequest req. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10. } public void doGet(HttpServletRequest req.com/javadetails/.. // Expire after the browser is closed // cookie.

pl (a PERL script) passing the parameters name and site.showDocument(cgiurl).pl". out.getOutputStream()).openConnection().com/cgi−bin/acgi.encode("Real Gagnon").writeBytes(encoded). c. URLConnection c = CGIurl. Here we calling a script called aCGI. URL CGIurl = new URL(theCGI).com/javadetails/. getAppletContext().getInputStream()).readLine()) != null) { // data from the CGI System.setDoOutput(true).rgagnon.10.com/cgi−bin/aCGI. 10. The POST method allows the programmer to manipulate the data received from the CGI. DataOutputStream out = new DataOutputStream(c. String theCGI = "http://www.pl?name=real).net.out. The client make a request and the server send back the result and close the connection.com/cgi−bin/aCGI. First a connection is made to the CGI. Each parameter is delimited by the character "Habitually the encoding is done through the static method encode of the java. BufferedReader in = new BufferedReader(new InputStreamReader(c..encode("Real Gagnon"). you call the CGI using the showDocument method (Applet). there is no difference talking to CGI or Servlet. Once the URL is constructed. String aLine.server. Then InputStream is created to receive the result. } You can't do some output then some input and do again some output. c.setUseCaches(false).println(aLine). out."application/x−www−form−urlencoded").setRequestProperty("content−type". You must do all the output and then the input. while ((aLine = in.URLencoder class.close(). spaces are changed to "+" and special character to hexadecimal using a 3−letter escape sequence. String encoded = "name=" + URLencoder. String theCGI = "http://www. There is no "dialog" between the client and the server.server. A typical URL talking to CGI using the GET method would be: new URL("http://www.9 Talk to a CGI/Servlet . Parameters are encoded. There is two ways to send a request to a CGI. String encoded = "name=" + URLencoder.flush(). c. out.pl?".9 Talk to a CGI/Servlet Current version of this HowTo : http://www. The GET method contains encoded parameters in the URL.server. an OutputStream is open to send the parameters (if any). URL cgiurl = new URL(thecgi + encoded).html From the client point of view. The CGI will process the result and produce a page to be displayed./javadetails/java−0082.

} out. ResultSetMetaData rsmd = rs.getRequestURI() +"?"+ paramName +"=bar" ).println("<TD>" + rs.. "world" ). out.10.rgagnon.servlet.*.html import javax. for (int i = 0. int columnCount = rsmd. } out.htm". i++) { out.com/javadetails/. import javax.sendRedirect(req.next()) { rowCount++. i < columnCount.getColumnLabel(i + 1) + "</TH>").sql.getColumnCount().getMetaData().println("<P ALIGN='center'><TABLE BORDER=1>").com/javadetails/. HttpServletResponse res) { if ( req.println("</TR>").io. } } 10.sendRedirect (( req.println("</TR>").getString(i + 1) + "</TD>"). successURI = "/success. public void doPost(HttpServletRequest req. } 10. paramName = "foo". // the data while (rs. i++) { out.getCookies()./javadetails/java−0374.servlet. java. i < columnCount.rgagnon.10 Test for Cookies .html private int dumpData(java.ResultSet rs.10 Test for Cookies Current version of this HowTo : http://www.*.length == 0 ) ? failureURI : successURI ) } public void doGet(HttpServletRequest req. } else { res.println("<TR>").addCookie( cookie ). res.htm".http. failureURI = "/failure. for (int i = 0. // table header out.getParameter( paramName ) == null ) { res.PrintWriter out) throws Exception { int rowCount = 0.println("<TH>" + rsmd.11 Display ResultSet data in an HTML Table in Servlet Current version of this HowTo : http://www. HttpServletResponse res) { doPost(req. out.println("<TR>"). public class Test4Cookies extends HttpServlet { private private private private static static static static final final final final Cookie String String String cookie = new Cookie( "hello" . res)./javadetails/java−0378..

html Say that your servlet called ""/servlet/GetFile" send back a file to a client request. A parameter received by the first servlet to the second one String requestVar = request.toString(textFile. File textFile = new File(filename). request.setHeader("Content−type". response.length())). If you do nothing. "Real's HowTo").com/javadetails/. myBean. For a simple string request.out. // open the file and write it in the OutputStream NOTE: For PDF output.setFooProperty("Real's HowTo").setAttribute("foo"..12 Specify the filename to be used for a file sent by a Servlet . requestVar).dat" . return rowCount.setAttribute("foo".html You set attributes on your request object and then forward the request object to the other servlet/jsp.setAttribute("foo". That file needs to be saved by the client.setHeader("Content−length".setHeader("Content−disposition"./javadetails/java−0401. consider making a small donation to show your support for this Web site and its content. request."inline.rgagnon./javadetails/java−0387. filename=" + filename ).println("</TABLE></P>"). the browser will suggest "GetFile" as the filename."application/octetstream").13 Pass information to another servlet/jsp Current version of this HowTo : http://www. A Bean MyBean myBean = new MyBean(). } 10.Integer. response. Then you forward the request 10.12 Specify the filename to be used for a file sent by a Servlet Current version of this HowTo : http://www. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10.com/javadetails/. response.getParameter("sitename"). myBean).. To specify the correct filename String filename = "abc. see this HowTo If you find this article useful.rgagnon.

Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10. If you find this article useful. consider making a small donation to show your support for this Web site and its content. consider making a small donation to show your support for this Web site and its content.size()). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10. and the ". CERT_KEYSIZE. • An additional thing that seems to help some IE browsers is to also have : response. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10.setHeader("Content−Disposition".rgagnon. Or you look at these HTTP headers : CERT_KEYSIZE . If you find this article useful.pdf").html Use the servlet request's isSecure() or getAuthType() methods. HTTPS_KEYSIZE Note: for a javascript solution see this HowTo If you find this article useful. ex.rgagnon.html public isDefined(HttpServletRequest req.com/javadetails/. response. like: http://x.14 Handle PDF output Current version of this HowTo : http://www./javadetails/java−0415./javadetails/java−0443.y. "inline.z/DoGenCompStmt?filename=dummy.forward(request. dispatch.getRequestDispatcher("next. consider making a small donation to show your support for this Web site and its content.rgagnon.filename=somepdf. so you need to give it a hint..15 Detect if the connection is via a secure channel Current version of this HowTo : http://www..pdf because IE ignores content−types. response). ex.setContentLength(bos.RequestDispatcher dispatch = request.html • Set the content−type of the response to "application/pdf". response.16 In a Servlet.jsp").com/javadetails/.14 Handle PDF output .pdf" extension is an easy way. check if Form Field is present Current version of this HowTo : http://www. • Add a dummy parameter on the end of the url./javadetails/java−0404.com/javadetails/.setContentType("application/pdf").. otherwise the Acrobat Reader plugin may not work properly. String fieldNameToSearchFor) { 10. • Set the "content−length" on the response.

.rgagnon. From JSP.17 Get the root dir of a web app .print( request. If you find this article useful. %> 10.18 Get client IP address from JSP Current version of this HowTo : http://www. In a Servlet String path = getServletContext.19 Output a binary stream from a JSP Current version of this HowTo : http://www./javadetails/java−0363..html In a JSP String path = application. it's a better idea to use a servlet. JSP pages were designed for *text* output.getRealPath("/"). only character stream should be used. consider making a small donation to show your support for this Web site and its content.getRemoteHost() ). like PDF or dynamically generated GIF./javadetails/java−0366.return req.com/javadetails/.17 Get the root dir of a web app Current version of this HowTo : http://www. consider making a small donation to show your support for this Web site and its content.com/javadetails/..getParameterMap().html <% out. out. } If you find this article useful.getRemoteAddr() ).com/javadetails/.rgagnon. which means it will play games with text encoding.getRealPath("/"). For binary output.html You can't. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10.containsKey(fieldNameToSearchFor).print( request. The "out" object is a Writer. 10. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10./javadetails/java−0519.rgagnon.

20 Use a connection cache from JSP Current version of this HowTo : http://www. you define the cache : 1.JCMCache jcmCache= null.getOutputStream(). java. byte[] buf = new byte[32 * 1024]. 0. NOTE: Java component can't use cached ODBC connection.write(buf.jcm. it's possible to modifed the output stream. while( (nRead=is.*" %> <%@page contentType="image/gif" %><% OutputStream o = response.getInputStream(). [image. If there is no JDBC driver available. % Thanks to Benjamin Grant for the bug fix. since a JSP will be converted to a servlet.sql. you need to use a cached JDBC connection. Define a regular System DSN (through the ODBC Administration panel) 2.jdbc..sql. // 32k buffer int nRead = 0.sybase.flush().net.odbc.jaguar.// *important* to ensure no more jsp output return. Cache Tab : checkbox cache−by−name checked <%@page contentType="text/html"%> <html> <head><title>JSP Page</title></head> <body> <%@ page import="java. Driver Tab : DLL or class name = sun. follow these steps: 1. String msg = "".com/javadetails/. try { jcmCache = 10. } o.jsp] <%@ page import="java.html Jaguar provides a very useful cache mechanism to speed up database requests. InputStream is = new URL("http://myserver/myimage.gif"). String jcmCacheString = "mycachename"./javadetails/java−0380.20 Use a connection cache from JSP .Having said that. But performance of such a bridge is poor and the reliability is not good in a multi−threaded environment. To define a cache using ODBC−JDBC (bridge) connection.close(). it's still possible to use the ODBC−JDBC provided by Sun. JDBC or Oracle cached connections.*" %> <%@ page import="java. In jaguar. o.read(buf)) != −1 ) { o. You can have ODBC.*" %> <% com. nRead).Connection dbConn = null.rgagnon. 10.JdbcOdbcDriver with JDBC radio button selected 3.io. General Tab : Server name = jdbc:odbc:YourSystemDSNName with user/pwd 2.

ResultSet rs = stmt.getMessage() + "<BR>").next()) { msg = rs..sql.close(). In this example.lookup("java:comp/env/jdbc/myconnection").rgagnon. javax.sql.sybase.html Web Application properties are defined in the WEB−INF/web.Connection con = ds.JCMCache. } } rs. java. while (rs.getConnection(com.jcm. } %> msgtext = <i><%= msg %></i> </body> </html> Instead of hard−coding the cache name into your java component.sql.getCacheByName(jcmCacheString).DataSource) ctx.naming./javadetails/java−0381.println("OUPS " + e.jcm.sql. make the name available through a Property (of the Environment) of the Web application.sybase. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10. Statement stmt = dbConn.executeQuery ("select msg from messages where msgid='00001'").jaguar. dbConn.com/javadetails/.prepareStatement(sql).21 Read a Web Application property .executeQuery().jaguar. java. This way your components are more flexible and you are using the "J2EE way" to make a connection.JCM. dbConn = jcmCache.JCM_WAIT).DataSource ds = (javax.InitialContext ctx = new javax. if(rs != null) { while(rs.21 Read a Web Application property Current version of this HowTo : http://www. consider making a small donation to show your support for this Web site and its content.sql.next()) { //do something } If you find this article useful.xml deployment descriptor (in between the <webapp> </webapp> tag) <env−entry> <env−entry−name>docPath</env−entry−name> <env−entry−value>c:/doc/doc1</env−entry−value> 10.com. java.InitialContext(). javax.getConnection().PreparedStatement stmt = con.naming. myconnection contains the cache name to be used. } catch (Exception e) { out.close().getString("msg").createStatement(). ResultSet rs = stmt.

com/javadetails/. String docBase = (String) env. Context env = (Context) new InitialContext().html Some JSP containers (as per section 8. bean).24 Precompile JSP pages Current version of this HowTo : http://www.rgagnon.String</env−entry−type> </env−entry> Then from your JSP or Servlet./javadetails/java−0410.company.MyBean bean=new com.rgagnon.String</env−entry−type> </env−entry> <env−entry> <env−entry−name>docUser</env−entry−name> <env−entry−value>net1</env−entry−value> <env−entry−type>java.4. String docBaseUser = (String) env.com/javadetails/..22 Use EJB from JSP .lookup("docUser").MyBean(1.22 Use EJB from JSP Current version of this HowTo : http://www.lookup("java:comp/env").html <%! public String sayHello(){ return "Hello".html EJB with constructor with no parameter <jsp:useBean id="myBean" scope="session" class="com.. } %> <%= sayHello() %> 10. 10. session. %> 10.company.23 Define a method in a JSP page Current version of this HowTo : http://www. 2.<env−entry−type>java. 10. 3./javadetails/java−0414.MyBean"/> EJB with constructor with parameters <% com.2 specification) support the capability of precompiling a JSP page.rgagnon..company.lang./javadetails/java−0396. 4).lang.2 of the JSP 1.com/javadetails/.lookup("docPath").putAttribute("myBean".

10. Here a JSP page that will scan the current directory (and subdirectories) to precompile all JSP found.java. ServletException { Set set = pageContext.HttpServletResponse response.jsp.</h4> </body> </html> NOTE: Many Application servers provide an utility to precompile JSP pages (ex.JSPs:</h4> <ul> <% HttpServletRequest req = new HttpServletRequestWrapper(request) { public String getQueryString() { // can be "jsp_precompile=true" return "jsp_precompile".servlet.getRequestDispatcher(uri). if (rd == null) { throw new Error(uri +" − not found"). access the page with a query string of ?jsp_precompile http://hostname.IOException"%> <%! private void compileAllJsps (PageContext pageContext.util.getServletContext().To precompile a JSP page.servlet. If the container supports precompilation.hasNext().charset=UTF−8" language="java" %> import="javax. response.Set. RequestDispatcher rd = getServletContext().http. }.next().java.io.jsp")) { out. %> </ul> <h4>Done. response). for (Iterator iter = set. JspWriter out. Check for a JSPC command file.jsp?jsp_precompile The JSP page will not be executed.*"%> import="javax.Iterator. BEAWLS). if (uri.servlet.javax. }.write("<li>"+ uri +"</li>").) { String uri = (String) iter.flush(). response.getResourcePaths(uripath). compileAllJsps(pageContext.*. HttpServletRequest request. iter. the JSP page will be compiled if necessary. String uripath) throws IOException.*"%> import="java. } } } %> <html><head><title>Precompiling *.util.endsWith("/")) { compileAllJsps(pageContext.include(request. <%@ <%@ <%@ <%@ page page page page contentType="text/html. } rd.JSPs</title></head> <body><h4>Precompiling *. out. req. EAServer. "/"). out. } else if (uri.iterator().endsWith(". out.com/mywebapp/mypage. request. uri).22 Use EJB from JSP .

rgagnon.length > 0) { for (int i = 0. consider making a small donation to show your support for this Web site and its content.25 Get a list of directories for JSP Current version of this HowTo : http://www. <% Hello h = new Hello().com/javadetails/./javadetails/java−0417.isDirectory()) { %> <li><a href="javadoc/<%=list[i]%>" target="_top"><%=list[i]%></a><br> <% } } } %> </ul> If you find this article useful. i++) { file = new java.25 Get a list of directories for JSP . 10. compile it. } } and I need to use it in many JSP pages using <%= say() %> They are many to achieve that goal : • Create a Java class with the method in it.File(root).io... and deploy the resulting .io. String[] list = dir.html I have a class public class Hello { public String say() { return "Hello".File file. if (file. if (list. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10.10.com/javadetails/. java.rgagnon.list().html <h1>Directories</h1> <ul> <% String root="c:/Repository/WebApplication/mydocs/javadoc/".io.io. java.class file(s) in your webapp's WEB−INF/class directory.length.File(root + list[i]). i < list.26 Use and share a class in JSP pages Current version of this HowTo : http://www.File dir = new java./javadetails/java−0508.

print(h.print(h.println("Hello").say()). place the method noted above in it.*.servlet.HelloTag</tagclass> </tag> </taglib> and to use the tag <%@ taglib prefix="ht" uri="WEB−INF/tlds/hello.tagext.io. TLD configuration (in the WEB−INF/tlds as hello.say()).jsp.inc).. } catch (IOException e) { } return SKIP_BODY.. out. <% Hello h = new Hello().tld" %> . %> • Create a JAR file containing the .class file(s) and deploy the resulting JAR file via your webapp's WEB−INF/lib directory.*. <ht:hello/> • Create the desired method at the top of the page and copy it from page to page <%! public static String say() { return "Hello". import javax.servlet.*. } } the resulting class should go in the WEB−INF/class directory.out. %> • Create a tag library for it. } %> • Create an "include file" (say hello. public class HelloTag extends TagSupport { public int doStartTag() throws JspException { try { pageContext. 10.inc" %> If you find this article useful. and include it at the top of each JSP page <%@ include file="hello.jsp.tld) <taglib> <tag> <name>hello</name> <tagclass>test. import javax. deploy it via the webapp's WEB−INF/tld directory. import java.getOut(). TAG source code TAG source code : package test.25 Get a list of directories for JSP . consider making a small donation to show your support for this Web site and its content.

consider making a small donation to show your support for this Web site and its content.com/javadetails/.Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10./javadetails/java−0519..getRealPath("/")./javadetails/java−0534.html In a JSP String path = application.28 Launch an applet from a JSP Current version of this HowTo : http://www. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10.class" width="500" height="300"> <jsp:params> <jsp:param name="message" value="Hello. Written and compiled by Réal Gagnon ©1998−2006 [ home ] 10. world"/> <jsp:param name="action" value="<%=AppletAction%>"/> </jsp:params> <jsp:fallback> <p> unable to start plugin </p> </jsp:fallback> </jsp:plugin> If you find this article useful.27 Get the root dir of a web app Current version of this HowTo : http://www. In a Servlet String path = getServletContext.rgagnon.getRealPath("/").rgagnon. consider making a small donation to show your support for this Web site and its content.html The jsp:plugin tag will generate the right html code to load your Applet.29 Prevent caching of a JSP output Current version of this HowTo : 10.com/javadetails/. If you find this article useful. <jsp:plugin type="applet" code="TestApplet.27 Get the root dir of a web app ..

rgagnon.30 Call another EJB . <% response. %> <HTML> <HEAD> </HEAD> <BODY> my page body </BODY> <HEAD> <META HTTP−EQUIV="PRAGMA" CONTENT="NO−CACHE"> <META HTTP−EQUIV="Expires" CONTENT="−1"> </HEAD> </HTML> NOTE: Pragma: no−cache prevents caching only when used over a secure connection.setHeader("Pragma".setHeader("Cache−Control".com/javadetails/.. response..30 Call another EJB Current version of this HowTo : http://www.setHeader("Cache−Control". response.com/javadetails/. −1).setDateHeader ("Expires". See http://support.class). 10."no−cache"). Object objref = ctx. response.http://www./javadetails/java−0384. %> However. response. MyEJBHome home = (MyEJBHome) PortableRemoteObject.html InitialContext ctx = new InitialContext().setHeader("Pragma"."no−cache"). −1).31 Keep java files generated from JSP (BEA WLS) Current version of this HowTo : http://www.com/javadetails/. return (MyEJB) home.html 10. cache handling is tricky with IE brower./javadetails/java−0590.narrow(objref.com/kb/q222064/.html You will need to set the appropriate HTTP header attributes..microsoft."no−cache").rgagnon.setDateHeader ("Expires". By adding a second HEAD is supposed to solve the problem! <% response. MyEJBHome. Expires: −1 should do the job over unsecure conection./javadetails/java−0446.lookup("MyPackage/MyEJB"). See also this HowTo and this one."no−cache").rgagnon. 10.create().

/javadetails/java−0449..version Thanks to Frederic Close for the tip! If you find this article useful.xml to 'true' <jsp−descriptor> <jsp−param> <param−name> keepgenerated </param−name> <param−value> true </param−value> </jsp−param> </jsp−descriptor> or.%> ... consider making a small donation to show your support for this Web site and its content.jsp If you find this article useful.32 Get the server version (BEA WLS) .common.rgagnon. consider making a small donation to show your support for this Web site and its content.html <%@page import = "weblogic.getImplementationVersion()% or from the command line java −cp weblogic..jar weblogic. follow these steps : 1. %=serverVersion.com/javadetails/.rgagnon. java weblogic. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10.cmd 10..jspc −keepgenerated Your.internal.32 Get the server version (BEA WLS) Current version of this HowTo : http://www. Open a Shell window in %BEA%\user_projects\domains\[mydomain]\applications 2.\setenv./javadetails/java−0447.com/javadetails/.theOne(). Run this script : ..33 Quickly create a Web application with BEA WLS Current version of this HowTo : http://www. with weblogic..html To create a web application without an EAR or WAR.VersionInfo"%> .jar in the classpath.Set the 'keepgenerated' parameter in weblogic. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10. <%VersionInfo serverVersion = VersionInfo.

. a sample web. Type this command : md testapp 4. // assume something like http://.xsl"?> .0" encoding="UTF−8"?> <?xml−stylesheet type="text/xsl" href="tree−view. // get the PARAM=??? (assumes you have used GET request method!).XML informations Current version of this HowTo : http://www.marathon./docxml.) which accepts as a parameter an XML filename and transforms the passed filename using the XSL. charset=ISO8859−1"> <%@ LANGUAGE="JScript" %> <% Response.buffer = true. See the sample output if your browser supports XML/XSL transformation. Attach the xsl to the xml by adding this line to the xml file : <?xml version="1. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10.com/javadetails/.xml file contains informations about a web application hosted by a application server.. the css file. or do the transformation in Java. var SrcXSL. Here an ASP page (yeah I know. for a hint see this How−to.. While it's possible to consult the data using a regular text editor..xml xmlfile = '' + Request.marathon. I found a nice generic stylesheet on the Web and adapted it a little bit for that purpose.WebInit testapp and that's all. // get the source file (XML and XSL) paths 10. Here the modified xsl file. Run this program : java weblogic..34 Nicely display WEB. var oXML.ddinit. it maybe easier to use a special stylesheet to nicely format the data for easy browsing. var xmlfile.QueryString('xmlfile'). var SrcXML.. consider making a small donation to show your support for this Web site and its content.xml.rgagnon. To configure your new application. var oXSLTemplate.3. <META http−equiv="Content−Type" content="text/html.XML informations .34 Nicely display WEB. Type this command : md testapp\WEB−INF 5. As an added bonus.. var oXSL. run this program java weblogic. var oXSLProcessor..html A web./javadetails/java−0451..asp?xmlfile=myxml. the original XML filename is displayed (you will need this XSL).Main testapp If you find this article useful.

SrcXML = Server.url + ' is not valid.. oXML. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 10.CreateObject('Msxml2.stylesheet = oXSL..DOMDocument'). // load the XML and XSL into your documents./javadetails/java−0551.xmlfile. Weblogic loads a class by asking the parent classloader to load the required class. consider making a small donation to show your support for this Web site and its content.. // create documents for the XML and XSL.xml in the WEB−INF directory with the content : <!DOCTYPE weblogic−web−app PUBLIC 10. // tell the XSL processor of the XML you want to have transformed. Response.35 Reverse the CLASSLOADER order (BEA) Current version of this HowTo : http://www.async = false .. create a file called weblogic. oXSLTemplate = Server. oXSLTemplate. oXML.com/javadetails/.html By default.CreateObject('Msxml2.MapPath(xmlfile). oXSLProcessor = oXSLTemplate. Reason: ' + e. oXSLProcessor. ref : WebLogic Server Application Classloader Overview To make sure that your web app will use the JAR located in its WEB−INF\LIB.rgagnon.reason ).output).write(oXSLProcessor. // we don't want to waste time validating the file oXSL. oXSLProcessor.''). // place the ?xmlfile=xxx value into the XSL processor.transform .load(SrcXSL).validateOnParse = false .input = oXML. } % If you find this article useful. } catch (e) { Response. oXML = Server.. oXSL = Server.resolveExternals = false .xsl').write ('The file ' +e.load(SrcXML).createProcessor..35 Reverse the CLASSLOADER order (BEA) . oXML. This can be a problem. SrcXSL = Server. try { oXSLProcessor..FreeThreadedDOMDocument'). // create the XSL template and processor...addParameter('xmlfile'..XSLTemplate').MapPath('xmldoc/tree−view2..CreateObject('Msxml2. if you have a JAR version in the server LIB directory and your web app requires an another version. oXML.

BEA WLS doesn't recompile a modified JSP. Written and compiled Réal Gagnon ©2007 real@rgagnon. Inc.com http://www.36 Detect change in JSP and recompile (BEA) Current version of this HowTo : http://www.com 10."−//BEA Systems. You change this behaviour by adding this directive in a weblogic. Dependencies are also checked and recursively reloaded if changed.bea.xml configuration file.dtd"> <weblogic−web−app> <container−descriptor> <prefer−web−inf−classes>true</prefer−web−inf−classes> </container−descriptor> </weblogic−web−app> 10.//DTD Web Application 8.rgagnon.com/javadetails/.html By default. If set to 0. if you deployed an application in exploded mode. page checking and recompiling is disabled. at which WLS checks to see if JSP files have changed and need recompiling. If set to −1.36 Detect change in JSP and recompile (BEA) . in seconds. <jsp−descriptor> <jsp−param> <param−name>page−check−seconds</param−name> <param−value>60</param−value> </jsp−param> </jsp−descriptor> page−check−seconds sets the interval. pages are checked on every request.rgagnon.com/servers/wls810/dtd/weblogic810−web−jar../javadetails/java−0562.1//EN" "http://www.

com Easerver and Powerbuilder • news.software.eclipse.php.4 (exampledepot.org Eclipse.2 * Read me * Current version of this HowTo : http://www.comp.mozilla.gmane..html If you can't find what you are looking here.* • news. Specialized server from vendors can be accessed to obtain support : • forums. Usenet's newgroups are very useful too.org/newsgroups/register.org Netbeans. need to ask for username first at http://www. look for the hierarchy gmane.1 java−language 11.java.sybase. Check out the comp.eclipse.org Mozilla • msnews.rgagnon.java.netbeans.* groups on your favorite Usenet newserver.bea./javadetails/java−0290.com Microsoft • news.com) Sun Developers Online Community Also check out my Java links page. you may want to look at these other sites : Java Glossary The Java Developers Almanac 1.11 Language 11. • news.microsoft.com IBM (WebSphere) • newsgroups.com BEA WebLogic 11 Language .ibm.lang.com/javadetails/.

println (resultArray[0] + ". array1)."2".*.11. With an arbitary key.com/javadetails/.io. System.forName(aClass). aMethod = lineInput("Method: "). arrays.html Hashtables are very useful for maintaining a 1−to−1 relationship between Objects. we retrieve a String array with a String.put("Array2".com/javadetails/.nextElement()./javadetails/java−0027./javadetails/java−0032.4 Scan the content of a hashtable Current version of this HowTo : http://www. public class TestReflect { public static void main(String s[]) throws Exception{ String aClass. while (true) { aClass = lineInput("\nClass : ").*.put("Array3". array3). array2). " + resultArray[1] + ". } 11. arrays. Object value = hash. String[] array1 = {"A".rgagnon.3 Use a Hashtable . String[] array3 = {"1".get(key).. // we assume that called methods have no argument Class params[] = {}.put("Array1".html Enumeration keys = hash. 11..lang.keys().reflect./javadetails/java−0031."C"}. In the following example.hasMoreElements() ) { Object key = keys. import java."Y". String aMethod."3"}."Z"}. Hashtable arrays = new Hashtable().5 Call a method dynamically (Reflection) Current version of this HowTo : http://www. 11.rgagnon. while( keys.com/javadetails/.. String[] resultArray = (String[])(arrays. " + resultArray[2]).get("Array2")). String[] array2 = {"X".rgagnon. // get the Class Class thisClass = Class.out. you can retrieve easily an Object.html import java. arrays. Object paramsObj[] = {}."B".3 Use a Hashtable Current version of this HowTo : http://www.

Date Method: getTime 1186852732140 */ } public static String lineInput (String prompt) throws IOException { BufferedReader input = new BufferedReader(new InputStreamReader(System. new Class[] {String. } } The next example calls a class method with 2 arguments : import java. System. String aMethod.newInstance(). } /* Output examples: Class : Class1 Method: class1Method2 ### Class 1. /* output : Hello World */ } public static void invoke (String aClass.// get an instance Object iClass = thisClass. public class TestReflect { public static void main(String[] args) throws Exception { TestReflect.out.print(prompt).Date Method: toString Sat Aug 11 13:18:39 EDT 2007 Class : java. } } class Class1 { public String class1Method1() { return "*** Class 1.out. params). paramsObj). "say". // get the method Method thisMethod = thisClass.3 Use a Hashtable . 11. Method2 ### Class : java. return input.class.util. Method2 ###".class}.lang. new Object[] {new String("Hello").*. } public String class1Method2() { return "### Class 1.forName(aClass).reflect. String.invoke(iClass.in)).readLine().util.getDeclaredMethod(aMethod. Class[] params. Object[] args) throws Exception { Class c = Class. new String("World")}).println (thisMethod. Method1 ***". // call the method System.toString()).invoke("Class1".

invoke(i. public class Test { public static void main(String args[]) { try { String name = "java.printStackTrace().rgagnon. // get String Class Class cl = Class.println(s1 + " " + s2). Class cl = Class.com/javadetails/. args).getConstructor(classParm). // the method has no argument Class arguments[] = new Class[] { }. Object i = c./javadetails/java−0351. 11. params).MyClass".Constructor constructor = cl.forName(name).lang. but this time we are passing a parameter to the constructor and calling a method dynamically. Class [] classParm = null. return co.out. Object r = m.reflect.Constructor co = cl.newInstance (new Object[]{"REAL'S HOWTO"}).forName(name).lang.rgagnon. try { String name = "com. return null.lang. } } 11. } Another example. } } class Class1 { public void say( String s1. // get the constructor with one parameter java.reflect. } catch (Exception e) { e.getConstructor (new Class[] {String.newInstance(objectParm).*. String s2) { System.getDeclaredMethod(aMethod.lang. Object [] objectParm = null.reflect.6 Create an object from a string .class}).String".Method m = c.newInstance(). java.html import java..6 Create an object from a string Current version of this HowTo : http://www. // create an instance Object invoker = constructor. String methodName = "toLowerCase".

toString().getField(lookingForValue).1416 42 Hello world */ } public static Object getValueOf(Object clazz.reflect."thirdValue")). String lookingForValue) throws Exception { Field field = clazz.getValueOf(test.equals("double")) return field. } } } 11.out.. public class ReflectUtils { public static void main(String[] args) throws Exception{ TestClass test = new TestClass().html import java./javadetails/java−0038. // convert "REAL'S HOWTO" to "real's howto" Object result = objMethod.get(clazz)..println (ReflectUtils.// get the method java. System. thirdValue = "Hello world".7 Get a variable value from the variable name . arguments).equals("int")) return field.lang. if (clazzType. System.println (ReflectUtils.toString(). // else other type . } catch (Exception e) { e. 11.*.Method objMethod = cl.getValueOf(test.getInt(clazz). (Object[])arguments). /* output : 3.7 Get a variable value from the variable name Current version of this HowTo : http://www.println(result).1416.printStackTrace(). System. secondValue = 42. else if (clazzType.getValueOf(test.reflect.out.println (ReflectUtils.invoke (invoker.out. System. } } class TestClass public double public int public String { firstValue = 3.lang.getMethod(methodName.out.com/javadetails/.getClass()."secondValue")).getDouble(clazz)..getType().rgagnon. Class clazzType = field. // and finally return field."firstValue")).

} } The above example is used when the class is hard−coded.forName(name).} } } 11.html While you can exec("java myaotherapp").out. new Object[] {new String[] {}}). // if you need parameters // String[] args = new String[] { "Hello". new Program1b().println("Hello from Program2").rgagnon.class}. public class Program1b { public static void main(String arg[]) { System. } catch(Exception e){ e.8 Launch an application from another application . take this simple application : public class Program2 { public static void main(String arg[]) { System.println("Hello from Program1b"). } } To call the above application from another public class Program1a { public static void main(String arg[]) { System.println("Hello from Program1a").} }.out. For example. new Thread(){ public void run() { Program2./javadetails/java−0394. The dynamic version is little more tricky.printStackTrace().main(new String[]{}).execute("Program2").8 Launch an application from another application Current version of this HowTo : http://www. params). } public void execute(String name) { Class params[] = {String[].. it is more appropriate to instanciate and called the main method of the other application.com/javadetails/. "world" }. try { Class.} 11.out.start(). invoke(null. getDeclaredMethod("main".getClass() }). // Class params[] = new Class[] { args.

String todayClass = "z_" + todayMillis.compileIt()) { System.getTime()).main(new String[]{}).out.*. } } The output : C:\>java Program1a Hello from Program1a Hello from Program2 Hello from Program2 Hello from Program2 Hello from Program2 Hello from Program1a 11.println("Hello from Program2").out. } } [Program1a.out.start().io. public class MakeTodayClass { Date today = new Date().out. String todaySource = todayClass + "./javadetails/java−0039. [Program2. compile and call Current version of this HowTo : http://www.java] public class Program1a { public static void main(String arg[]) throws Exception{ System.createIt().} }.toString(today.join().html import java.println("Hello from Program1a"). t1.todayClass + ":\n\n"). String todayMillis = Long. System.*. if (mtc. compile and call .lang. import java. mtc. } else 11. t1.9 Create a java source dynamically.reflect.9 Create a java source dynamically.println("Hello from Program1a").println("Hello from Program2").java".runIt().java] public class Program2 { public static void main(String arg[]) { System.println("Running " + mtc. mtc.out. System.println("Hello from Program2"). System..out.util.out. System.rgagnon.Launch many programs using Thread and use join() to wait for the completion. public static void main (String args[]){ MakeTodayClass mtc = new MakeTodayClass(). Thread t1 = new Thread(){ public void run() { Program2. import java.*.com/javadetails/.println("Hello from Program2").

tools.flush(). } public void runIt() { try { Class params[] = {}. true). Object iClass = thisClass.write(" }}\n").javac.write(" System. aWriter.printStackTrace().compile(source). } } public boolean compileIt() { String [] source = { new String(todaySource)}."). } catch (Exception e) { e.compile(source).out. new sun. } catch(Exception e){ e.close().printStackTrace(). aWriter.toString().tools.forName(todayClass).javac.write("public class "+ todayClass + "{").10 Access the enclosing class from an inner class Current version of this HowTo : http://www. return (baos.write(" public void doit() {"). /* output : Hello world! */ } public void doit() { new InnerClass().getDeclaredMethod("doit".sayHello()..html public class TestIt { public static void main(String a[]){ new TestIt().source[0]).rgagnon. } public void enclosingClassMethod(){ 11. Class thisClass = Class. params). aWriter.println(\""+todayMillis+"\").3 then use // public static int com.newInstance().invoke(iClass.doit()./javadetails/java−0037.println(mtc. // if using JDK >= 1.Main(baos. Object paramsObj[] = {}.todaySource + " is bad.indexOf("error")==−1).10 Access the enclosing class from an inner class . thisMethod. paramsObj). aWriter.").out. Method thisMethod = thisClass. aWriter. } public void createIt() { try { FileWriter aWriter = new FileWriter(todaySource.Main. } } } 11.sun. ByteArrayOutputStream baos= new ByteArrayOutputStream().System.com/javadetails/. aWriter.

doit().html public class TestIt { public static void main(String[] args) { Outer outer = new Outer().enclosingClassMethod().11 Access inner class from outside .System.out.println("Hello world!").11 Access inner class from outside Current version of this HowTo : http://www. /* output : Hello from Inner() */ } } class Outer { public class Inner { public void hello(){ System. public static void main(String a[]){ new TestIt(). } } } or public class TestIt { TestIt testItClass = this. } class InnerClass { public void sayHello() { TestIt.new Inner().println("Hello world!"). 11. } public void enclosingClassMethod(){ System. } class InnerClass { public void sayHello() { testItClass. /* output : Hello world! */ } public void doit() { new InnerClass().hello().out.rgagnon../javadetails/java−0425.out.com/javadetails/. } } } 11.enclosingClassMethod().sayHello().println("Hello from Inner()"). outer.this.

driver./javadetails/java−0040... .12 Use globally defined constants . An application−level class needs to implement the interface to be able to see the constant definitions. } .12 Use globally defined constants Current version of this HowTo : http://www.. there is no need to instantiate the class. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11. setTitle(APPNAME). To use a constant.. then to use a constant.} } } If you find this article useful.[constant name] if (myMethod()==CONSTANT. Since the members of the class are defined as "static".html Via a class This technique is useful for constants defined on a corporate level.SUCCESS) { . They are very generic by nature. integer NOTFOUND = 0. The CONSTANT class is included in the classpath.. APPVERSION = "version 1. } else { .. } Via an interface This technique can be used if the constants are not really global but especially designed to be used in a specific application for example. consider making a small donation to show your support for this Web site and its content.0".rgagnon.jdbc. simply implement the interface public class TheAppFrame extends Frame implements APPCONSTANT { TheAppFrame { .com/javadetails/.. 11. public class CONSTANT public static final public static final public static final } { integer SUCCESS = 1. integer FAILURE = −1. public interface APPCONSTANT public static final String public static final String public static final String } { APPNAME = "The Super APP". simply use CONSTANT.OracleDriver"...... DBDRIVER = "oracle..

Then rename main to main_serialize and main_reload to main and compile. First the Queue state is saved to a file. it must implements the Serializable interface.util.} NOTE : This is not considered as good practice (depending on who you are talking to!) to use an interface this way. } } If you find this article useful. import static java.13 Serialize an Object . Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11.13 Serialize an Object Current version of this HowTo : http://www. // System.ObjectOutputStream out) throws IOException private void readObject(java.*. System. we use a Vector to simulate a Queue.rgagnon.abs(x)). // instead of System.println(Math. constant name are always in CAPITALS.0. import java. JDK1.out. ClassNotFoundException.com/javadetails/.5 JDK1./javadetails/java−0042.out.*.io.println(abs(x)).out.println(Math.PI). public class Queue extends Vector { /* 11. The object needs 2 functions with these signatures private void writeObject(java.println(PI).lang. NOTE: By convention.Vector. In the following snippet.html To serialize an object.out.. import java.Math. System. Now the snippet read the file to reload the Queue from the data previously saved. Many standard Java objects already implements the Serializable interface so there is almost nothing to do.io.io.5 import statement can be used to import only static member from a class.ObjectInputStream in) throws IOException. consider making a small donation to show your support for this Web site and its content. public class DemoImport { public static void main(String[] args) { double x = 16.

theQueue = (Queue) ois.printStackTrace(). // serialize the Queue System.out.put("element 3").writeObject(theQueue).printStackTrace().put("element 4"). ois.println("unserializing theQueue"). try { FileInputStream fin = new FileInputStream("thequeue. oos.out.println(theQueue. } catch (Exception e) { e. } System. theQueue.toString()). // unserialize the Queue System.put("element 2").println("serializing theQueue").put("element 1"). return o.close().readObject(). } } Note : See this How−to to serialize using XML format.toString()). theQueue.dat"). theQueue = new Queue().dat"). System. return firstElement(). ObjectOutputStream oos = new ObjectOutputStream(fout). theQueue.** FIFO */ Queue() { super(). } Object peek() { if (isEmpty()) return null.out. ObjectInputStream ois = new ObjectInputStream(fin). } } public static void main_load(String args[]) { Queue theQueue. theQueue. } Object get() { if (isEmpty()) return null. removeElement(o).close(). } public static void main(String args[]) { Queue theQueue. 11.13 Serialize an Object . } catch (Exception e) { e. } void put(Object o) { addElement(o). try { FileOutputStream fout = new FileOutputStream("thequeue.println(theQueue. Object o = firstElement(). theQueue = new Queue().out. oos.

since Debug. when you need some debugging codes. the Debug class looks like this: public class Debug { public static final boolean RELEASE = false.RELEASE) { System.14 Serialize an Object over a socket Current version of this HowTo : http://www.com/javadetails/.html Unlike a C/C++ compiler. oos. the code in the if statement will not be included in the compilation./javadetails/java−0043.15 Easily remove my debugging code Current version of this HowTo : http://www. you open a Socket and then oos = new ObjectOutputStream(socket. That's because Java keeps objects sent in an internal cache and the old version will be taken in account instead of the new one.. public class Debug { public static final boolean RELEASE = true. you have a class called Debug. you use the ObjectInputStream.rgagnon. there is no JAVA compiler directive to exclude certain source code parts from compilation. } During compilation. On the server side. but the execution time will be a little faster too by not making unnecessary test. In the production environment.getOutputStream()).11.println("The value of i is " + i).html From the client side. Not only the resulting class will be smaller. Without editing the source to remove the debugging codes./javadetails/java−0130. the loading process will faster.14 Serialize an Object over a socket .RELEASE is always true.out. 11. you included them in a if statement like if (Debug. you will not see a change on the server side. By making the release version of a class smaller. the code will be present. The fix is to do an ObjectOutputStream. you can rely on the simple optimization that the JAVA compiler always do.rgagnon.readObject method. If a if expression is always false.com/javadetails/. NOTE: If the OutputStream is kept open and you modify your object and resend it. The technique is simple.writeObject(someObject). } 11.. } In your source.reset() before re−sending the object or open a new connection each time. In the development environment.

System.getName() + " is loaded from " + this.println("This class (FromWhere) is located at : " + u).html public class LoadingFromWhere { public static void main(String args[]){ LoadingFromWhere s = new LoadingFromWhere(). // may want System.println() will be present in your class but the output is disabled). } } class MyClass { MyClass() { System. } } The output >java LoadingFromWhere LoadingFromWhere is loaded from file:/C:/temp/ MyClass is loaded from file:/C:/temp/ Other technique (doesn't work with jar) public class FromWhere { public static void main(String args[]){ Class theClass = FromWhere.err. } public void doit() { System.out.URL u = theClass.When compiling in that environment. (System. public class TestOut { public TestOut() { } public static void main(String s[]) { System.net.release is always false. i++){ System.rgagnon.getLocation()).out.getClass()./javadetails/java−0300. Another way is to simply close the out stream. } } 11.getCodeSource().out. i <100000.print(".getClass().println (this.getCodeSource().getClass().").close() too for (int i=0. s.getProtectionDomain().println(this.com/javadetails/.16 Obtain from where a Class is loaded ..getResource(""). MyClass s = new MyClass().} } } 11. java.class.getProtectionDomain().getName() + " is loaded from " + getClass().close().out.out.out.16 Obtain from where a Class is loaded Current version of this HowTo : http://www.getLocation()).doit(). the debugging code will be absent from the class file since Debug.

11./javadetails/java−0420.The output > java FromWhere This class (FromWhere) is located at : file:/C:/temp/ See these related HowTo's : 1 2 11.html public class ClassFromStatic { public static void main(java.getMethodName()). it is expensive since we need to create an Exception.18 Get the current method name Current version of this HowTo : http://www.4 public class MyTest { public static void main(String args[]) { new MyTest().getClassName() + " class"). } public void doit() { System.out.5 While the above snippet is not bad.getName(). } public static class CurrentClassGetter extends SecurityManager { public String getClassName() { return getClassContext()[1].17 Get the class name in a static method Current version of this HowTo : http://www.println (new Exception().println ("I'm in " + new CurrentClassGetter().getStackTrace()[0].html JDK1. } } The output doit JDK1. } } } 11./javadetails/java−0402.com/javadetails/...String[] args) { someStaticMethod().doit(). } public static void someStaticMethod() { System.rgagnon.rgagnon.com/javadetails/.out.lang.17 Get the class name in a static method .

trace(Thread.currentThread().getMethodName()). doitagain().getStackTrace())./javadetails/java−0422. } public void doitagain() { trace(Thread.currentThread().html public class ClassUtils { 11.getMethodName()).5.With JDK1.out. for (StackTraceElement s : e) { if (doNext) { System. If you find this article useful. consider making a small donation to show your support for this Web site and its content. } public void doit() { System.getStackTrace()).doit().19 Detect if a package is available .doit()..println(s. a new technique is available.getStackTrace()). } public static void trace(StackTraceElement e[]) { boolean doNext = false.currentThread().rgagnon.19 Detect if a package is available Current version of this HowTo : http://www. } public void doit() { trace(Thread.println( Thread. return.getMethodName().getStackTrace()).currentThread(). public class Test { public static void main(String args[]) { trace(Thread. } } See also this HowTo.com/javadetails/.currentThread(). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11.getStackTrace()[3].equals("getStackTrace"). new Test(). } doNext = s. } } } main doit doitagain main To get the calling method public class Test { public static void main(String args[]) { new Test().out.

xml.isAvailable("imaginary.ImageJAI")?"present":"absent"))..forName(className.com/javadetails/. System.println ("Java3d " + (ClassUtils. try { Class.out. private OnlyOne(){} public static OnlyOne getInstance() { return one. System. /* output : Swing present JAI absent SAX present ImaginaryClass absent Java3d absent */ } public static boolean isAvailable(String className) { boolean isFound = false.media.println ("JAI " + (ClassUtils.println ("Swing " + (ClassUtils.isJava3dAvailable()?"present":"absent")).JComponent")?"present":"absent")). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11. } } 11. } public static boolean isJava3dAvailable() { return isAvailable("javax.out. } return isFound.out.isAvailable("org.sax.20 Have a singleton Current version of this HowTo : http://www.media. System.XMLReader")?"present":"absent")).isAvailable("javax. Repeated calls always return the same instance. System.ImaginaryClass")?"present":"absent")).rgagnon.jai.j3d.swing. consider making a small donation to show your support for this Web site and its content.isAvailable("javax.out.public static void main(String args[]) { System. } } If you find this article useful.View").20 Have a singleton .html A singleton is a class that can be instantiated only one time in a JVM. null).out. false. } catch (ClassNotFoundException e) { isFound = false./javadetails/java−0355. public class OnlyOne{ private static OnlyOne one = new OnlyOne().println ("SAX " + (ClassUtils. isFound = true.println ("ImaginaryClass " + (ClassUtils.

} public void myMethod(Object parms[]) { for (int i=0. } } NOTE : In JDK1.5.21 Make methods that have unspecified number of parameters .com/javadetails/./javadetails/java−0289. public class Howto { public static void main(String args[]) { Howto howto = new Howto().out.21 Make methods that have unspecified number of parameters Current version of this HowTo : http://www. i < parms.out. } } 11. args) { for(String arg:args) { System.To use it OnlyOne myOne = OnlyOne. If you find this article useful. new Integer(2).length.html You pass an array of Objects. i++) System..out. "value n" )... parms) { for(Object parm:parms) { System. "value n"} ). we have VARARGS parameters so this not needed anymore! public class TestIt { public static void main(String args[]) { TestIt.println(arg). howto..println(parm).println(parms[i]). } } } public class TestIt { public static void main(String .doit ( "value 1". /* output : value 1 2 value n */ } public static void doit(Object .myMethod ( new Object[] {"value 1".rgagnon. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11.getInstance().. consider making a small donation to show your support for this Web site and its content. new Integer(2).

j=0./javadetails/java−0316./javadetails/java−0432.22 Multiple expressions in for loops .com/javadetails/..*.awt package.awt. import java. public class MultipleFor{ public static void main (String [] args){ for (int i=0. If you find this article useful. .com/javadetails/. i < 10. consider making a small donation to show your support for this Web site and its content. The solution is to fully qualify the name used when you reference the List class or interface.println ("i = " + i + " j= " + j).rgagnon.util. java.. ./javadetails/java−0372.html The List interface is declared in the java. j−−) System.html A nice idea is to put this toString() into a base class so all the descendents inherit from it. 11.com/javadetails/.List myAwtList = new java.awt...util package and the List class is in the java.awt. So if both import are defined in your source you won't be able to compile properly because this will cause a name conflict. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11.22 Multiple expressions in for loops Current version of this HowTo : http://www.out.List().rgagnon.rgagnon./* output : >java TestIt 1 2 3 how−to 1 2 3 how−to */ } 11.*.23 Handle the List conflict Current version of this HowTo : http://www.html You do it "à la C"... } } 11. i++.24 Use a generic toString() Current version of this HowTo : http://www.. import java.

lang. AccessibleObject.getSuperclass().com import java.util. Class cls = getClass().printStackTrace().setAccessible( f. } return cls.reflect. java.AccessibleObject. for ( int i = 0. } catch (IllegalAccessException e) { e. } private static void toString( Object o. hello=world} } public String toString() { java. //jdk1.getName().ArrayList. your solution is fine.printStackTrace().out. } } if (cls. list ).getSuperclass() != null ) 11. class ToStringHelper { public static String toString( Object o ) { ArrayList list = new ArrayList().22 Multiple expressions in for loops .util. java. super.getClass(). // generictostring{i=42.put(f[i].reflect.Field[] f = cls.AccessibleObject.lang. i < f. but has some drawbacks: − it based on inheritance − an attribute of a subclass cannot overlap an attribute of a superclass (because of hashtable) So I changed your solution a bit: // @author Christian Ullenboom // @url http://java−tutor.lang.getSuperclass() != null) { h.add( f[i]. import java.toString() ).getClass().getName().getName() + "=" + f[i].get(this)).length.reflect.println(new generictostring().getSuperclass(). int i = 42.toString()). } } Christian Ullenboom wrote: Hi. Class clazz.f[i]. } } if ( clazz.public class generictostring { String hello = "world".length.Hashtable h = new java. public static void main(String args []) { System.get(o) ).setAccessible(f. o.toString()). return o. true ).Field.getDeclaredFields(). toString( o.put("super". ArrayList list ) { Field f[] = clazz.getDeclaredFields().concat( list.Hashtable().lang. import java. } catch ( IllegalAccessException e ) { e.reflect.2 for (int i = 0. i++) { try { h.getName() + h. true). i < f. i++ ) { try { list.util.

util./javadetails/java−0433.clone() Current version of this HowTo : http://www. clazz. System.html Consider the following example. } } class Ober { int i = 123.println(d). d=3..25 Use Object.out. class MyData { private Date aDate.println( ToStringHelper. 11. // ToStringHelperTest[hello=world. Date d = mydata. list ). import java.setTime(1000). private double d = 3. MyData() { aDate = new Date(). i=123.Date. } public void setdate(Date d) { aDate = d.clone() . int i = 42.toString( o. public static void main(String args[]) { Ober t = new ToStringHelperTest(). } } public class DemoClone { public static void main(String args[]) { MyData mydata = new MyData(). i=42. d. } public class ToStringHelperTest extends Ober { String hello = "world". System.toString(t) ).out.1415] } } If you find this article useful.25 Use Object. } public Date getDate() { return aDate.println(d).rgagnon. System.getDate(). consider making a small donation to show your support for this Web site and its content.1415. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11.out.com/javadetails/.getSuperclass().

getDate()).out. } } public class DemoClone { public static void main(String args[]) { MyData mydata = new MyData(). Date d = mydata. not the original.html Consider the following class public class Foo { 11. import java.out. constructor and exception .getDate()). // Sat Apr 19 23:17:43 EDT 2003 // Wed Dec 31 19:00:01 EST 1969 // Wed Dec 31 19:00:01 EST 1969 which is no good } } Even if aDate is declared as private. The solution is to return a copy of aDate. so even if you have reference to it.26 Static field. it is possible to modify because a Date object is mutable and we have a reference to it. // Sat Apr 19 23:17:43 EDT 2003 // Wed Dec 31 19:00:01 EST 1969 // Sat Apr 19 23:17:43 EDT 2003 which is good } } If you find this article useful. d. } public Date getDate() { return (Date)aDate. constructor and exception Current version of this HowTo : http://www. System. MyData() { aDate = new Date(). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11.rgagnon.util. } public void setdate(Date d) { aDate = d.System.Date. class MyData { private Date aDate../javadetails/java−0444.println(mydata.println(d).out.com/javadetails/.println(d).out.getDate(). any modification will be done on the copy. System.clone(). consider making a small donation to show your support for this Web site and its content.println(mydata. System.26 Static field.setTime(1000).

private static Bar b = new Bar(). out: { for( int row=0.html Labelled breaks allow breaking out of several levels of nested loops inside a pair of curly braces. use a static block. row< max.. j += 1. int j = 0..printStackTrace() .. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11.27 Use a Label break .out. // output 5 11. } } } class Bar { public Bar ( ) throws Exception { } } If you find this article useful.rgagnon.27 Use a Label break Current version of this HowTo : http://www. row++ ) { for( int col=0. } class Bar { public Bar ( ) throws Exception { } } it will not compile because Bar() is declared to throw an exception. This way./javadetails/java−0500.println(j). . static { try { bar = new Bar() . } } System. you can almost simulate a GOTO! class JavaGoto { public static void main(String args[]) { int max = 10.com/javadetails/. public class Foo { static Bar bar . To solve this situation. col< max. } catch ( Exception e ) { e. int limit = 5. col++ ) if( row == limit) break out. consider making a small donation to show your support for this Web site and its content.

Exception: for no reason! // at TestException. public class TestException { public static void main(String args[]) { try { throw new Exception("for no reason!"). } catch (Exception e) { StringWriter sw = new StringWriter(). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11.toUpperCase()).LANG.28 Put printStackTrace() into a String Current version of this HowTo : http://www. } } // output : // JAVA.28 Put printStackTrace() into a String .java:8) } You redirect the StackTrace to a String with a StringWriter/PrintWriter : import java. If you find this article useful.com/javadetails/. } catch (Exception e) { e. consider making a small donation to show your support for this Web site and its content.} } If you find this article useful.MAIN(TESTEXCEPTION. Written and compiled by Réal Gagnon ©1998−2006 [ home ] 11. System.println(sw. consider making a small donation to show your support for this Web site and its content./javadetails/java−0537.io.rgagnon.io.PrintWriter. } }2 // output : // java.printStackTrace(pw).EXCEPTION: FOR NO REASON! // AT TESTEXCEPTION.. e.html public class TestException { public static void main(String args[]) { try { throw new Exception("for no reason!").printStackTrace().out. import java.StringWriter.main(TestException. PrintWriter pw = new PrintWriter(sw).lang.JAVA:7) } This can be useful if you want to format the StackTrace before showing it to the user.toString().

Comparer comparer) { sort(a. b. // Sort the rest if (from < j) sort(a. int to. a[j]) > j−−. j−−. comparer). // sort using Quicksort int i = from. from.compare( center.1 public class ArraySorter { /* ** Sort in the same array */ public static void sort(Object[] a.compare(center. a. null./javadetails/java−0008. } else { // Decending sort while( (i < to) &(comparer. 0. boolean ascending. } public static interface Comparer { /** * The interface implementation should compare the two * objects and return an int using these rules: * if (a > b) return > 0.length < 2) return. Object center = a[ (from + to) / 2 ]. * if (a == b) return 0. if (i < to) sort(a.com/javadetails/. Comparer comparer) { // No sort if (a == null || a. } } while(i <= j). comparer).compare(center.. to. while( (j > from) &(comparer. int from.compare( center. // Swap in b array if needed if (b != null) { temp = b[i]. do { if (ascending) { while( (i < to) &(comparer. a[j]) < j−−. j = to.html [ArraySorter. b[j] = temp. b[i] = b[j]. a[i]) > i++. b. a[i] = a[j].length − 1. 0) ) 0) ) 0) ) 0) ) 11. true. } } if (i <= j) { i++.29 Sort an array Current version of this HowTo : http://www.rgagnon. comparer). while( (j > from) &(comparer. a[i]) < i++. } if (i < j) { // Swap elements Object temp = a[i].11. i. ascending. using a as the reference */ public static void sort(Object[] a.java] JDK1. } /* ** Sort a and b. a[j] = temp. j. Object[] b.29 Sort an array . ascending.

50.10.50.Arrays. i++) { System. 0.Arrays.10.println(args[i]). 11.30 Initialize multidimensional array Current version of this HowTo : http://www.00.20}.com/javadetails/. java.70.Comparer { public int compare(Object a.30 Initialize multidimensional array . static double[][] Rates = { {0.90. 4. 11. {1. 2.util."Bar". } } } JDK1. 2.. Object b) { return ((String)a).. } } } public static class ASCIIComparer implements ArraySorter.println("give me some args to sort"). 2.00}. for (int i = 0. java. } } [testArraySorter.80.00. 6. 0.length.sort(myArray. {0.compareTo((String)b).text. else { ArraySorter.80}. 1. asciiComparer).00} }. 5.4 case−sensitive String[] myArray = new String[] {"foo".20.java] public class testArraySorter { public static final ASCIIComparer asciiComparer = new ASCIIComparer().* if (a < b) return < 0. */ public int compare(Object a. {6."baz"}. 0.50.30}.sort(args. Object b). java. 1..out.rgagnon. {4.70. public static void main(String args[]) { if (args.90. 0.out.sort(myArray). 1.60}. 4. {2.util.40. case−insensitive String[] myArray = new String[] {"foo"./javadetails/java−0036.10}. 3. 0.50.Collator.getInstance()). 0.50. i < args.50.length == 0) System."baz"}.20. 1."bar".60.11. 3.60. 8.html Simply use braces.40. {0.

} } To get the number of dimensions : class ArrayDim { public static void main(String args[]) { String[][] data = new String[3][4]. // expected output : // "This array has 2 dimensions" } public static int getDim(Object array ) { int dim=0. i < buf. while( c. } return( dim ).11.0..getClass().println("This array has " + getDim(data) + " dimensions").split(regexp) method. See this HowTo.rgagnon.length).html NOTE: This HowTo was designed for JDK 1. It's the String.indexOf(buf. System. consider making a small donation to show your support for this Web site and its content.. System.4. dim++.length(). Starting with version 1.32 Convert a String to an array Current version of this HowTo : http://www.getComponentType().rgagnon.out. i++ ) { if ( sep.println("Dimension 1: " + data.2. } } If you find this article useful./javadetails/java−0280.com/javadetails/. 11.charAt(i) ) != −1 ) arraysize++.31 Get array upperbound . Class c = array. for ( int i = 0.31 Get array upperbound Current version of this HowTo : http://www. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11./javadetails/java−0368.out. Thanks to T.out.println("Dimension 2: " + data[0].isArray() ) { c = c. System. int arraysize = 1. the String class offers a better way to split a String into an Array. GUIRADO public String[] stringtoArray( String s.com/javadetails/.html class ArrayLength { public static void main(String args[]) { String[][] data = new String[3][4].length). String sep ) { // convert a String s to an Array. the elements // are delimited by sep StringBuffer buf = new StringBuffer(s).

} buf = null. i < k./javadetails/java−0428.toString(). buf. } 11. if ( buf.toString(). for (int i= 1 .delete(0.lastIndexOf(sep) ) { elements[z] = buf. buf.indexOf(sep). } To transform back to String public String arrayToString(String s[].toString().} String [] elements = new String [arraysize]. return elements. y + 1).delete(0.toString().length.33 Sort in reverse order Current version of this HowTo : http://www.html Arrays.sort (myArray. z++.toString(). Collections.toString().indexOf(sep) != −1 ) { while ( buf.rgagnon. y ). } else if ( buf. if (k > 0) { result = s[0]. buf. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11. if ( y != buf.. elements[z] = buf. } } } } else { elements[0] = buf.indexOf(sep)).33 Sort in reverse order .toString().z = 0.reverseOrder()). int y.toString(). i++) { result += sep + s[i] .lastIndexOf(sep) == y ) { elements[z] = buf.substring(0. buf.length() ). consider making a small donation to show your support for this Web site and its content. } } return result.indexOf(sep) + 1).indexOf(sep) != −1 ) { y = buf. String sep) { int k.z++. buf.length() > 0 ) { if ( buf.toString(). z++.com/javadetails/. k = s. String result = "".delete(0.toString().substring (0. If you find this article useful.toString(). buf.

System.out.get(0). 4}.. // 4 i = (int[])ArrayUtils.3. } // a 11.println("The i array length is " + i. if (!cl. newLength).. return newArray. you use a Collection (Map.println("Array 1 " +list.lang. } } But a better way is to use a Vector or an ArrayList.).println("The s array length is " + s. list. System.ArrayList. System. ArrayList is roughly equivalent to Vector. import java. // 2 System.println("The i array length is " + i.34 Resize an array . public class ArrayUtils { public static void main (String arg[]) { String s[] = new String[20].rgagnon.reflect. // 6 } public static Object expand(Object a) { Class cl = a. you can use System.arraycopy(a. } public void doit1() { // single dimension ArrayList list = new ArrayList().. int size = list. 0.newInstance(componentType. ArrayList. list.size().2 .out.add("a").out.out.html Arrays cannot be resized dynamically. newArray. // 50% more Class componentType = a. public class ArrayListDemo { public static void main (String arg[]) { ArrayListDemo x = new ArrayListDemo(). Object newArray = Array. x.doit1(). System.doit2().util.length).getClass(). If you want a dynamic data structure with random access. int newLength = length + (length / 2).length).length).length). length). System.11.arraycopy() method to copy the content of an array to another one. x.out.34 Resize an array Current version of this HowTo : http://www. // 20 s = (String[])ArrayUtils. import java.add("b"). // 30 int i[] = {1 .expand(i).Array. 0.println("The s array length is " + s. If you need to expand.getClass().expand(s).isArray()) return null. except that it is unsynchronized./javadetails/java−0431. int length = Array.getLength(a).getComponentType()..com/javadetails/.

80} }. double d [][]= { {0.Arrays provides new ways to dump the content of an array.rgagnon. 0.Arrays. ArrayList l1 = new ArrayList(). {0. b. public class Test { public static void main(String args[]) { String s[] = {"a". System.println("Array 2 " + ((ArrayList)list.35 Dump array content Current version of this HowTo : http://www. System. c. l2. It's even possible to dump muti−dimensional arrays.add("c"). "d"}.add(l1).util.out.out. 0.get(0)).size(). "b".50. l1.util. This technique works only with classes and not with primitives like int or double.add("b"). // b } } If you find this article useful. ArrayList l3 = new ArrayList(). d] } } JDK1.get(1)). public class Test { public static void main(String args[]) { String s[] = {"a".5 java. 1.println(java.70. 0.Arrays. l3. consider making a small donation to show your support for this Web site and its content.println(java.get(0)).10.40.deepToString(d)). // output 11. System.35 Dump array content . "c".util.50. // output // [a.Arrays. list. System.add(l2). int size1 = list.toString(s)). "b".utils.html Convert the array to a List and then convert to String. list..add("a"). "d"}. "c".asList(s).50. 0./javadetails/java−0465. // 3 int size2 = ((ArrayList)list. 0. list.out. // 1 Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11.out.public void doit2() { // multi dimensions ArrayList list = new ArrayList().println(java.com/javadetails/.add(l3). ArrayList l2 = new ArrayList().toString()).size().60}.

b.html import java.*. }. new Integer(2). consider making a small donation to show your support for this Web site and its content. 0. } } If you find this article useful.out.5. new Integer(3).println(integerArray[i]). "d"}. "c". class InitStaticArray { static Integer[] integerArray.length. consider making a small donation to show your support for this Web site and its content. d] // [[0. "b". i <integerArray..8]] } } You can also use the new shorthand notation to iterate through an array : public class Test { public static void main(String args[]) { String s[] = {"a".io.util.rgagnon.5. 0. 0. 0.36 Initialize a static array .1. new Integer(4).out. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11.6].com/javadetails/./javadetails/java−0475.println(element). [0. } } } If you find this article useful.5.4. i++){ System.*.7. c. } public static void main(String args[]) { for (int i=0. 0. import java. for (String element : s) System. 1.// [a. static { integerArray= new Integer[] { new Integer(1).36 Initialize a static array Current version of this HowTo : http://www.

out.put(array1[0]. array2[0]).html Data in hashtable are not sorted."A"}.hasNext()) { String element = (String)it.sort(v). h.keySet()).out.println( element + " " + (String)h. while (it.get(element)). System..37 Sort an Hashtable . h. array2[1]).37 Sort an Hashtable Current version of this HowTo : http://www. while (it. // unsorted keys output Iterator it = h.*. System.put(array1[1].keySet(). } System./javadetails/java−0478. See this Howto.put(array1[2]. Since Hashtable methods are synchronized they are slower than those in HashMap. it = v.util."B".hasNext()) { String element = (String)it.iterator().iterator(). public class HashtableTest { static String[] array1 = {"C".next(). import java.get(element)). h. static String[] array2 = {"1". } /* output : A 3 C 1 B 2 ============ A 3 B 2 C 1 */ } } NOTE : When possible always use an HashMap instead of an Hashtable. We extract the keys and sort them.next().println("============"). array2[2]). // sorted keys output thanks to T."2". If you find this article useful."3"}. GUIRADO for the tip! Vector v = new Vector(h. Collections.out. public static void main(String args[]) { Hashtable h = new Hashtable(). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11.rgagnon.println(element + " " + (String)h.com/javadetails/. consider making a small donation to show your support for this Web site and its content.11.

/javadetails/java−0521..11. Simply add the expected type (between < and >) after the class.add("hello").util. ^ C:\ArrayListGeneric.Iterator required: java.ArrayList data.iterator()..util.add("hello").add("world")...iterator(). Iterator<String> it = data.add("world").util.. your class is ready to run but . ^ C:\ArrayListGeneric.iterator(). public class ArrayListGeneric { public static void main(String[] args) { ArrayList data = new ArrayList()..rgagnon.add("hello"). Iterator<String> it = data." compiler warning Current version of this HowTo : http://www.java:21: warning: [unchecked] unchecked call to add(E) as a member of the raw type java. data.add("world"). while (it. data.util.java:25: warning: [unchecked] unchecked conversion found : java.out. import java. public class ArrayListGeneric { public static void main(String[] args) { ArrayList<String> data = new ArrayList<String>(). while (it.next().util..Iterator Iterator it = data.38 Eliminate "[unchecked] unchecked call . ^ 3 WARNINGS Since there are only warnings.*.38 Eliminate "[unchecked] unchecked call .util.hasNext()) { String s = it." compiler warning .html import java.println(s). System. 11.5) emits the following warnings : C:\ArrayListGeneric.hasNext()) { String s = it.com/javadetails/. it's not bad idea to eliminate the warnings in production code. data.java:22: warning: [unchecked] unchecked call to add(E) as a member of the raw type java. the compiler (jdk1.next(). data.ArrayList data.*. } } } When compiling the above class.

consider making a small donation to show your support for this Web site and its content.out. String l) { this.html. Iterator it = data. } } } A complete list of possible @SuppressWarnings parameters can be found at http://mindprod.firstName = f. it will be possible to insert a special annotation to suppress this kind of warning. public class ArrayListGeneric { @SuppressWarnings("unchecked") public static void main(String[] args) { ArrayList data = new ArrayList().com/jgloss/annotations. lastName.com/javadetails/. data.iterator().add("hello").. while (it. this. } } } In JDK 1.util.39 Sort on many fields Current version of this HowTo : http://www. If you find this article useful. 11.println(s).39 Sort on many fields .add("world").*.hasNext()) { String s = it.out./javadetails/java−0520. } public String getLastName() { return lastName.lastName = l. System.next(). } public String getFirstName() { return firstName. something like : import java. public Person(String f.6. data. First the Person class class Person implements Comparable { String firstName. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11.rgagnon.System.html We want to sort a Collection of Person objects based on their LastName and Firstname.println(s).

names.util.getFirstName()) : nameComp). "Homer".compareTo(emp. java. i < Smith. class PersonComparator implements Comparator{ public int compare(Object obj1. java. java.Iterator.util.compareTo(emp2. } } To test it : import import import import import java.equals(emp.util. Object obj2) { Person emp1 = (Person) obj1. } public boolean equals(Object obj) { if (!(obj instanceof Person)) { return false.Arrays.getFirstName()). } } then we need a class to implement the Comparable interface. // do the smith for(int i = 0 .compareTo(emp.equals(emp. import java. int deptComp = firstName. Person emp2 = (Person) obj2. public class TestSort { public static void main(String args[]) { String Smith[] = { "Real".compareTo(emp2.ArrayList.getFirstName()) &lastName. i ++) { Person one = new Person(Smith[i]. int nameComp = emp1.getLastName()) : deptComp). } public int compareTo(Object obj) { Person emp = (Person) obj. "Christine" }.util. java. ArrayList names = new ArrayList(). "Nathalie". "Maggie" }.Collections. "Vincent".getFirstName().util.39 Sort on many fields ."Smith"). "Lisa". return ((nameComp == 0) ? emp1. "Marge". } Person emp = (Person) obj. return firstName.} public String toString() { return "[ firstname=" + firstName + ".add(one).List. return ((deptComp == 0) ? lastName. It's in there where we put the logic behind the sorting.length .Comparator. String Simpsons[] = { "Bart".getLastName()).util.getLastName().getLastName()). } 11.lastname=" + lastName + "]".

println(iter1.out.lastname=Simpsons] [ firstname=Marge.out.lastname=Simpsons] [ firstname=Maggie. i < Simpsons.com/javadetails/. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11. i ++) { Person one = new Person(Simpsons[i]. Iterator iter2 = names.lastname=Smith] */ } } If you find this article useful.40 Optimize Collection usage .lastname=Smith] [ firstname=Real.lastname=Simpsons] [ firstname=Homer.lastname=Smith] [ firstname=Vincent. Iterator iter1 = names.sort(names. while (iter2.hasNext()) { System.next()). System.out.html 11.lastname=Simpsons] [ firstname=Lisa.out.lastname=Smith] [ firstname=Nathalie."Simpsons").lastname=Smith] [ firstname=Bart.lastname=Simpsons] [ firstname=Christine.length .lastname=Smith] [ firstname=Vincent.lastname=Simpsons] [ firstname=Maggie.println(iter2.lastname=Simpsons] [ firstname=Marge. } /* output : BEFORE: [ firstname=Real.rgagnon.iterator()./javadetails/java−0553.lastname=Simpsons] AFTER: [ firstname=Bart. } // now sort everything Collections.add(one). names.next()).hasNext()) { System.lastname=Smith] [ firstname=Christine. consider making a small donation to show your support for this Web site and its content.println("AFTER:"). while (iter1.. new PersonComparator()).lastname=Simpsons] [ firstname=Lisa.println("BEFORE:").lastname=Simpsons] [ firstname=Homer.40 Optimize Collection usage Current version of this HowTo : http://www.// do the simpsons for(int i = 0 . } System.iterator().lastname=Smith] [ firstname=Nathalie.

} } Result : 522396 duplicated words. 11. new TreeSet<String>()). 522396 duplicated words.currentTimeMillis(). new HashSet<String>()). for (StringTokenizer i = new StringTokenizer(text). } } long endTime = System.println(t.io.txt". public static void main(String[] args) { try { String text = readText().From Usenet. } else { listOfWords.add(word).*.out. " + "Using " + listOfWords. } return text. countDuplicateWords(text.currentTimeMillis().toString()). // Read text into RAM countDuplicateWords(text. String line = null. Using java. the execution time is very different! import java. class TestCollectionPerformance { private static String TEXT_BOOK_NAME = "war−and−peace.toString(). Using java.util.40 Optimize Collection usage .util.contains(word)) { numDuplicatedWords++. (a post by ""Ed") a post to demonstrate that depending on your need.) { String word = i. } private static void countDuplicateWords(String text.util.readLine()) != null) { text.HashSet.println(numDuplicatedWords + " duplicated words.out. } } private static String readText() throws Throwable { BufferedReader reader = new BufferedReader(new FileReader(TEXT_BOOK_NAME)).TreeSet. In the demonstration. } catch (Throwable t) { System. if (listOfWords. countDuplicateWords(text.txt and then count the duplicated words.*."). while ((line = reader. as you can see depending on the Collection used. time = 453ms.getName() + ". countDuplicateWords(text. long startTime = System. time = " + (endTime − startTime) + "ms. new ArrayList<String>()). System. Collection<String> listOfWords) { int numDuplicatedWords = 0. we read a huge text file war−and−peace. time = 1031ms. StringBuffer text = new StringBuffer().append(line + " "). i. new LinkedList<String>()). choosing the right Collection implementation can be really important.getClass().nextToken().hasMoreElements(). import java.

• An HashSet maintains its collection in an unordered manner.41 Sort an HashMap Current version of this HowTo : http://www. It provides quick indexed access to its elements. while (it.41 Sort an HashMap . Using java.. i++) { map./javadetails/java−0561. for (int i=0. // to hold the result HashMap map = new LinkedHashMap(). it just manipulates reference pointers. Using java.get(yourMapValues. Sort based on the values HashMap yourMap = new HashMap(). time = 129375ms. To make this happen.hasNext()) { String file = (String)it. • A Set offers a collection of unique elements. List yourMapKeys = new ArrayList(yourMap.put (yourMapKeys..length. • A TreeSet keeps the elements in the collection in sorted order.. ref : Sun's Java tech Tips Feb2003 11. sortedArray[i]). But LinkedList's added flexibility comes at an added cost −− it results in much slower indexed operations.html Sort based on the keys Map yourMap= new HashMap().util. not only at the end. int size = sortedArray.util. i<size. time = 100937ms.ArrayList. TreeSet sortedSet = new TreeSet(yourMapValues). // put some tuples in yourMap . • The LinkedList is best when add and remove operations happen anywhere. LinkList doesn't do an internal move operation for an element insert or remove.iterator().keySet(). • The ArrayList provides a collection backed by an array. Iterator it = ref.toArray(). Object[] sortedArray = sortedSet. // put some tuples in yourMap . Map sortedMap = new TreeMap(yourMap).LinkedList.. 11. } To iterate your new Sorted Map Set ref = map.next().values()). • A List provides ordered access (by index).indexOf(sortedArray[i])).keySet()).522396 duplicated words.com/javadetails/. 522396 duplicated words.rgagnon.. but it doesn't guarantee uniqueness. ArrayList performs an internal move operation when an element is added or removed. and works best when elements are only added and removed at the end. List yourMapValues = new ArrayList(yourMap.

Object value){ Set ref = hm.hasNext()) { Object o = it.*.. } 11. while (it.com/javadetails/.com/javadetails/.props] # this a comment ! this a comment too DBuser=anonymous DBpassword=DBlocation=bigone [JAVA code] import java.} 11.43 Use an INI file (properties) Current version of this HowTo : http://www.html [Java 5] public static Object getKeyFromValue(HashMap hm. By convention. if(o.equals(value)) { return o. Iterator it = ref./javadetails/java−0024. The structure is very similar to Windows INI file with except that there is no [..keySet().util. import java.html In Java.Object value){ for(Object o:hm.. the filename extension is props or properties.equals(value)) { return o.*.4] public static Object getKeyFromValue(HashMap hm.iterator().get(o)..next(). [Props file : user. configuration file are stored in properties file. } } return null. 11.42 Get a key from value with an HashMap .keySet()){ if(hm. } } return null.rgagnon.] section.42 Get a key from value with an HashMap Current version of this HowTo : http://www.rgagnon./javadetails/java−0564.io. } [Java 1.

println(e). The modified data can be saved back to a file with the save method. } } } Since the Properties class extends the Hashtable. } catch (Exception e) { System. System. import java.list(System. To read a Properties file via an Applet. p.out. System. "/* properties updated */").toString()). p.load(new FileInputStream("user. } public void doit() { try{ Properties p = new Properties(). Note that the order is not preserved.println("user = " + p.println("password = " + p. A Properties file stored in a JAR can be loaded this way : 11.println(e). p.put("today".util.println("location = " + p.getProperty("DBuser")). new Date().getProperty("DBpassword")).put("DBpassword". p.props")). // modify a Property p."foo").out.getProperty("DBlocation")). } } } This ok with an application but you can't do it from an Applet since you can't write directly on the server without some kind of a server−side process.props").out.io. "user. p.42 Get a key from value with an HashMap . class WriteProps { public static void main(String args[]) { WriteProps props = new WriteProps(). props.doit(). System.*.out).out).props")).doit(). props. // new Property p.*. FileOutputStream out = new FileOutputStream("user. This can be useful to store user preferences for example.props")).load(new FileInputStream("user. import java.save(out.load((new URL(getCodeBase(). } public void doit() { try{ Properties p = new Properties().list(System. } catch (Exception e) { System. we can manipulate the Properties through the get and put methods.out.out. load the Properties files this way : p.openStream()).class ReadProps { public static void main(String args[]) { ReadProps props = new ReadProps().

println(props). this one and finally this one too! 11. } } If you find this article useful.println(props).util.substring(6). notation • To avoid having to type all the \u.toString(). consider making a small donation to show your support for this Web site and its content.FileInputStream fis = new java.getProtectionDomain(). String path = getClass(). 11.. props.props")).util. } public void doit() throws Exception{ // properties in the classpath java. use the native2ascii tool (included with the SDK).File( path + "\\myprops.openStream()).util.html The rules are • Only use ISO Latin 1 characters in the Properties/ResourceBundle files • For other characters use the \u.io.net.Properties props = new java.io.io. if (url != null) props..44 Load a properties file .Properties().URL url = ClassLoader.com/javadetails/.openStream()).URL url = ClassLoader.props").html public class LoadProps { public static void main(String args[]) throws Exception{ h.getSystemResource("myprops.getSystemResource("/com/rgagnon/config/system. System. } public void doitagain() throws Exception{ // properties in the startup directory java. If you find this article useful. java. System.Properties props = new java. notation manually. consider making a small donation to show your support for this Web site and its content.doit().doitagain().props").out.44 Load a properties file Current version of this HowTo : http://www. getLocation(). See also this HowTo.45 Accentuated characters in Properties/ResourceBundle file Current version of this HowTo : http://www.util..load(fis)...load(url. java.rgagnon.FileInputStream (new java.rgagnon../javadetails/java−0492./javadetails/java−0434.load(url. props.Properties().getCodeSource(). h.com/javadetails/.out. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11..

util.println("prop1 :\n " + props..Properties(). Take the following properties file : [props.Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11. } public void doit() throws Exception{ // properties in the classpath java. consider making a small donation to show your support for this Web site and its content. h.doit(). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 11.properties").46 Have a multi−line value in a properties file Current version of this HowTo : http://www. System.java] public class Hello { public static void main(String args[]) throws Exception{ Hello h = new Hello().properties] prop1=first line of prop1 \ second line of prop1\ third line of prop1 prop2=first line of prop2 \n \ second line of prop2 \n \ third line of prop2 A program to read the properties file : [Hello. System.net. props. java.rgagnon.getSystemResource("props.get("prop2")).load(url./javadetails/java−0503.Properties props = new java.46 Have a multi−line value in a properties file .URL url = ClassLoader.util.println("prop2 :\n " + props.html You add a slash ("\") to continue the value on the next line. } } The output >java Hello prop1 : first line of prop1 second line of prop1third line of prop1 prop2 : first line of prop2 second line of prop2 third line of prop2 If you find this article useful.com/javadetails/.get("prop1")).openStream()).out.out.

p.48 Use the Registry to store informations (Preferences API) Current version of this HowTo : http://www. p.. import java.out).dtd"> <properties> <comment>props updated</comment> <entry key="user">Bob</entry> <entry key="today">Thu Aug 09 22:45:11 EDT 2007</entry> </properties> 11.doit().4.io.rgagnon. FileOutputStream out = new FileOutputStream("user.com/dtd/properties. class XMLProps { public static void main(String args[]) { new XMLProps().html With JDK1.props"). p. the Preferences class can use the Windows registry (on Unix. } } } The XML looks like <?xml version="1.11.put("today"./javadetails/java−0421.rgagnon.put("user".com/javadetails/. p. a file is used) : 11. new Date(). FileInputStream in = new FileInputStream("user..printStackTrace(). "Bob").*.list(System.util.47 Use XML with Properties Current version of this HowTo : http://www.loadFromXML(in).*.props").0" encoding="UTF−8"?> <!DOCTYPE properties SYSTEM "http://java. p.toString()).sun.com/javadetails/.47 Use XML with Properties . } public void doit() { try{ Properties p = new Properties()."props updated")./javadetails/java−0578.storeToXML(out. /* output : −− listing properties −− today=Thu Aug 09 22:45:11 EDT 2007 user=Bob */ } catch (Exception e) { e.html import java.

rgagnon. // read back from HKEY_CURRENT_USER System.util.get(REALKEY. // write into HKLM\Software\Javasoft\Prefs\com.com http://www.foo p = Preferences. public static void main(String[] args){ new UsingReg(). "bar").get(REALKEY.foo Preferences p = Preferences. a file is used and you may run into problems if you don't have write access in the default location for the Preferences storage.println(p). See this interesting article and these 2 bugs : 1 2 If you find this article useful.rgagnon. } } See also this How−to to access the Windows registry. System. public class UsingReg { public static final String REALKEY= "com.Preferences.println(p.import java.out.out.put(REALKEY. "HKCU houston we have a problem")).out.rgagnon. "HKLM houston we have a problem")).put(REALKEY.println(p. p.prefs. With Unix (or Linux). // read back from HKEY_LOCAL_MACHINE System. Written and compiled by Réal Gagnon ©1998−2005 [ home ] Written and compiled Réal Gagnon ©2007 real@rgagnon.out.doit().println(p).com 11. "barbar").systemRoot(). consider making a small donation to show your support for this Web site and its content.47 Use XML with Properties . p.userRoot().rgagnon.foo". } public void doit() { // write into HKCU\Software\Javasoft\Prefs\com. System.

} static void displayInterfaceInformation(NetworkInterface netint) throws SocketException { System.1 java−net 12.util.IOException. 12 Networking .BufferedInputStream.getNetworkInterfaces()..net.rgagnon.2 Extract network card address Current version of this HowTo : http://www.io.println("Hardware address: " + Arrays.html JDK1.out.5 or less One way.12 Networking 12. import java.InputStream.com/javadetails/.*.io.NetworkInterface import java. for (NetworkInterface netint : Collections. public class ListNetsEx { public static void main(String args[]) throws SocketException { Enumeration nets = NetworkInterface.*. Otherwise.toString(netint. import java. Example for Windows import import import import java. java.list(nets)) displayInterfaceInformation(netint). System.io./javadetails/java−0369. without using JNI.out. "arp −a" will return the MAC addresses of all adapters that have TCP/IP bound to them and have recently (default < 5 mins) resolved an IP address.getHardwareAddress())). including the MAC address (displayed as "physical address").getDisplayName()). In Linux.io.*. in NT/2K/XP. "ipconfig /all" will return all relevant network info for IP−bound adapters. java. "ifconfig" does something similar. In Windows. is to launch an external utility and interpret the output.println("Display name: " + netint.net.6 java.net. java.InetAddress. } } JDK1.

} } catch(ParseException e) { e. import java.name"). while(tokenizer. // // inspired by // http://forum. // . // Process p = Runtime.StringTokenizer.startsWith("Mac OS X")) { .text.getRuntime().java..sun. } } private final static String winMacAddress(String ipConfigOutput) throws ParseException { String localHost = null.net. "\n")..jspa?messageID=902023 // public final class NetworkUtils { private final static int MACADDR_LENGTH = 17.getMessage(). 0).exec("ifconfig"). } catch(java. try { localHost = InetAddress.startsWith(WIN_OSNAME)) { return winMacAddress(winIpConfigCommand()). else { throw new IOException("OS not supported : " + os).getProperty("os. private final static String WIN_MACADDR_EXEC = "ipconfig /all".getLocalHost().exec("ifconfig").com/thread.getHostAddress().getRuntime().endsWith(localHost) && lastMacAddress != null) { return lastMacAddress.ParseException. } StringTokenizer tokenizer = new StringTokenizer(ipConfigOutput.startsWith("Linux")) { .nextToken().import java.hasMoreTokens()) { String line = tokenizer.util. // MAC OSX −−> else if(os. public final static String getMacAddress() throws IOException { String os = System.. } // other OS left as an exercise ! // LINUX −−> else if (os..printStackTrace(). } 12 Networking .printStackTrace().. private final static String WIN_MACADDR_REG_EXP = "^[0−9A−F]{2}−[0−9A−F]{2}−[0−9A−F]{2}−[0−9A−F]{2}−[0−9A−F]{2}−[0−9A−F]{2}$". // Process p = Runtime.getMessage()). // see if line contains IP address if (line. String lastMacAddress = null. try { if (os.. private final static String WIN_OSNAME = "Windows". throw new IOException(e.trim(). throw new ParseException(ex..UnknownHostException ex) { ex.. // .

println(" IP/Localhost: " + InetAddress.read(). buffer. } } } 12. if (!macAddressCandidate. return outputText. } String outputText = buffer.toString().getProperty("os.close(). System.out.out. } } ParseException ex = new ParseException ("cannot read MAC address from [" + ipConfigOutput + "]". StringBuffer buffer= new StringBuffer(). } private final static String winIpConfigCommand() throws IOException { Process p = Runtime. throw ex.trim(). stdoutStream.3 Get the workstation name/ip .3 Get the workstation name/ip 12.name")).out. } public final static void main(String[] args) { try { System.println("MAC ADDRESS"). for (..exec(WIN_MACADDR_EXEC). return true.) { int c = stdoutStream.append((char)c).length() != MACADDR_LENGTH) return false. InputStream stdoutStream = new BufferedInputStream(p.printStackTrace().// see if line contains MAC address int macAddressPosition = line.getRuntime().println(" MAC Address : " + getMacAddress()). } catch(Throwable t) { t.getLocalHost().printStackTrace(). System.out. continue. ex. if (c == −1) break. } private final static boolean winIsMacAddress(String macAddressCandidate) { if (macAddressCandidate.matches(WIN_MACADDR_REG_EXP)) return false. String macAddressCandidate = line.getHostAddress()).println(" OS : " + System.substring(macAddressPosition + 1). System. 0).getInputStream()). if (winIsMacAddress(macAddressCandidate)) { lastMacAddress = macAddressCandidate. if(macAddressPosition <= 0) continue.indexOf(":").

java. To list all the interfaces available on a workstation : [JDK1. while(e. java.InetAddress.*.4] import import import import java.getName()). Enumeration e2 = netface. while (e2. System.out. public class IPAdress { public void getInterfaces (){ try { Enumeration e = NetworkInterface. } public void say() { try { java..println ("e: " + e).println(i.io.*. System.html public class NetInfo { public static void main(String[] args) { new NetInfo().net. // IP address only } catch(Exception e){e. java.getNetworkInterfaces(). // name System.hasMoreElements()) { NetworkInterface netface = (NetworkInterface) e.getHostName()). } } } catch (Exception e) { System./javadetails/java−0390.println("Net interface: "+netface.InetAddress i = java.out.net.println(i). System.println(i.util.net.printStackTrace().} } } The output > java NetInfo realone/209.out.*.out.say().nextElement().rgagnon.72.out.142.3 Get the workstation name/ip .getHostAddress()).println("IP address: "+ip.out.112 Note: This may not work on Linux workstation.nio.hasMoreElements()){ InetAddress ip = (InetAddress) e2.getLocalHost(). } } public static void main(String[] args) { 12.142.72.toString()).112 realone 209.Current version of this HowTo : http://www.nextElement().getInetAddresses(). Search Sun's Bug Parade for a workaround.*. // name and IP address System.com/javadetails/.

.com/javadetails/.4 Find port number not in use . urlconnection. So pass it to your JVM as java −Dcomputername="%COMPUTERNAME%" . "netstat −an" list the ports currently in use.IPAdress ip = new IPAdress()..ttl (default: −1) Specified in java.getenv("COMPUTERNAME") 12. 12.20 Net interface: ppp0 IP address: /64.5 which can extract environment variable directly with System.html Once an application has performed network access (i.5 Disable DNS caching Current version of this HowTo : http://www./javadetails/java−0412. networkaddress. the DNS settings get cached so any subsequent operation will use the old settings even if the real settings have changed.168.org/assignments/port−numbers for a list of assigned numbers.115.147. To reset everything.68. etc).69 Windows A "low−tech" way to get the computer name (can be useful if there is no network card) is to use the environment variable COMPUTERNAME (at least on modern Windows installation). parsing of xml document with external references.getInterfaces().cache. ip. and the get the value with System. you have to restart the server since the the default setting JVM setting is to cache forever. There are 4 properties that can be used to override the default behaviour. } } The output > java IPAdress Net interface: lo IP address: /127.e.. 12.html On Windows.rgagnon.0.security to indicate the caching policy for successful name lookups from the name service.rgagnon. The value is specified as as integer to indicate the number of seconds to cache the successful lookup.iana..254.1 Net interface: eth0 IP address: /194.com/javadetails/./javadetails/java−0445.4 Find port number not in use Current version of this HowTo : http://www.0.getProperty("computername") or use the jdk1.0. Take a look at http://www.1 Net interface: eth1 IP address: /164.

6 Encode/Decode to/from Base64 Current version of this HowTo : http://www.negative.internet.negative.security to indicate the caching policy for un−successful name lookups from the name service.net.ttl" .ttl.7 Using javax. However. but can be set as a command−line option..setProperty("networkaddress.negative.cache. However. consider making a small donation to show your support for this Web site and its content.6 Encode/Decode to/from Base64 .*. ref : J2SE 1.net.ttl=10 or set the value in your code with java.cache.com/javadetails/. OutputStream b64os = MimeUtility. The value is specified as as integer to indicate the number of seconds to cache the failure for un−successful lookups.ttl This is a sun private system property which corresponds to networkaddress. the preferred way is to use the security property mentioned above.mail. sun.cache.inetaddr. "0").misc.ttl (default: 10) Specified in java.ttl=60 networkaddress. sun.cache./javadetails/java−0598.html As seen in this HowTo. but can be set as a command−line option.internet. public class Base64Utils { public static byte[] encode(byte[] b) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream().tt It takes the same value and has the same meaning.inetaddr. 12.4 Net properties If you find this article useful.cache.A value of −1 indicates "cache forever".encode(baos.MimeUtility import javax.security file located in %JRE%\lib\security networkaddress. A value of 0 indicates "never cache".BASE64Encoder/Decoder or creating your own Base64 handling are the best way to deal with Base64 encoding/decoding.ttl This is a sun private system property which corresponds to networkaddress. the preferred way is to use the security property mentioned above. import java.cache.security. You can set the required value in the java.MimeUtility.ttl=0 on the command line starting the JVM.negative.ttl on the command line.cache.write(b). 12.rgagnon. Written and compiled by Réal Gagnon ©1998−2006 [ home ] 12.mail. A value of −1 indicates "cache forever". "base64"). networkaddress. the sun.inetaddr. It takes the same value and has the same meaning. So you can disable caching by adding −Dsun. But you can't set the value of networkaddress. b64os.net.Security.io.

out. 86. 109. n).toString(res1)).println(new String(res1)).println(""). 86.out. InputStream b64is = MimeUtility.b64os.out.util.Base64. 51. res. 100.codec. 118] * string −−> realhowto */ } } 12. /* * output * realhowto base64 −> * [99. 82.encodeBase64(clearText.commons.arraycopy(tmp.decode(res1).length].println( java.decodeBase64(encodedText.8 Using Apache Commons Codec Apache Commons Codec provides implementations of common encoders and decoders such as Base64.org/codec/ import org. System. // Base64 encodedText = new String(Base64.Arrays. 118. 104. 98. } public static void main(String[] args) throws Exception { String test = "realhowto". 0. System.getBytes()))). 98. // // output : // Encoded: SGVsbG8gd29ybGQ= // Decoded:Hello world // } 12. return res.read(tmp). 104. 71.8 Using Apache Commons Codec . byte[] tmp = new byte[b.out. int n = b64is.decode(bais. return baos.apache. Download at http://commons. byte res1[] = Base64Utils. 51.toByteArray().println(test + " base64 −> " + java. public class Codec { public static void main(String[] args) { try { String clearText = "Hello world". System. 71.apache. System. 100. 104. Phonetic and URLs.out. 109.binary. 118. System.getBytes())).util.toString(res1) + " string −−> " + new String(res2)). } public static byte[] decode(byte[] b) throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream(b).getBytes()). 0.close(). Hex.Arrays.println("Encoded: " + encodedText). System. "Base64"). System.out. 82. 104. byte[] res = new byte[n].encode(test. String encodedText. 118] * cmVhbGhvd3Rv * [99. byte res2[] = Base64Utils.println("Decoded:" + new String(Base64.

Attributes attrs = ictx. System. Attribute attr = attrs.*. import import import java./javadetails/java−0452.dns.rgagnon.length.Hashtable. javax.DnsContextFactory").naming. env.exit( 99 ).*. if( attr == null ) return( 0 ).naming.jndi..sun.com/javadetails/.. return( attr.10 Lookup using MX record to validate mail server Current version of this HowTo : http://www.catch (Exception e) { e..printStackTrace().put("java.get( "MX" ).getAttributes( hostName.com has 1 mail servers 12.9 MiGBase64 .println(args[i] + " : " + e.println( args[i] + " has " + doLookup( args[i] ) + " mail servers" ). public class MXLookup { public static void main( String args[] ) { if( args. } } } static int doLookup( String hostName ) throws NamingException { Hashtable env = new Hashtable(). 12.net/.com rgagnon. "com.directory.html The best you can do to verify if an email address is real is to verify if there is a mail server registered to the domain name. DirContext ictx = new InitialDirContext( env ).length == 0 ) { System.initial".naming. } for( int i = 0.sourceforge.]" ).out.out. i++ ) { try { System.err.println( "Usage: MXLookup host [. } } } 12. javax.factory.util. } catch( Exception e ) { System.com realhowto. new String[] { "MX" }). i < args.size() ). http://migbase64. } } The output is >java MXLookup rgagnon.getMessage()).9 MiGBase64 • MiGBase64 is a very fast Base64 Codec written in Java.

com : DNS name not found [response code 3] From T. and the address is valid. it just accepts everything and relies on abc. their provider isp. the message gets forwarded. Others will return a failure even if the address exists but the command has been disables (although this is typically a 450 error). Orbaker. This is the point at which most servers will give up the dirt on whether or not an address is valid. more infos on that subject (thanks to him).com.*.com gets the message and when abc. then isp. mean that someone will at least SEE the message). Yahoo appears to use a store and forward mechanism to its own internal servers.naming. it have typically been disabled on most mail servers. Note that some servers (qmail) return 252 as a means of pleading the fifth. I suspect that hotmail is the same.*. imagine that you connect to isp. javax. you create the SMTP envelope.*. however. If these are not checked in the proper order. The MX records would look something like: MX 1 abc. there will be no errors for invalid addresses. If an envelope cannot be built.com agrees to set up a 'store and forward' scheme for their mail. java. you should get a 250 if the address is valid and a 550 if it isn't. java. Once you have connected. To prevent bounces and other mail errors if their connection or server should be down. 12.util.com Now. There are other methods by which to validate an email address to a higher degree of than just the mail server. BUT (and the code below doesn't do this) they must be tried from lowest preference to highest to be absolutely correct.com is not available. issue the HELO command and then send 'VRFY '.realhowto.io. Some recent servers don't even support this command as they are so frequently shut off. Because this was abused by spammers. If it is enabled. The reason for connecting in order of preference: Imagine ABC company has an Internet conneciton and runs their own mail server for abc.net. Two (better method): Connect to the servers determined by your code snippet. The mail server at isp.*. If abc.com doesn't have the actual user list to know which addresses are valid. When it works. we know that the address is invalid. thus conclusively verifying a yahoo address is not possible. import import import import java.com is again available. but you don't put anything in it.com MX 5 isp.com to sort out the bounces.com and try to send a message.9 MiGBase64 . It is not possible to verify an address on a domain that uses a catch−all account as the catch account will receive the mail (it does. One: Use the VRFY command (see RFCs 821/2821). connect to the server.

String f[] = x.getAttributes( hostName. return. if( attr == null ) throw new NamingException ( "No match for name '" + hostName + "'" ). // if we don't have an MX record. ArrayList res = new ArrayList(). (f[1].add( f[1] ). } // Huzzah! we have machines to try.flush(). } private static void say( BufferedWriter wr. DirContext ictx = new InitialDirContext( env ).naming.parseInt( pfx ).endsWith( ".write( text + "\r\n" ). } private static ArrayList getMX( String hostName ) throws NamingException { // Perform a DNS lookup for MX records in the domain Hashtable env = new Hashtable().*.charAt( 3 ) != '−' ) break. } return res.getAttributes ( hostName. int res = 0.length() − 1)). wr.get( "MX" ). res. Attributes attrs = ictx. 12.DnsContextFactory").getAll().initial".substring( 0.naming. } if ( line.dns. attr = attrs. while ( en.sun. NamingEnumeration en = attr.readLine()) != null ) { String pfx = line.hasMore() ) { String x = (String) en.next().size() == 0 )) { attrs = ictx.factory. try the machine itself if (( attr == null ) || ( attr.split( " " ).get( "A" ). Return them as an array list // NOTE: We SHOULD take the preference into account to be absolutely // correct.directory.9 MiGBase64 . public class SMTP { private static int hear( BufferedReader in ) throws IOException { String line = null. while ( (line = in.import javax. new String[] { "MX" }). try { res = Integer. String text ) throws IOException { wr.put("java.substring( 0. env." ) ) f[1] = f[1]. Attribute attr = attrs. new String[] { "A" }). This is left as an exercise for anyone who cares. } catch (Exception ex) { res = −1. } return res. 3 ).jndi. if ( f[1]. "com.

get( mx ).size() . res = hear( rdr ). "QUIT" ). rdr. it's not valid if ( pos == −1 ) return false. Socket skt = new Socket( (String) mxList. res = hear( rdr ).getInputStream() ) ). try { mxList = getMX( domain ).com>" ). // Now. try each mail exchanger until we get // a positive acceptance. } // Just because we can send mail to the domain. but if we can't. wtr. ArrayList mxList = null. "RCPT TO: <" + address + ">" ). hear( rdr ). "RSET" ). 25 ). say( wtr. say( wtr.close(). res = hear( rdr ). } catch (NamingException ex) { return false.com" ). for ( int mx = 0 . BufferedReader rdr = new BufferedReader ( new InputStreamReader( skt. if ( res != 220 ) throw new Exception( "Invalid header" ). valid = true. skt.getOutputStream() ) ). // If the address does not contain an '@'. say( wtr. It *MAY* be possible for one MX to allow // a message [store and forwarder for example] and another [like // the actual mail server] to reject it.size() == 0 ) return false. try { int res. // Isolate the domain/machine name and get a list of mail exchangers String domain = address. 12.9 MiGBase64 . This is why we REALLY ought // to take the preference into account. "MAIL res = hear( rdr if ( res != 250 sender address FROM: <tim@orbaker. doesn't mean that the // address is valid. hear( rdr ). ). "EHLO orbaker. BufferedWriter wtr = new BufferedWriter ( new OutputStreamWriter( skt. mx < mxList. if ( res != 250 ) throw new Exception( "Not ESMTP" ). // be polite say( wtr. do the SMTP validation.close(). it's a sure sign that it isn't if ( mxList. mx++ ) { boolean valid = false. ) throw new Exception( "Sender rejected" ).substring( ++pos ).} public static boolean isAddressValid( String address ) { // Find the separator for the domain name int pos = address. // validate the say( wtr.close().indexOf( '@' ). if ( res != 250 ) throw new Exception( "Address is not valid!" ).

} public static void main( String args[] ) { String testData[] = { "tim@orbaker.split( " " ). } } return false.net.util. 12. // Invalid address "nosuchaddress@yahoo. ctr < testData.} catch (Exception ex) { // Do nothing but try next host } finally { if ( valid ) return true. } return. } else { mailhost = f[0]. java. } Here my proposed fix : import import import import import java. ctr++ ) { System. and later if (hasMX) { mailhost = f[1]. I used something like: boolean hasMX = "MX".length is always 1. if ( f[1].me@nowhere.Boerner has this comments about this HowTo : The method SMTP::getMX() in the second example throws an ArrayIndexOutOfBoundsException while getting the mailhost via the "A" attribute at: while ( en.spam".hasMore() ) { String x = (String) en.net".*. String f[] = x.9 MiGBase64 .directory. for ( int ctr = 0 .io.naming." ) ) The "A" attribute returns only an address list.*.out. java.*. // Invalid domain name "arkham@bigmeanogre.length . javax.*.next().println( testData[ ctr ] + " is valid? " + isAddressValid( testData[ ctr ] ) ). } } S.naming.com". javax.*. so f.getID()).com" // Failure of this method }.equals(attr.endsWith( ". // Valid address "fail.

} private static ArrayList getMX( String hostName ) throws NamingException { // Perform a DNS lookup for MX records in the domain Hashtable env = new Hashtable(). } catch (Exception ex) { res = −1. ArrayList res = new ArrayList().factory. else if ( f[1].dns. try { res = Integer. attr = attrs.length == 1) mailhost = f[0]. (f[1].substring( 0. // THE fix ************* if (f.initial".jndi.getAttributes( hostName. if( attr == null ) throw new NamingException ( "No match for name '" + hostName + "'" ). try the machine itself if (( attr == null ) || ( attr. int res = 0.getAttributes ( hostName. Attribute attr = attrs. DirContext ictx = new InitialDirContext( env ).length() − 1)).parseInt( pfx ).getAll().write( text + "\r\n" ). else mailhost = f[1].put("java. Return them as an array list // NOTE: We SHOULD take the preference into account to be absolutely // correct. Attributes attrs = ictx.public class SMTPMXLookup { private static int hear( BufferedReader in ) throws IOException { String line = null. while ( (line = in.readLine()) != null ) { String pfx = line. } // Huzzah! we have machines to try. new String[] { "MX" }).split( " " ). This is left as an exercise for anyone who cares. while ( en.size() == 0 )) { attrs = ictx.DnsContextFactory").9 MiGBase64 . String x = (String) en. wr. return. String f[] = x. } return res. NamingEnumeration en = attr. String text ) throws IOException { wr. // THE fix ************* 12. new String[] { "A" }). } if ( line.substring( 0. "com.sun. env.get( "MX" ).next(). 3 ). // if we don't have an MX record. } private static void say( BufferedWriter wr.hasMore() ) { String mailhost.flush().charAt( 3 ) != '−' ) break." ) ) mailhost = f[1].naming.endsWith( ".get( "A" ).

size() . try each mail exchanger until we get // a positive acceptance. } return res. mx++ ) { boolean valid = false. "QUIT" ). try { int res. // Now. "EHLO rgagnon. } public static boolean isAddressValid( String address ) { // Find the separator for the domain name int pos = address. say( wtr. "RCPT TO: <" + address + ">" ). } // Just because we can send mail to the domain. BufferedWriter wtr = new BufferedWriter ( new OutputStreamWriter( skt. mx &lt.getOutputStream() ) ). hear( rdr ). but if we can't. do the SMTP validation. // Socket skt = new Socket( (String) mxList. ).size() == 0 ) return false. 12.substring( ++pos ). ) throw new Exception( "Sender rejected" ). res = hear( rdr ). if ( res != 250 ) throw new Exception( "Address is not valid!" ). // Isolate the domain/machine name and get a list of mail exchangers String domain = address. say( wtr.com>" ).getInputStream() ) ). for ( int mx = 0 . res = hear( rdr ). say( wtr. it's a sure sign that it isn't if ( mxList. // validate the say( wtr.res. mxList. This is why we REALLY ought // to take the preference into account. BufferedReader rdr = new BufferedReader ( new InputStreamReader( skt. res = hear( rdr ).get( mx ). "MAIL res = hear( rdr if ( res != 250 sender address FROM: <tim@orbaker.9 MiGBase64 . "RSET" ).indexOf( '@' ). // be polite say( wtr.add( mailhost ). hear( rdr ). // If the address does not contain an '@'.com" ). ArrayList mxList = null. doesn't mean that the // address is valid. if ( res != 250 ) throw new Exception( "Not ESMTP" ). It *MAY* be possible for one MX to allow // a message [store and forwarder for example] and another [like // the actual mail server] to reject it. } catch (NamingException ex) { return false. 25 ). try { mxList = getMX( domain ). it's not valid if ( pos == −1 ) return false. if ( res != 220 ) throw new Exception( "Invalid header" ).

printStackTrace()./javadetails/java−0079.. BufferedReader in = new BufferedReader 12. for ( int ctr = 0 .com myFriend@somewhere.io.close().com".close(). 25). import java.*. // Invalid domain name "arkham@bigmeanogre. } public void sendMail(String mailServer. } finally { if ( valid ) return true. } catch (Exception ex) { // Do nothing but try next host ex. public class SendElvisMail { public static void main(String s[]) { // // Send fake mail from Elvis Presley // // SendElvisMail [mail server] [recipient address] // mail server can be hostname or IP address // // ex. s[1]).valid = true. "you@acquisto.company.com" // Failure of this method }. } public static void main( String args[] ) { String testData[] = { "real@rgagnon.net". } return. String recipient) { try { Socket s = new Socket(mailServer. ctr < testData.qc.*. wtr. rdr. "fail.ca // SendElvisMail t = new SendElvisMail(). ctr++ ) { System.me@nowhere.sendMail(s[0].11 Send an email using the SMTP protocol . } } return false.close().length . // Invalid address "nosuchaddress@yahoo. skt. t.println( testData[ ctr ] + " is valid? " + isAddressValid( testData[ ctr ] ) ). } } 12.spam".net". SendElvisMail mail.rgagnon.11 Send an email using the SMTP protocol Current version of this HowTo : http://www.com/javadetails/.net.html import java.out.

12.io. s = in.out.net.html import java. "I'm alive.write(s + "\n"). } } } A good idea would be to download the JavaMail API from Sun if you're looking for a more object−oriented approach. out./javadetails/java−0080.getOutputStream(). send(in. "From: Elvis Presley <Elvis. } catch (Exception e) { e.out. "8859_1")). out. out. "RCPT TO: " + recipient). s.println(s). "\n"). send(out. "DATA").getInputStream().Presley@jailhouse.flush(). } } public void send(BufferedWriter out. String s) { try { out..12 Check if there is mail waiting Current version of this HowTo : http://www.println(s). send(out. put your real address here send(in. out. out.12 Check if there is mail waiting . out. "HELO theWorld"). "QUIT").*. System. "8859_1")). "\n.readLine().out. send(in. "Subject: In the ghetto").printStackTrace(). BufferedWriter out = new BufferedWriter (new OutputStreamWriter(s. } } public void send(BufferedReader in.(new InputStreamReader(s.printStackTrace().com/javadetails/. out. BufferedWriter out.*. Help me!"). String s) { try { out. // warning : some mail server validate the sender address // in the MAIL FROm command. "MAIL FROM: <Elvis.println(s). System.Presley@jailhouse. } catch (Exception e) { e. send(out.\n").rock>").flush().rock>"). } catch (Exception e) { e. send(in.printStackTrace(). send(in.rgagnon. public class CheckMail { 12. send (out.close(). import java.write(s + "\n"). // message body send(out. System.

int i = t. "USER " + user). } 12.readLine().out. out). String s. out. BufferedReader in = new BufferedReader( new InputStreamReader(s.12 Check if there is mail waiting . send(out.getOutputStream())).println ("There " + (i==1?"is " :"are ") + i + " message" +(i==1?"":"s")+ " waiting. receive(in). 110).printStackTrace().").getInputStream())). } } catch (Exception e) { e. receive(in)."). "LIST"). String pass) throws IOException { Socket s = new Socket(server.public static void main(String s[]) { // // CheckMail [mailServer] [user] [password] // try { CheckMail t = new CheckMail(). if (i==0) { System.write(s+"\n").flush(). } else { System. } return 0. } else return i. receive(in). send(out. BufferedWriter out) throws IOException { int i = 0. } public int getNumberOfMessages (BufferedReader in. while((s = receive(in)) != null) { if (!(s."))) { i++. receive(in). BufferedWriter out = new BufferedWriter( new OutputStreamWriter(s.checkMyMail(s[0]. String s) throws IOException { out. String user. } } private void send(BufferedWriter out. return getNumberOfMessages(in. "PASS " + pass). } private int checkMyMail (String server. send(out. s[1].equals(".println("No mail waiting.out. s[2]). } private String receive(BufferedReader in) throws IOException { return in.

com/javadetails/. send(out. mail. BufferedWriter out.println("No mail waiting. System. out.out.getInputStream())).println("*****"). 110).13 Receive email Current version of this HowTo : http://www. arg[2]).out.. } // // If the mail was removed from the server // (see getMail()) then we must COMMIT with // the "QUIT" command : // send(out.13 Receive email .println(msg). BufferedWriter out = new BufferedWriter( new OutputStreamWriter(s. System. String t = "". out./javadetails/java−0081.*.} 12.out. "QUIT"). BufferedReader in = new BufferedReader( new InputStreamReader(s.println("*****").net. j). while (((s = in. // } } catch (Exception e) { e.io.check(in.*. System. "RETR "+i).readLine()) != null) )))) { 12.out.login(in.html import java. j++) { String msg = mail. arg[1]. j <= i. } else { for (int j=1.println("Connect to " + arg[0] + ":110"). public class DisplayMail { public static void main(String arg[]) { // // usage : // DisplayMail [mailServer] [user] [password] // (will not delete mail on the server) // try { // connect on port 110 (POP3) System. } } public String get (BufferedReader in.out). if (i==0) { System.getOutputStream())).out.printStackTrace(). import java."). int i = mail.rgagnon. DisplayMail mail = new DisplayMail().get(in. Socket s = new Socket(arg[0]. int i) throws IOException { String s = "".

String user. BufferedWriter out) throws IOException { return getNumberOfMessages(in. receive(in). return s.13 Receive email . receive(in). } private void send(BufferedWriter out. "HELO theWorld"). } // // To remove the mail on the server : // send(out.println(s). BufferedWriter out.equals(". } public int getNumberOfMessages (BufferedReader in. } private int check (BufferedReader in. } private void login (BufferedReader in. } } return 0. String s) throws IOException { System.write(s+"\n"). receive(in).out. // return t. send(out. } private String receive(BufferedReader in) throws IOException { String s = in. send(out. out. "LIST"). out. while((s = receive(in)) != null) { if (!(s.readLine(). System.println(s). } } 12. // receive(in). send(out. send(out.out. receive(in). out).t += s + "\n". "PASS " + pass). "DELE "+i). } else { return i. "USER " + user)."))) { i++. String pass) throws IOException { receive(in). BufferedWriter out) throws IOException { int i = 0.flush(). String s.

io.0"). out. static Socket socket.getInputStream(). // warning : some mail server validate the sender address // in the MAIL FROM command. String recipient) { System.com/javadetails/.getOutputStream().html In this example. String boundary = "DataSeparatorString". /* Name of file to be sent. // thanks to P−Y Colle for the tip! sendln(in. "DATA"). "8859_1")).. "MAIL FROM: "). "8859_1")). // to have more than one recipient.out.Presley@jailhouse. "RCPT TO: <" + recipient2 + ">" ). // here you are supposed to send your username sendln(in.sendMail(s[0]. sendln(in. sendln(out.14 Send email with an attachment . "HELO theWorld"). out. we are sending as attachment this image : import java. put your real address here sendln(in.. In this example.rock>").net. // etc. "RCPT TO: <" + recipient3 + ">" ). */ String FileName = "gumby. s[1]). out. "MIME−Version: 1. static PrintStream prout. import java.gif". sendln 12. t. BufferedReader in = new BufferedReader (new InputStreamReader(s.*. out. sendln(out. static DataInputStream in. // sendln(in.. static DataOutputStream out./javadetails/java−0083. repeat // sendln(in. "From: Elvis Presley <Elvis. "Subject: remember me"). 25). public class TestMailMIME { static int SMTPport = 25.rgagnon.*. out. Elvis is sending a GIF of his old Gumby friend.12. public static void main(String s[]) { /* ** TestMailMIME [server] [recipient] */ TestMailMIME t = new TestMailMIME().println("Send mail with attached file "). out. "RCPT TO: <" + recipient + ">" ). The attachment is encodded using the BASE64 algorithm. BufferedWriter out = new BufferedWriter (new OutputStreamWriter(s.14 Send email with an attachment Current version of this HowTo : http://www. sendln(out. try { Socket s = new Socket(mailServer. } public void sendMail(String mailServer.

allowing 6 bits for each character so the character "m" with a Base64 value of 38.io. String s) { try { out.out. "\r\n−−" + boundary).close(). } } } And the MIMEBase64 class import java. sendln(in. // send the GIF sendln(out. String s) { try { out.(out.printStackTrace(). } } public void sendln(BufferedReader in. MIMEBase64.*. "Content−Disposition: attachment. sendln(out. is 100110. } catch (Exception e) { e.". sendln(out."). "Content−Type:image/gif.printStackTrace(). out. public class MIMEBase64 { /* Base64 uses a 65 character subset of US−ASCII.printStackTrace(). out.flush(). "\r\n−−" + boundary). out). sendln (out. // System. sendln(out. sendln(in. "Content−Type: multipart/mixed.flush(). } } public void sendln(BufferedWriter out. s.write(s + "\r\n"). With a text string. sendln(out.println(s). body "Content−Type: text/plain.out. Help me!\r\n\r\n").out. sendln(out. "Content−transfer−encoding: base64\r\n").14 Send email with an attachment .println(s). "I'm alive. "\r\n−−" + boundary ). "QUIT"). boundary=\"" + boundary +"\"").filename=\""+FileName+"\""). sendln(out.println(s). // Send the sendln(out. charset=\"us−ascii\"\r\n"). BufferedWriter out. System. out.encode(FileName. // System.readLine(). when represented in binary form. out. } catch (Exception e) { e. let's say "men" is encoded this 12.write(s + "\r\n"). name="+FileName). s = in. "\r\n\r\n−−" + boundary + "−−\r\n"). } catch (Exception e) { e.

"j"."e"."0"."V"."3"."G". we use the special character "=" to pad until 4 base64 characters is reached."D"."M". "w"."K"."Y"."y"."Z"."4"."P"."5"."B"."o". To encode one or two then."a".14 Send email with an attachment ."h". (AND to fill the missing bits) = = (two paddings are added) Finally."q"."W"."1"."m"."I"."/" 12. The character "m" has the decimal value of 109 The character "e" has the decimal value of 101 The character "n" has the decimal value of 110 When converted to binary the string looks like this : m e n 01101101 01100101 01101110 These three "8−bits" are concatenated to make a 24 bit stream 011011010110010101101110 This 24 bit stream is then split up into 4 6−bit sections 011011 010110 010101 101110 We now have 4 values."k"."F". These binary values are converted to decimal form 27 22 21 46 And the corresponding Base64 character are : b W V u The encoding is always on a three characters basis (to have a set of 4 Base64 characters)."X"."H"."f"."6". "g"."r"."t". */ static String BaseTable[] = { "A"."p"."d"."b"."N"."O"."l". MIME specifies that lines are 76 characters wide maximum."s"."C"."T"."u"."9"."v"."2". encode "me" 01101101 01100101 0110110101100101 011011 010110 0101 111111 011011 010110 010100 b W U b W U so "bWU=" encode "m" 01101101 011011 01 111111 011011 010000 b Q (AND to fill the missing bits) = ("=" is the padding character) is the base64 equivalent."z"."S"."+"."U"."8"."R"."i"."J"."c"."x"."n"."7". "Q". ex."E".is what happens : The text string is converted into its US−ASCII value."L".

public static void encode(String filename.}. send(out. BaseTable[buf[0]]). while ( i < k ) { buf[0] = (byte)(( bytes[i] &0xFC) >> 2). buf[3] = (byte)( bytes[i+2] &0x3F). Harder to understand but more compact. BaseTable[buf[2]]). // current linelength 0. } // deals with with the padding . send(out.BaseTable[buf[0]]+BaseTable[buf[1]]+ BaseTable[buf[2]]+BaseTable[buf[3]]). buf[1] = (byte)(((bytes[k] &0x03) << 4) | ((bytes[k+1] &0xF0) >> 4))... send(out. int int int int int n3byt nrest k linelength i = = = = = // no bytes to encode!?! // array of base64 characters n / 3. /* The above code can be written in more "optimized" way. FileInputStream fin = new FileInputStream(filename).. Tordera for the tip! buf[0]= (byte)(b[i] >> 2). Thanks to J. // the remaining bytes from the grouping n3byt * 3.. "\r\n").length())]. if (n < 1) return. } i += 3. */ if ((linelength += 4) >= 76) { send(out. buf[1]= (byte)(((b[i] &0x03) << 4)|(b[i+1]>> 4)). BaseTable[buf[3]]). // how 3 bytes groups? n % 3. buf[1] = (byte)(((bytes[i] &0x03) << 4) | ((bytes[i+1] &0xF0) >> 4)). buf[3]= (byte)(b[i+2] &0x3F). buf[2] = (byte)(((bytes[i+1] &0x0F) << 2) | ((bytes[i+2] &0xC0) >> 6)). byte buf[] = new byte[4].14 Send email with an attachment . send(out. 12. // we are doing 3 bytes at a time 0. linelength = 0. } else if (nrest==1) { // 1 byte left buf[0] = (byte)((bytes[k] &0xFC) >> 2). send(out. if (nrest==2) { // 2 bytes left buf[0] = (byte)(( bytes[k] &0xFC) >> 2). buf[2] = (byte)(( bytes[k+1] &0x0F) << 2). BufferedWriter out) { try { File f = new File(filename).read(bytes). int n = fin. buf[2]= (byte)(((b[i+1] &0x0F)<< 2)|(b[i+2]>> 6)). BaseTable[buf[1]]). // read the entire file into the byte array byte bytes[] = new byte[(int)(f. // index // do the 3−bytes groups .

BaseTable[buf[1]]). String recipient) { System. "MAIL FROM: <real@gagnon.flush().0"). sendln(in.buf[1] = (byte)((bytes[k] &0x03) << 4)..printStackTrace(). out. } } } If Elvis want to send a GIF and a text file about his Gumby old friend then he would change his sendMail() for something like this . . } else { send(out.com>"). BufferedReader in = new BufferedReader (new InputStreamReader(s.getOutputStream(). sendln(in.printStackTrace(). out.print(s). 12. String FileName2 = "gumby.14 Send email with an attachment .gif". "MIME−Version: 1. } out. Claerman for the bug fix here! if (nrest==2) { send(out. "=").txt". } if (nrest > 0) { // send the padding if ((linelength += 4) >= 76) send(out. send(out. BaseTable[buf[2]]).out.. } send(out. System. "8859_1")). "DATA").. out. "HELO world"). "RCPT TO: <" + recipient + ">" ). String s) { try { out. "8859_1")).. } catch (Exception e) { e. out. "\r\n"). BufferedWriter out = new BufferedWriter (new OutputStreamWriter(s.write(s). "="). public void sendMail(String mailServer. try { Socket s = new Socket(mailServer. 25). } } public static void send(BufferedWriter out. // here you are supposed to send your username sendln(in. } catch (Exception e) { e.getInputStream(). /* Name of files to be sent. send(out. sendln(out. */ String FileName1 = "gumby. String boundary = "DataSeparatorString".out.println("Send mail with attached file"). // Thanks to R. sendln(in. BaseTable[buf[0]]).

.Properties. "\r\n−−" + boundary).15 Send email with JavaMail . name="+FileName1). sendln(out.printStackTrace(). sendln(out. s."Content−Type: multipart/mixed."Content−Disposition: attachment. import java.filename=\""+FileName1+"\""). it is very short! NOTE: Check this related HowTo. // sendln // (out. NOTE: A compact algorithm to encode string as Base64 can be found here. "\r\n−−" + boundary).".com/javadetails/.rgagnon. MIMEBase64. out). "Content−Type: text/plain.").sendln(out. sendln (out. // done sendln(in. "Content−Type: text/plain.15 Send email with JavaMail Current version of this HowTo : http://www.filename=\""+FileName2+"\""). } } .close(). "\r\n" + "−−" + boundary ). out. sendln(out. sendln(out.Presley@jailhouse. Check out the Javascript. 12. "From: Elvis Presley <Elvis. sendln(out./javadetails/java−0321. "\r\n\r\n−−" + boundary + "−−\r\n").internet. "Content−Disposition: inline.rock<"). "Content−Transfer−Encoding: base64\r\n"). out). Help me!\n\n"). sendln(out. You need 2 jars : mail. sendln(in. boundary=\"" + boundary +"\"").. charset=\"us−ascii\"\r\n"). sendln (out.*. It's a good idea to read the JavaMail FAQ. // send the GIF sendln(out. out.mail. name="+FileName2). MIMEBase64. sendln(out.encode(FileName2. "Content−transfer−encoding: base64\r\n").jar. } catch (Exception e) { e. "Content−Type:image/gif. "Subject: remember me"). name="+FileName2).encode(FileName1..jar and activation.*. sendln(out. sendln(out. 12. "Content−Disposition: attachment. // the text file sendln(out.util. // to send the file as an attachment instead of "inline" use : // sendln // (out. "Content−Type: text/plain. sendln(out.mail.filename=\""+FileName2+"\""). Simple email import javax.html The JavaMail API can found here. "QUIT"). "I'm alive. import javax.

} } HTML Email import javax.mail. Session mailSession = Session. message. "smtp"). transport.TO)). 12.sendMessage(message. props.internet.setProperty("mail.password".RecipientType. props.connect().org")). message. props.internet.Properties. ""). transport. message.RecipientType. new InternetAddress("elvis@presley.org")).setProperty("mail.user". null).*. message.transport.transport.*.getDefaultInstance(props. "smtp"). "emailuser").setSubject("Testing javamail plain").class SimpleMail { public static void main(String[] args) throws Exception{ Properties props = new Properties().getTransport().RecipientType. "text/plain").getRecipients(Message.*.getRecipients(Message. "mymail. message.mail. import java. transport. import javax.activation. message. message.setContent ("This is a test <b>HOWTO<b>". transport.15 Send email with JavaMail .protocol".setProperty("mail.*. Transport transport = mailSession.host". MimeMessage message = new MimeMessage(mailSession). class SimpleHTMLMail { public static void main(String[] args) throws Exception{ Properties props = new Properties(). Session mailSession = Session. Transport transport = mailSession.connect().mail. null).org"). message. transport.getTransport().TO)).addRecipient(Message.getDefaultInstance(props.setProperty("mail.setSubject("Testing javamail html").setProperty("mail.RecipientType.util. props.DataHandler.user". javax.server.activation.setContent("This is a test". props. javax.mail. MimeMessage message = new MimeMessage(mailSession). ""). javax.org"). "emailuser"). props.close(). "mymail. props.protocol".setProperty("mail. new InternetAddress("elvis@presley.TO. "text/html.sendMessage(message. transport. props.password". charset=ISO−8859−1"). } } Email with attachment import import import import javax.FileDataSource.setProperty("mail.setProperty("mail.host".server.TO.close().addRecipient(Message.

getName()).TO.server.java").mail.getRecipients(Message.mail. "smtp"). props.setContent(mp). javax. import java.setSubject("Testing javamail with attachment").setDataHandler(new DataHandler(fds)).password". javax. props.setProperty("mail.*.transport.getTransport(). "emailuser"). textPart. } } 12. Properties props = new Properties().host".com/javadetails/.org")).user". "").16 Send email with authentication .protocol". transport.mail.myserver.PasswordAuthentication. FileDataSource fds = new FileDataSource("SimpleMailWithAttachment. MimeMessage message = new MimeMessage(mailSession).close(). transport.setProperty("mail.setProperty("mail. public class SimpleMail { private static final String SMTP_HOST_NAME = "smtp. attachFilePart.Properties.16 Send email with authentication Current version of this HowTo : http://www.sendMessage(message. private static final String SMTP_AUTH_USER = "myusername".connect().RecipientType. mp.addRecipient(Message.Properties. message.addBodyPart(textPart).. message.html import import import import javax. null).mail. props.util.setDebug(debug). attachFilePart. javax. Transport transport = mailSession. class SimpleMailWithAttachment { public static void main(String[] args) throws Exception{ boolean debug = false.setFileName(fds. Multipart mp = new MimeMultipart(). Session mailSession = Session.internet.setProperty("mail.setContent("<h1>Check attachment</h1>". mailSession. MimeBodyPart textPart = new MimeBodyPart(). MimeBodyPart attachFilePart = new MimeBodyPart()./javadetails/java−0538.import java.util.addBodyPart(attachFilePart). mp.Authenticator. "text/html"). "mymail.com". props.TO)). new InternetAddress("elvis@presley.org").*. transport.rgagnon.RecipientType. message. message. 12.getDefaultInstance(props.

protocol". public static void main(String[] args) throws Exception{ new SimpleMail().*.Authenticator { public PasswordAuthentication getPasswordAuthentication() { String username = SMTP_AUTH_USER. props. new InternetAddress("elvis@presley. javax.getTransport().getDefaultInstance(props./javadetails/java−0458.1.org")). transport.TO)). Authenticator auth = new SMTPAuthenticator().net variety.connect(). "smtp"). Transport transport = mailSession.io.getRecipients(Message.sendMessage(message. password). 12.util. message.mail package and is different from the java.. public class ReadEmail { public static void main(String args[]) throws Exception{ display(new File("C:\\temp\\message.transport. props. MimeMessage message = new MimeMessage(mailSession). transport. which didn't have the java. return new PasswordAuthentication(username. This kind of file can be read and parsed by JavaMail. } public void test() throws Exception{ Properties props = new Properties().smtp. javax.RecipientType.mail.17 Handle EML file with JavaMail Current version of this HowTo : http://www.eml")). props.host". java. "true").internet.setContent("This is a test". transport.TO. } } } NOTE : The JavaMail Authenticator is found in the javax.*. message.mail. auth).RecipientType.put("mail.html When saving an email to a file. String password = SMTP_AUTH_PWD.setDebug(true).rgagnon.close().net class of the same name.test().setFrom(new InternetAddress("me@myhost.private static final String SMTP_AUTH_PWD = "mypwd".auth". the resulting file has an eml extension (email files−−which are in RFC 822 format). The two don't share the same Authenticator as the JavaMail API works with Java 1.put("mail.addRecipient(Message. "text/plain").*.17 Handle EML file with JavaMail . message. SMTP_HOST_NAME). import import import import java. } private class SMTPAuthenticator extends javax.mail. // uncomment for debugging infos to stdout // mailSession. Session mailSession = Session.*.org")).put("mail. message. 12.com/javadetails/.smtp.

226. consider making a small donation to show your support for this Web site and its content.com User−Agent: Mozilla/5.4) Gecko/20030624 Netscape/7.out.protocol".out.−!!T@1"! This is an example for HowTo Running the above HowTo gives this output : Subject : Example for HowTo From : real gagnon −−−−−−−−−−−−−− Body : This is an example for HowTo If you find this article useful. props.getProperties(). 1 Feb 2004 13:25:33 −0500 (EST) Date: Sun. charset=us−ascii.getSubject()).1. MimeMessage message = new MimeMessage(mailSession.9. en MIME−Version: 1.3/8. } } A typical eml looks like this : X−Mozilla−Status: 0001 X−Mozilla−Status2: 00000000 Received: from tomts25−srv.put("mail. System.out. Sun.println("Subject : " + message.com").println("From : " + message. props. System. U.net (tomts25.getContent()). "smtp. source). en−US.getDefaultInstance(props.com (8. System.getFrom()[0]). format=flowed Content−Transfer−Encoding: 7bit X−UIDL: oP#!!c]^!!1.net [209.host".9. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 12.println("Body : " + message.17 Handle EML file with JavaMail . "smtp").transport.dummydomain. System.3) with ESMTP id NAA07621 for .175. Session mailSession = Session.} public static void display(File emlFile) throws Exception{ Properties props = System. rv:1.0 (Windows.188]) by tactika. null).com Subject: Example for HowTo Content−Type: text/plain.put("mail.out.bellnexxia.1 (ax) X−Accept−Language: en−us. Windows NT 5. 01 Feb 2004 13:31:40 −0500 From: real gagnon Reply−To: real@rgagnon.0 To: real@rgagnon.println("−−−−−−−−−−−−−−").bellnexxia. InputStream source = new FileInputStream(emlFile).

.RecipientType. Properties props = new Properties().Properties.TO.host". props.internet. props.setProperty("mail. import javax.host". props.com")).com").mail..setProperty("mail.*. "smtp. import javax.setProperty("mail.out.setProperty("mail.user".protocol".TO)).mymailserver.Properties.out.sendMessage(message.setProperty("mail.mymailserver..util. transport..").*.setContent("<h1>Hello world</h1>".RecipientType.rgagnon. Transport transport = mailSession. Session mailSession = Session. } } One approach to include images in the mail body is to use the IMG tag and make the images available on a server.mail.user"."). message.com/javadetails/. "smtp.getTransport(). transport. "mypwd").addRecipient(Message.. class SimpleMail1 { public static void main(String[] args) throws Exception{ System.com")).transport. mailSession.setDebug(true).*.setProperty("mail. "smtp").println("Sending mail.connect().getTransport(). props. message.com"). Session mailSession = Session.getRecipients(Message. "myuser").html It's easy to send HTML mail with JavaMail. import javax.setSubject("HTML mail with images").password".18 Send HTML mail with images (Javamail) Current version of this HowTo : http://www. Properties props = new Properties().getDefaultInstance(props. Transport transport = mailSession. new InternetAddress("you@receiver. import javax.protocol".transport.password". "text/html"). MimeMessage message = new MimeMessage(mailSession). null). null). message. props.18 Send HTML mail with images (Javamail) . 12.println("Sending mail.setFrom(new InternetAddress("me@sender. "mypwd").12.internet.util. props. "smtp"). import java. props.setProperty("mail.setProperty("mail. message. message. "myuser"). props.*. class SimpleMail { public static void main(String[] args) throws Exception{ System. mailSession.setDebug(true). import java./javadetails/java−0504. transport. Simply set the content type to "text/html".close().mail.getDefaultInstance(props.mail.

message.setContent ("<h1>This is a test</h1>" + "<img src=\"http://www. To protect your privacy.user". transport. message. props.out.com"). Session mailSession = Session.mail. new InternetAddress("you@receiver.setFrom(new InternetAddress("me@sender. props. String htmlText = "<H1>Hello</H1><img src=\"cid:image\">".gif\">". class SimpleMail2 { public static void main(String[] args) throws Exception{ System.util. import javax. "text/html"). new InternetAddress("you@receiver.*. spammers have used this mechanism as a sneaky way to record who visits their site (and mark your email as valid).mymailserver.getTransport().com")).password". message. the BODY and the embedded image // MimeMultipart multipart = new MimeMultipart("related").setContent(htmlText.addRecipient(Message.setProperty("mail.rgagnon.setDebug(true)..connect().setProperty("mail. "smtp"). props. // first part (the html) BodyPart messageBodyPart = new MimeBodyPart().mail.sendMessage(message.TO. import java. "text/html"). "mypwd"). MimeMessage message = new MimeMessage(mailSession). "myuser").protocol". many Web−based (and other) email clients don't display images in HTML emails.setProperty("mail.addRecipient(Message. Transport transport = mailSession. An alternative to placing absolute URLs to images in your HTML is to include the images as attachments to the email. props. // // This HTML mail have to 2 part.RecipientType. mailSession.RecipientType.MimeMessage message = new MimeMessage(mailSession).com")).").Properties.println("Sending mail.setFrom(new InternetAddress("me@sender.com")). transport. Unfortunately. transport. The HTML can reference the image in an attachment by using the protocol prefix cid: plus the content−id of the attachment.activation.com")).RecipientType. null).host".18 Send HTML mail with images (Javamail) .transport.TO.*. message.getRecipients(Message. message. "smtp. } } The browser accesses these images just as if it were displaying an image in a Web page.setSubject("HTML mail with images").internet.getDefaultInstance(props.. import javax. messageBodyPart.setSubject("HTML mail with images"). message.TO)).com/images/jht.setProperty("mail. 12. Properties props = new Properties().*. import javax. message. message.close().

net/ and http://quintanasoft. mailSession.setContent(multipart). DataSource fds = new FileDataSource ("C:\\images\\jht.RecipientType.setHeader("Content−ID".rgagnon. transport. consider making a small donation to show your support for this Web site and its content. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 12. // second part (the image) messageBodyPart = new MimeBodyPart(). message.setDebug(true).getDefaultInstance(props. 12. messageBodyPart. These mock−ups are designed to act a mail server but the actual email is not delivered to the mail recipient which can be useful in a testing stage.19 Debug a Javamail Program . // put everything together message.TO)).com/javadetails/.sendMessage(message. // add it multipart.out.setDataHandler(new DataHandler(fds)).connect(). null). messageBodyPart. This setting puts the Javamail classes in verbose mode to System.gif").// add it multipart. transport.addBodyPart(messageBodyPart)."<image>").getRecipients(Message./javadetails/java−0552.. Use a Javamail server mock−up to act as "in−memory" mail server : See https://mock−javamail. you can detect if your firewall is blocking your connection.com/dumbster/.dev.addBodyPart(messageBodyPart).19 Debug a Javamail Program Current version of this HowTo : http://www. Verify connectivity to the MailServer with Telnet : telnet mymailserver 25 for example.html Set the Javamail DEBUG mode "on" : Session mailSession = Session. } } If you find this article useful.java.close(). transport.

MimeMessage message = new MimeMessage(mailSession). String SMTP_AUTH_PWD = "mypwd".smtps.close().put("mail.internet. "smtps").put("mail.put("mail.put("mail. // props.RecipientType. public class SimpleSSLMail { private private private private static static static static final final final final String SMTP_HOST_NAME = "smtp.getDefaultInstance(props). It's the case for GMAIL for example.setDebug(true). props.com". props.TO.TO)).*.mail.getTransport().org")).smtps.smtps. message.20 Send email with SMTPS (eg.com". message.put("mail. "false"). } } The property props. transport.transport.20 Send email with SMTPS (eg. Transport transport = mailSession.com/javadetails/. } public void test() throws Exception{ Properties props = new Properties(). Google GMail) (Javamail) Current version of this HowTo : http://www. import java. props. import javax. transport. mailSession. 12. message. Google GMail) (Javamail) . "false"). "text/plain").rgagnon.connect (SMTP_HOST_NAME.Properties.auth". public static void main(String[] args) throws Exception{ new SimpleSSLMail().*. SMTP_AUTH_PWD).protocol". import javax.host".smtps. SMTP_HOST_PORT.html It's not uncommon that the outgoing mail needs to be encrypted using the SMTPS protocol.. int SMTP_HOST_PORT = 465.getRecipients(Message. String SMTP_AUTH_USER = "myaccount@gmail.quitwait". message. "true").12.mail.4 to use the SMTPS protocol./javadetails/java−0570. SMTP_HOST_NAME).sendMessage(message.gmail. Session mailSession = Session.test(). new InternetAddress("elvis@presley.addRecipient(Message.setContent("This is a test". SMTP_AUTH_USER. You need Javamail 1.util.setSubject("Testing SMTP−SSL"). transport.RecipientType.quitwait".

quitwait.com (POP3 − port 110) Outgoing Mail Server − smtp.SSLException: Unsupported record version Unknown−50.com (SMPTS SSL enabled..smtps.1 Settings for well known mail providers Yahoo Incoming Mail Server − pop..com (POP3S SSL enabled./javadetails/java−0471.com").html Properties props = new Properties(). messageBodyPart. messageBodyPart.rgagnon. port 465) 12.null).setText("Here is your plain text message").setFrom(from).html This setting. InternetAddress to = new InternetAddress("to@you.mail.gmail.setContent(htmlText. causes the transport to wait for the response to the QUIT command.20. multipart.com"). MimeMessage message = new MimeMessage(session). ref : http://java. message. mail. The property quitwait means If set to false.sun.addBodyPart(messageBodyPart).host".yahoo. // HTML TEXT messageBodyPart = new MimeBodyPart().com/javadetails/. port 995) Outgoing Mail Server − gmail.com (SMPTP − port 25) Google GMail Incoming Mail Server − pop. InternetAddress from = new InternetAddress("from@me. is not required anymore! (july2007) 12. nested exception is: javax. The mail is sent but the exception is unwanted.20.setSubject("I am a multipart text/html email" ). If set to true (the default). Session session = Session.TO... String htmlText = "<H1>I am the html part</H1>".com/products/javamail/javadocs/com/sun/mail/smtp/package−summary.1 Settings for well known mail providers .addRecipient(Message.49 . the QUIT command is sent and the connection is immediately closed.smtp. "text/html").is required to get rid of a strange SSL exception : javax.getInstance(props. Multipart multipart = new MimeMultipart(). message..21 Mix plain text and HTML content in a mail Current version of this HowTo : http://www.MessagingException: Exception reading response. 12. // PLAIN TEXT BodyPart messageBodyPart = new MimeBodyPart(). to).RecipientType. props.net.put("mail.yahoo.mail. message.mail.ssl. "MYMAILSERVER").

22 Check if a file was modified on the server . public class URLUtils { public static void main(String s[]) { System.*.printStackTrace().println(URLUtils. long timestamp = 0.1] import java. re−open an URLConnection ** to the same file to check if the timestamp is different ** with the getLastModified() method. System. Transport. uc. message. } catch (Exception e) { e.com/howto.html [JDK1. import java.gif").openConnection(). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 12.*.out. } } 12.html")).multipart.exists("http://www.net.com/javadetails/. If you find this article useful.io.out.22 Check if a file was modified on the server Current version of this HowTo : http://www..com/pagenotfound./javadetails/java−0059. /* output : true false */ } 12.setUseCaches(false).rgagnon.setContent(multipart). "test.getLastModified().addBodyPart(messageBodyPart).exists("http://www.rgagnon.com/javadetails/. */ timestamp = uc.send(message).println(URLUtils.23 Check if a page exists Current version of this HowTo : http://www. try { u = new URL(getDocumentBase().html URL u =null.html")).rgagnon. URLConnection uc = u.rgagnon. /* ** use timestamp has a reference../javadetails/java−0069. consider making a small donation to show your support for this Web site and its content.

public class URLUtils { public static void main(String s[]) { System.com")).getResponseCode() == HttpURLConnection.put("http.printStackTrace(). systemSettings.getResponseCode() == HttpURLConnection. 12. } public static boolean exists(String URLName){ try { Properties systemSettings = System. "80") .Properties. String encodedUserPwd = encoder. // note : you may also need // HttpURLConnection.openConnection(). con.rgagnon. } } } Thanks to Steve B.proxyHost".local") .out. systemSettings. // sun.put("proxySet".printStackTrace(). return false.* class // Sun strongly advises not to use them since they can // change or go away in a future release so beware.yahoo.getResponseCode() + " : " + con. con. System.println(exists("http://www. } catch (Exception e) { e.println (con.util.22 Check if a file was modified on the server .HTTP_OK).net. for the bug fix! The following is doing the same thing but this time we identify ourself to a proxy. System.misc.setFollowRedirects(false).println(exists("http://www.out.openConnection().out. URL u = new URL(URLName). import java.proxyPort".BASE64Encoder encoder = new sun.put("http.public static boolean exists(String URLName){ try { HttpURLConnection.*. "Basic " + encodedUserPwd).setRequestProperty ("Proxy−Authorization".HTTP_OK).*. return (con.mycompany. return (con.getResponseMessage()). // // it's not the greatest idea to use a sun.io.setRequestMethod("HEAD"). import java.getProperties().encode("domain\\username:password". con. systemSettings. return false. HttpURLConnection con = (HttpURLConnection) u. import java.misc. } catch (Exception e) { e.misc. See also this HowTo.com")).setRequestMethod("HEAD").BASE64Encoder()."proxy.getBytes()). "true").setInstanceFollowRedirects(false) HttpURLConnection con = (HttpURLConnection) new URL(URLName).

proxyPort".setProperties(systemSettings).html You have to set the following properties : http..Properties. String encoded = new String (Base64.com/javadetails/. System.put("http. Properties systemSettings = System. The following example dumps the content of a URL but before we identify ourself to the proxy import java.util.proxyhost=myproxyserver.getProperties(). import java.sun.proxyHost specified) http.util.setProperties(systemSettings).proxyport=80 MyJavaApp Or in your source : import java.} } } 12. Properties systemSettings = System.proxyPort (default: 80 if http.html.nonProxyHosts (default: <none>) NOTE: proxyHost. System.connect().getBytes())).*. systemSettings.getProperties(). NOTE: For a base64 function. 12. systemSettings./javadetails/java−0085.base64Encode(new String("username:password"). .24 Connect through a Proxy Current version of this HowTo : http://www. see this How−to.net. You might need to identify yourself to the proxy server. uc.com").". import java.com −Dhttp.com/j2se/1. you have to prefix them with "http.put("http. uc..io. One way is to use the HTTP property "Proxy−Authorization" with a username:password base64 encoded. You can set the required properties when starting the JVM for a JAVA application from the command line: java −Dhttp. URLConnection uc = url.4/docs/guide/net/properties.proxyHost".Properties.24 Connect through a Proxy .. "myProxyServer. "Basic " + encoded). "80").. proxyPort are deprecated. .*.. NOTE: Those properties are documented here : http://java.openConnection (). URL url=new URL("http://someserver/somepage").rgagnon.proxyHost (default: <none>) http.setRequestProperty("Proxy−Authorization".

// sun.yahoo. } } } With JDK1.BASE64Encoder().net. systemSettings.put("http.mydomain.println("**************"). URL u = new URL(URLName). // // it's not the greatest idea to use a sun.local") .toCharArray())."password". System. URLUtils.dump("https://www.com").read(b. 12. byte [] b = new byte[1].dump("http://www.getProperties().misc.24 Connect through a Proxy .getBytes()). con.openConnection().put("http. while(−1 != di.proxyHost". System.Authenticator can be used to send the credentials when needed.out. systemSettings.encode("mydomain\\MYUSER:MYPASSWORD".put("http.setRequestProperty ("Proxy−Authorization".print(new String(b)).proxyHost".println("**************"). FileOutputStream fo = null. Authenticator.misc. systemSettings. When no username/password are provided then popup is shown to ask for the credentials.mydomain. the java. systemSettings. "Basic " + encodedUserPwd).getInputStream()). // PROXY Properties systemSettings = System. byte [] b = new byte[1].local") . // PROXY −−−−−−−−−− di = new DataInputStream(con."proxy. "80") .put("http. public static void dump(String URLName){ try { DataInputStream di = null. HttpURLConnection con = (HttpURLConnection) u. FileOutputStream fo = null."proxy.0. // PROXY Properties systemSettings = System. "80") .1)) { System.public class URLUtils { public static void main(String s[]) { URLUtils. String encodedUserPwd = encoder.proxyPort".misc. } public static void dump(String URLName){ try { DataInputStream di = null.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("mydomain\\username".* class // Sun strongly advises not to use them since they can // change or go away in a future release so beware.printStackTrace().BASE64Encoder encoder = new sun.proxyPort".paypal.getProperties(). } } catch (Exception e) { e.com").out.2.out.

*.nonProxyHosts="*. each seperated by a |.rgagnon. The value can be a list of hosts./javadetails/java−0084. args[2]))).mycompany.html import java.25 Identify yourself using HTTP Authentification Current version of this HowTo : http://www.printStackTrace(). import java. String uname.*.io.getInputStream()).print(new String(b)).0. URL u = new URL(URLName).. while(−1 != di.printStackTrace().readLine()) != null) { System.nonProxyHosts property indicates the hosts which should be connected too directly and not through the proxy server. and in addition a wildcard character (*) can be used for matching.local|localhost" MyClass 12.com/javadetails/. The http. public class TestAuth { public static void main (String args[]){ /* ** args[0] is the URL protected ** args[1] is the username ** args[2] is the password */ try { BufferedReader in = new BufferedReader( new InputStreamReader (openURLForInput(new URL(args[0]). String line.openConnection().println(line).}}). } } public static InputStream openURLForInput (URL url. while ((line = in. args[1].exe −Dhttp.mycompany.net.25 Identify yourself using HTTP Authentification . } } catch (IOException e) { e. HttpURLConnection con = (HttpURLConnection) u. you may need to bypass the proxy server and go directly to the http server.read(b.1)) { System. } } In intranet environment.out. } } catch (Exception e) { e.out. di = new DataInputStream(con.com|*. String pword) throws IOException 12. java.

while (i < bytes. conn. String password) { return "Basic " + base64Encode (username + ":" + password). '7'. 'W'. 'm'. 'R'. encodedString += base64Array [c2]. 'r'. 'K'. 'X'. return conn. 'c'. }. conn. 'D'. } private final 'A'. encodedString += base64Array [c4]. 'E'. } byte c1 = (byte)(b1 >> 2). 'j'. '6'. 'O'.{ URLConnection conn = url. } else b3 = bytes [i++]. static char base64Array [] = { 'C'. 'v'.length) { byte b1 = bytes [i++]. 'f'. int pad = 0. '5'. 's'. 'y'. 'b'. 'S'. int i = 0. 'Y'. byte b3. 'e'. '3'. pad = 1. break. 'M'. '/' private static String base64Encode (String string) String encodedString = "".getInputStream(). byte c2 = (byte)(((b1 & 0x3) << 4) | (b2 >> 4)). 'P'.pword)).length) { b2 = 0. 'G'. '1'.connect ().length) { b3 = 0. } public static String userNamePasswordBase64 (String username. 'N'. encodedString += base64Array [c1]. 'w'. byte bytes [] = string. 'B'. 'H'. 'Q'.setDoInput (true). 'n'. } else { b2 = bytes [i++].openConnection(). 't'.getBytes (). 'o'. b3 = 0. 'x'. 'U'. byte c4 = (byte)(b3 & 0x3f). '4'. userNamePasswordBase64(uname. byte c3 = (byte)(((b2 & 0xf) << 2) | (b3 >> 6)). 'l'. '+'. '0'. if (i >= bytes. 'J'. 'F'. switch (pad) { case 0: encodedString += base64Array [c3]. '9'. 'z'. 'a'. 'I'.25 Identify yourself using HTTP Authentification . 'k'. 'Z'. 'd'. 'h'. 'L'. if (i >= bytes. byte b2. '2'. 'g'.setRequestProperty ("Authorization". 'i'. 'u'. pad = 2. 'p'. 'V'. conn. 'T'. case 1: { 12. 'q'. '8'.

case 2: encodedString += "==". } } A better alternative is the Authenticator class.pl (a PERL script) passing the parameters name and site.* package. NOTE: a simple explanation about the base64 encoding principle is shown in this How−to. Once the URL is constructed. break.pl?name=real).misc.html From the client point of view. there is no difference talking to CGI or Servlet. break. Those classes can be missing in your JDK release. con.BASE64Encoder().26 Talk to a CGI/Servlet .misc. Each parameter is delimited by the character "Habitually the encoding is done through the static method encode of the java. 12. encodedString += "=". see this HowTo. The CGI will process the result and produce a page to be displayed. String theCGI = "http://www.showDocument(cgiurl). you call the CGI using the showDocument method (Applet). } } return encodedString.setRequestProperty("Proxy−Authorization".BASE64Encoder encoder = new sun. 12. Parameters are encoded.server. The GET method contains encoded parameters in the URL.encodedString += base64Array [c3]. sun.getBytes()). String encodedUserPwd = encoder. Use of the sun.com/cgi−bin/acgi.26 Talk to a CGI/Servlet Current version of this HowTo : http://www. "Basic " + encodedUserPwd).URLencoder class.com/javadetails/.encode("domain\\username:password".rgagnon. Here we calling a script called aCGI.com/cgi−bin/aCGI. A typical URL talking to CGI using the GET method would be: new URL("http://www.net.* package is "discouraged" by sun and not formally supported. URL cgiurl = new URL(thecgi + encoded). An alternative way to Base64 encoding is to use the Base64 class in the sun. spaces are changed to "+" and special character to hexadecimal using a 3−letter escape sequence.server. Check this HowTo for a more official way to encode/decode to/from Base64..pl?". String encoded = "name=" + URLencoder./javadetails/java−0082.misc. getAppletContext(). There is two ways to send a request to a CGI.encode("Real Gagnon").

getInputStream()). The client make a request and the server send back the result and close the connection. import java.openConnection().*.setUseCaches(false). check this How−to.getOutputStream()).nextElement().close(). import java.27 Write/Read cookies using HTTP .html For a Java−Javascript solution.The POST method allows the programmer to manipulate the data received from the CGI. Enumeration keys = theCookies. cookieString += key + "=" + theCookies.net.com/cgi−bin/aCGI.setDoOutput(true). c../javadetails/java−0092. * @param printCookies Print or not the action taken. out.server. */ public URLConnection writeCookies (URLConnection urlConn. while (keys. /** * Send the Hashtable (theCookies) as cookies.flush(). DataOutputStream out = new DataOutputStream(c.io. class CookiesInJava { static Hashtable theCookies = new Hashtable(). import java.writeBytes(encoded). String theCGI = "http://www.*. out. boolean printCookies){ String cookieString = "". and write them to * the specified URLconnection * * @param urlConn The connection to write the cookies to.encode("Real Gagnon"). an OutputStream is open to send the parameters (if any). String aLine.out. First a connection is made to the CGI. } You can't do some output then some input and do again some output. 12. URL CGIurl = new URL(theCGI).hasMoreElements()) { String key = (String)keys. * * @return The urlConn with the all the cookies in it. c.*.setRequestProperty("content−type". while ((aLine = in. You must do all the output and then the input.rgagnon.util. There is no "dialog" between the client and the server. 12.get(key). out. URLConnection c = CGIurl.readLine()) != null) { // data from the CGI System. BufferedReader in = new BufferedReader(new InputStreamReader(c."application/x−www−form−urlencoded"). Then InputStream is created to receive the result.com/javadetails/. c.keys().println(aLine).27 Write/Read cookies using HTTP Current version of this HowTo : http://www. String encoded = "name=" + URLencoder.pl".

cookieString).hasMoreTokens()) { String s = st.substring(0.out. j))){ // if the Cookie do not already exist then when keep it.out."). String hdrKey.clear().equals("Set−Cookie")) { hdrString = urlConn.nextToken().hasMoreElements()) cookieString += ". Enumeration keys = theCookies. s.println("All Cookies are:").")).". } urlConn.aCookie.println(" Val: " + aCookie.println("Wrote cookies:\n " + cookieString). // you may want to add some logic to update // the stored Cookie instead. if (j != −1) { if (!theCookies. j)). int j = aCookie. 12. System.getHeaderFieldKey(i)) != null) { if (hdrKey.substring(j + 1)).substring(0. int i=1. aCookie = s.indexOf(".out. } } } } } i++.if (keys. // aCookie = hdrString.27 Write/Read cookies using HTTP . s.substring(0. and insert them * to the Hashtable * The hashtable represents the Cookies.getHeaderField(i).substring(j + 1)). } } /** * Display all the cookies currently in the HashTable * */ public void viewAllCookies() { System.setRequestProperty("Cookie". j). * * @param urlConn the connection to read from * @param printCookies Print the cookies or not. while (st. StringTokenizer st = new StringTokenizer(hdrString. if (printCookies) System.containsKey(aCookie. if (printCookies){ System.indexOf(". ".println("Reading Key: " + aCookie.indexOf("=").substring(0. return urlConn. } /** * Read cookies from a specified URLConnection.out. boolean reset){ if (reset) theCookies.put (aCookie. boolean printCookies. String aCookie. thanks to rwhelan theCookies.")). while ((hdrKey = urlConn.keys(). for debugging * @param reset Clean the Hashtable or not */ public void readCookies(URLConnection urlConn.substring(0. String hdrString.

*.hasMoreElements()){ key = (String)keys. System. * * @param urlConn The URL to print the associates cookies in.out. System.String key.. b. while (keys.nextElement(). public static void main(String args[]) { // GIF JAVA How−to at Real's Home String url = "http://www.net.com/javadetails/.rgagnon. public class SuckURL { String aFile.com/images/".out.print("Cookies in this URLConnection are:\n "). } 12.doit().rgagnon. System. import java.out. boolean printCookies){ if (!theCookies.out.28 Read a GIF or CLASS from an URL save it locally Current version of this HowTo : http://www.put(_key.println("Adding Cookie: "). if (printCookies){ System.*.28 Read a GIF or CLASS from an URL save it locally . */ public void viewURLCookies(URLConnection urlConn) { System. by hand.println(" " + _key + " = " + _val).containsKey(_key)){ theCookies. to the HastTable of the Cookies * * @param _key The Key/Name of the Cookie * @param _val The Calue of the Cookie * @param printCookies Print or not the result */ public void addCookie(String _key. * searching for the: "Cookie" header * * This is Valid only after a writeCookies operation. } } } } Thanks to Saar Machtiner for the bug fix 12.gif"). } } /** * Display the current cookies in the URLConnection.html import java.println(" " + key + "=" + theCookies. String _val. } /** * Add a specific cookie.println(urlConn. "jht.get(key)).out./javadetails/java−0060.getRequestProperty("Cookie")). String aURL._val). SuckURL b = new SuckURL(url.io.

println(" at " + aURL ).internal. } public void doit() { DataInputStream di = null.close(). HttpURLConnection con = (HttpURLConnection) url.protocol..sun.").*.www. URL url = new URL("https://www.handler. try { System.io.sun.println(inputLine).getInputStream())).println("Oups!!!"). byte [] b = new byte[1].close(). // output fo = new FileOutputStream(aFile).net. FileOutputStream fo = null.protocol").internal. URLConnection urlConnection = url. String inputLine. } 12.thawte.openConnection().out.SuckURL(String u.close().out.getInputStream()).setProperty("java.net.1). } catch (Exception ex) { System. aFile = s.addProvider(new com.out.0. System. // System.ssl. while ((inputLine = in. BufferedReader in = new BufferedReader( new InputStreamReader( con.1)) fo.pkgs". di = new DataInputStream(urlConnection.exit(1). fo.println("Sucking " + aFile).ssl. import java.connect().println("done. String s){ aURL = u.out.printStackTrace().readLine()) != null) System. System. di. } } This example dumps a page using the HTTPS protocol : import java.ssl. // input URL url = new URL(aURL + aFile).net. public class URLReader { public static void main(String[] args) throws Exception { // no longer necessary since JSSE is now included in // recent jdk release. // copy the actual file // (it would better to use a buffer bigger than this) while(−1 != di.out.. ex.write(b.28 Read a GIF or CLASS from an URL save it locally .*. } System.0. // Security.openConnection(). in.read(b. urlConnection.Provider()). // "com.com").

println("Usage: FileSizeFromURL ").close().out. relativeURL = new URL ( baseURL.*. } 12.out.do?assetkey=1−26−57436−1.getContentLength(). int size.30 File size from URL Current version of this HowTo : http://www.html */ } } 12.com/"). URLConnection conn.println(args[0] + "\nSize: " + size).net.html")..URL.openConnection().com/javadetails/.html import java./javadetails/java−0001./javadetails/java−0297.net.println("Could not determine file size. import java.toExternalForm ()). return.rgagnon.MalformedURLException { URL relativeURL. public class FileSizeFromURL { public static final void main(String[] args) { URL url.com/javadetails/.rgagnon.com/javadetails/java−0001. else System.sun.net. baseURL. public class ResolveRelativeURL { public static void main (String[] args) throws java.io.29 Resolve a relative URL Current version of this HowTo : http://www.rgagnon. size = conn.println ( relativeURL. conn = url.length != 1) { System.. if(size <0) System.html import java. you have exception talking about "untrusted server").").out.rgagnon. 12. you may want to review this note : http://sunsolve. /* output : http://www. conn. System.*. } try { url = new URL(args[0]).out. if(args. baseURL = new URL ("http://www.} There is an issue with root certificate from Verisign (jdk142 or less.29 Resolve a relative URL ./javadetails/java−0298. ".getInputStream().com/search/document.

secureserver. Go in "%java_home%\bin" and type this: keytool −import −v −alias meincert −trustcacerts −file c:\ 12. InputStream is = ssl. String google="http://www.ca/search?q=" + search + "e=UTF8".net.rgagnon. we must do this first : java.. Before connecting with a secure URL.google.internal.www.net.com/javadetails/. the JSSE package is included so you don't have to add anything special.net.4.com). One easy way to do this is to open a secured page (say https://mysecuredhost.URL class so just use it exactly as you would for a regular http URL.internal.rgagnon.sun.security.Security. URL ssl = new URL("https://www.html For Applets. both IE and NN have implemented https in their java.ssl. "com.ce".printStackTrace().protocol.31 Use the HTTPS protocol Current version of this HowTo : http://www.pkgs".sun.com/javadetails/.setProperty ("java.32 Fetch a page from Google Current version of this HowTo : http://www. take a look at the Sun's Secure Socket Extension (JSSE).com) with IE. 12.protocol").ssl. However you may need to import the certificate from the host (that is the server that you are connecting to using the https: protocol).Provider()).handler. You need to fool Google by pretending to be a legitimate browser. System. A useful link for that is this JavaWorld's Tip Since JDK 1. For application./javadetails/java−0308. } } } 12./javadetails/java−0399..html You can't directly fetch a page from Google because a check is made (by Google) to restrict access to "real" browser so a "403" HTTP code is returned to your Java program.31 Use the HTTPS protocol .catch(Exception e) { e.addProvider(new com. String search= "What you want to search for".ssl. click on the SSL−symbol (bottom right) and exported the key into the file "c:\cacerts.openStream().

. "Mozilla/4. Windows NT 5.0. 12. URLConnection con = urlObject./javadetails/java−0543.getInputStream())). Typically in Java..setProperty ("http.servlet) On the client side.agent".0)" ).rgagnon. MSIE 6. MSIE 6. a java application can use Jakarta Commons HTTP client to initiate a file upload. . 12. Another way is to start the program with a modified System.com/javadetails/. Note : You may want to take a look at http://www.agent.property http.URL urlObject = new URL(google).com/apis/ to learn how to interact with Google via the official API's.0. As seen above.0)" MyClass or in your program System. Windows NT 5. A simple way to use the HTML tag in a FORM <FORM METHOD=POST ENCTYPE="multipart/form−data" ACTION=". you can directly override the HTTP header.0 (compatible. con. it's a servlet.agent=Mozilla/4. >java "−Dhttp. Windows NT 5..0.google.. "Mozilla/4. Postlet is useable with any server side scripting language that is capable of handling file uploads.html To upload a file to a server you need something on the server side to accept the file. webData = new BufferedReader(new InputStreamReader(con. you can't do it with client−side code only. Postlet is a Java applet used to enable websites to allow their users to send multiple files to a webserver with a few simple clicks.0 (compatible.setRequestProperty ( "User−Agent".0 (compatible. The 2 most popular Java packages (server−side) to handle file upload are : • Jakarta Commons File Upload • O'reilly MultipartRequest (com. MSIE 6.33 Upload a file to a server Current version of this HowTo : http://www.0)").openConnection()./myuploadscript"> File to upload: <INPUT TYPE=FILE NAME="upfile">< <INPUT TYPE=SUBMIT VALUE="Submit"> </FORM> which looks like File to upload: The associated FORM target is a script on the server side that can handle HTTP file upload.oreilly.33 Upload a file to a server .

import java. String encoded = new String (Base64.base64Encode(new String("username:password").com −Dhttp.setProperties(systemSettings). systemSettings.com").rgagnon.put("http../javadetails/java−0085. . uc.put("http.proxyhost=myproxyserver.html. import java.34 Connect through a Proxy Current version of this HowTo : http://www. uc.yahoo.dump("https://www.proxyPort (default: 80 if http.net. One way is to use the HTTP property "Proxy−Authorization" with a username:password base64 encoded.sun.getProperties(). URLUtils.proxyPort"..proxyHost".com/j2se/1. . URL url=new URL("http://someserver/somepage"). proxyPort are deprecated.util.openConnection ().com").4/docs/guide/net/properties.setRequestProperty("Proxy−Authorization".getProperties(). "Basic " + encoded). NOTE: Those properties are documented here : http://java. System. You can set the required properties when starting the JVM for a JAVA application from the command line: java −Dhttp.". Properties systemSettings = System. "80").connect(). Properties systemSettings = System.12.println("**************"). The following example dumps the content of a URL but before we identify ourself to the proxy import java.proxyHost specified) http. you have to prefix them with "http.dump("http://www.*.html You have to set the following properties : http.com").. NOTE: For a base64 function.*.io. URLConnection uc = url. public class URLUtils { public static void main(String s[]) { URLUtils..proxyport=80 MyJavaApp Or in your source : import java. 12.com/javadetails/. systemSettings. see this How−to.nonProxyHosts (default: <none>) NOTE: proxyHost. "myProxyServer.util..getBytes())).Properties.paypal.proxyHost (default: <none>) http.34 Connect through a Proxy . System.setProperties(systemSettings).out. System. You might need to identify yourself to the proxy server.Properties.

byte [] b = new byte[1].getInputStream()).* class // Sun strongly advises not to use them since they can // change or go away in a future release so beware.System.BASE64Encoder().read(b.0.1)) { System.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("mydomain\\username". byte [] b = new byte[1]. systemSettings.mydomain. FileOutputStream fo = null. }}).proxyHost".BASE64Encoder encoder = new sun.local") . // // it's not the greatest idea to use a sun.mydomain. HttpURLConnection con = (HttpURLConnection) u.getInputStream()). "Basic " + encodedUserPwd). 12. } } catch (Exception e) { e. HttpURLConnection con = (HttpURLConnection) u. systemSettings.toCharArray()). When no username/password are provided then popup is shown to ask for the credentials."proxy.openConnection(). the java.getProperties().setRequestProperty ("Proxy−Authorization".getBytes()).getProperties(). // PROXY Properties systemSettings = System."proxy.misc. systemSettings. public static void dump(String URLName){ try { DataInputStream di = null. // sun.34 Connect through a Proxy .Authenticator can be used to send the credentials when needed. di = new DataInputStream(con.proxyPort".put("http.put("http. URL u = new URL(URLName).net. // PROXY −−−−−−−−−− di = new DataInputStream(con.openConnection().put("http.out. } public static void dump(String URLName){ try { DataInputStream di = null.println("**************"). while(−1 != di. } } } With JDK1.misc.2."password".print(new String(b)). systemSettings.encode("mydomain\\MYUSER:MYPASSWORD". // PROXY Properties systemSettings = System. Authenticator.put("http.out.proxyHost". FileOutputStream fo = null.proxyPort".local") . "80") . String encodedUserPwd = encoder. con.misc. "80") . URL u = new URL(URLName).printStackTrace().

html It's not possible to really "ping" a machine to check if it's alive or not (it's a long story.com|*. We write a string to that port and the server will echo the string.html [JDK11] ServerSocket server = new ServerSocket(port).local|localhost" MyClass 12./javadetails/java−0086.1)) { System.rgagnon.0.println( "Timed Out (60 sec)!" ).*. Note that when the TIMEOUT expires.while(−1 != di.out.com/javadetails/.. import java. } This is true for READ operation too. and in addition a wildcard character (*) can be used for matching. However.com/javadetails/. 12. } } catch (Exception e) { e. java. The http. the echo port is always port 7.printStackTrace(). On a server.rgagnon. // timeout after 60 seconds server. you may need to bypass the proxy server and go directly to the http server.accept().. but to keep it short I will just say that the Socket class is not low−level enough for that operation).36 Ping a server Current version of this HowTo : http://www./javadetails/java−0093.err. each seperated by a |. } catch ( java. an InterruptException is thrown.mycompany. But we can emulate a ping by talking the "echo port".35 Have timeout on socket connection .setSoTimeout(60000).io. The value can be a list of hosts. 12.read(b. } } In intranet environment. try { Socket socket=server.nonProxyHosts property indicates the hosts which should be connected too directly and not through the proxy server.mycompany.io.nonProxyHosts="*.InterruptedIOException e ) { System. Since READ operation blocks as long necessary it may be wise to use the setSoTimeout() method.exe −Dhttp.print(new String(b)). the socket is still connected even though the Exception was raised.35 Have timeout on socket connection Current version of this HowTo : http://www.

equals("Hello")) System. 7).edu").out.out. Since JDK1.readLine(). System.net.mit.37 Get the Date from server Current version of this HowTo : http://www.isReachable(int) can be used to check if a server is reachable or not. DataInputStream dis = new DataInputStream(t.InetAddress. } catch (UnknownHostException e) { System.*.println("Addr: " + address. } catch (IOException e) { System. else System. String str = dis.net.println("Reach: " + address. 12.isReachable(3000)).println("Name: " + address.mit. But most Internet sites have disabled the service or blocked the requests (except some university web sites like the example above) . import java.getOutputStream()). public class ReachableTest { public static void main(String args[]) { try { InetAddress address = InetAddress.println("Hello").37 Get the Date from server . t. import java.} } } } NOTE: To make this a more "complete PING".out. ps. } } } isReachable() will use ICMP ECHO REQUESTs if the privilege can be obtained.*.close(). PrintStream ps = new PrintStream(t. java.html This can be done by opening a socket to the port "daytime" (port 13) (on Unix or NT machine).println("Unable to lookup web.println("Dead or echo port not responding"). if (str./javadetails/java−0094.getHostAddress()).println("Alive!") .getByName("web.com/javadetails/.err.printStackTrace().edu"). System. 12.5. } catch (IOException e) { e. you may want to check this How−to to display the response time. public class PseudoPing { public static void main(String args[]) { try { Socket t = new Socket(args[0].mit. System.println("Unable to reach web.import java.rgagnon.edu")..err.io.out.getHostName()).getInputStream()).net.*.out. otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host.

you must go to the security TAB.out.class" HEIGHT=10 WIDTH=10> </APPLET> Check JAVA console for output /BODY Try it here NOTE: Netscape returns the IP address with the default security settings so it's not problem.i)).net.printStackTrace().println("Usage: GetTime HOST"). With IE5.rgagnon.38 Get the client IP address .length != 1) { System. import java.printStackTrace().println("IP:"+thisIp.html import java.io. Java Custom. } try { Socket s = new Socket(args[0]. } catch(Exception e) { e.0.com/javadetails/. 12.getInputStream().*.getHostAddress()). int i=is.print(new String(b. return.getLocalHost(). } } } <HTML><HEAD></HEAD><BODY> <APPLET CODE="GetClientIP.import java. Internet.*.out.*.*. public class GetClientIP extends Applet { public void init() { try { InetAddress thisIp = InetAddress. Edit and select "Allow access to all IP address".applet. import java.. InputStream is = s. System. import java.out./javadetails/java−0095. } } catch (Exception e) { e.*. if (i==−1) return. System.net. while (true) { byte b[] = new byte[100].38 Get the client IP address Current version of this HowTo : http://www.io.read(b). public class GetTime { public static void main(String args[]) { if (args. } } } 12.13).

/javadetails/java−0293..Socket.net. and the int controls the delay time (in seconds.Using a Servlet.Socket. The Nagle's algorithm is described in RFC 896. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 12.com/javadetails/.getRemoteAddr().close() method is invoked. You get the current "TCP_NODELAY" setting with java. at the cost of an increase in bandwidth consumption.rgagnon. You get the current "linger" setting with java.rgagnon.40 Use the java.Socket.setTcpNoDelay method Current version of this HowTo : http://www.net.setSoLinger() method accepts as parameters a boolean and an int. meaning a reset will be sent as soon as the java. The boolean flag activates or deactivates the SO_LINGER option. or you can specify a delay of zero. Data will be sent earlier.Socket.net. giving more time for data to be read or send. they can disable Nagle's algorithm (that is enable TCP_NODELAY).html java.39 Use the java.Socket. and acknowledgements to be received.getSoLinger() 12.net. HttpServletResponse res) throws IOException { String IP = req.com/javadetails/. then any unsent packets are thrown away when the socket is closed otherwise the close() method blocks while waiting the specified number of seconds for the data to be sent.39 Use the java. The java. When applications wish to decrease network latency and increase performance.. } If you find this article useful.html By using the setSoLinger() method. Nagle's algorithm try to conserve bandwidth by minimizing the number of segments that are sent.net. you can explicitly set a delay before a reset is sent.Socket.net./javadetails/java−0294. this can be done with : public void service(HttpServletRequest req. Note that if a linger time is set to zero.getTcpNoDelay() 12.setTcpNoDelay() is used to enable/disable TCP_NODELAY which disable/enable Nagle's algorithm. You can possibly increase performance with a delay of zero. max 65535).net.Socket.Socket.setSoLinger method .net.setSoLinger method Current version of this HowTo : http://www. consider making a small donation to show your support for this Web site and its content.

pdf")..").out.0.41 Find out who is accessing my ServerSocket .net.html A client module connects to a server then a file is sent to the client.net."). // sendfile File myFile = new File ("source. os.mybytearray. while (true) { System.accept().out.write(mybytearray.12.41 Find out who is accessing my ServerSocket Current version of this HowTo : http://www.io.close(). import java.0.. os. public class FileServer { public static void main (String [] args ) throws IOException { // create socket ServerSocket servsock = new ServerSocket(13267).println("Sending./javadetails/java−0542.getOutputStream(). byte [] mybytearray = new byte [(int)myFile. bis.getPort()).mybytearray. System...flush().com/javadetails/. OutputStream os = sock.html Socket aSock = myServerSocket.println("Waiting.accept().println ("Connection from : " + aSock. BufferedInputStream bis = new BufferedInputStream(fis). sock.rgagnon. System.out.length()].*. public class FileClient{ 12.*. This exemple is very simple with no authentication and hard−coded filename! First a server module.out.length).42 Transfer a file via Socket Current version of this HowTo : http://www. import java.*.length). } } } The client module import java. 12.getInetAddress()./javadetails/java−0295. Socket sock = servsock. System.*.getHostAddress() + ':' + aSock...rgagnon.io. import java.read(mybytearray.println("Accepted connection : " + sock). FileInputStream fis = new FileInputStream(myFile).com/javadetails/.

current. bos.close(). (mybytearray.println(end−start).println("Connecting.41 Find out who is accessing my ServerSocket . } while(bytesRead > −1).getInputStream(). long end = System.. InputStream is = sock. // receive file byte [] mybytearray = new byte [filesize].com 12..13267). 0 .length).read(mybytearray. current). FileOutputStream fos = new FileOutputStream("source−copy.public static void main (String [] args ) throws IOException { int filesize=6022386. // localhost for testing Socket sock = new Socket("127.pdf").currentTimeMillis(). int current = 0.rgagnon.mybytearray.com http://www. Cádiz for the bug fix do { bytesRead = is. BufferedOutputStream bos = new BufferedOutputStream(fos). System.write(mybytearray.0. int bytesRead.length−current)). // filesize temporary hardcoded long start = System.out. bos.1". System.out.0. // thanks to A.read(mybytearray.close(). } } Written and compiled Réal Gagnon ©2007 real@rgagnon. bytesRead = is. current = bytesRead. if(bytesRead >= 0) current += bytesRead.0.currentTimeMillis()."). sock.

Input.encrypt(Input. try again.!").getBytes()).print("Now try to enter a password : " ).security.StreamTokenizer(System. } else System. if (secret.html Message digests are secure one−way hash functions that take arbitrary−sized data and output a fixed−length hash value.. } } public static byte[] encrypt(String x) throws Exception { java.getInstance("SHA−1").MessageDigest d =null.. java.2 Encrypt a password Current version of this HowTo : http://www./javadetails/java−0400. while (ok) { System..StreamTokenizer Input=new java.out.equals(s)){ System. s = new String(CryptoUtils.rgagnon.io. d. // System.nextToken(). boolean ok = true.. } } catch (Exception e){ e.com/javadetails/.println("Wrong.out. String secret = new String(CryptoUtils.security. System.sval)). public class CryptoUtils { public static void main(String arg[]) { try { // quick way to do input from the keyboard.out.update(x. } } The output is : 13 Security .print("Input your secret password : ").encrypt(Input.digest().. return d.in).println("the encrypted result : " + secret).1 java−security 13.13 Security 13. d = java. now deprecated. d. String s = "".printStackTrace(). ok = false.nextToken().sval)).println("You got it!").MessageDigest.out.io. Input.reset().out.

! Now try to enter a password : howTo Wrong.length.append(Integer. String encoded=encoder. −127 }. } return sb.out. i < b. −1. if (v < 16) { sb. Or we can simply convert the byte array into an hexadecimal string: public class StringUtils { public static void main(String arg[]) { byte b[] = { 7.encode(secret.out.Input your secret password : howto the encrypted result : ûóbf−m¦esd Now try to enter a password : Howto Wrong.length. 42.BASE64Encoder().misc. 13 Security . you may need to transform it into a hexadecimal string because the encrypted string may contains non−printable characters. } sb.toString().length() / 2].length * 2)..getBytes()).println(b[i]). for (int i = 0.append('0'). // 7.toHexString(v)). i < b. /* output : 072AFF81 */ b = hexStringToByteArray(byteArrayToHexString(b)). FF.! Now try to enter a password : howto You got it! If you need to save the encrypted string into a file. 2A. i++){ int v = b[i] &0xff.parseInt(s. // encoded is a string with printable characters. i < b. int v = Integer.BASE64Encoder encoder = new sun.. sun. try again.. i++){ int index = i * 2. for (int i = 0.println(byteArrayToHexString(b)). 16). index + 2).toUpperCase(). } public static byte[] hexStringToByteArray(String s) { byte[] b = new byte[s. 81 System. for (int i = 0.length. i++) { System.misc. try again. One technique is to encode using Base64 the encrypted string. } /* output : 7 42 −1 −127 */ } public static String byteArrayToHexString(byte[] b){ StringBuffer sb = new StringBuffer(b.substring(index..

MessageDigest complete = MessageDigest. fis. } // see this How−to for a faster way to convert a byte array to // a HEX string public static String getMD5Checksum(String filename) throws Exception { byte[] b = createChecksum(filename).5. for (int i=0.org/dist/ // tomcat/tomcat−5/v5.out. } public static void main(String args[]) { try { System.com/javadetails/.println(getMD5Checksum("apache−tomcat−5.rgagnon.close().length. import java.17/bin // /apache−tomcat−5..exe.17. byte[] buffer = new byte[1024].io. } } 13.5. } return result.update(buffer. String result = "".substring( 1 ). 0. } } while (numRead != −1). return complete. } return b.getInstance("MD5").apache. i++) { result += Integer.3 Create a checksum Current version of this HowTo : http://www. if (numRead > 0) { complete. 16).5.exe")).MD5 // 0bb2827c5eacf570b6064e24e0e6653b *apache−tomcat−5.toString( ( b[i] & 0xff ) + 0x100.digest().MessageDigest. do { numRead = fis.17.17. int numRead. A user can compare a published MD5 sum with the checksum of a downloaded file.3 Create a checksum . public class MD5Checksum { public static byte[] createChecksum(String filename) throws Exception{ InputStream fis = new FileInputStream(filename). // output : // 0bb2827c5eacf570b6064e24e0e6653b // ref : // http://www./javadetails/java−0416. numRead). i < b.security.b[i] = (byte)v. import java.exe 13.html MD5 digests have been widely used in the software world to provide some assurance that a downloaded file has not been altered.*.5.read(buffer).

chk file which contains a MD5 checksum of a given file. public class Checksum { // // return 0 error // 1 ok (create)1 // 1 same (check) // 2 different (check) // public static void main(String args[]) { if (args.read(chk2). } } } The next example is used to create a .println("Usage : java Checksum create [filename]\n"+ " java Checksum check [filename]"). File f = new File(filename + ". os.chk file and compared with current checksum of the given file. import java.write(chk). } } else { System. return 1. OutputStream os = new FileOutputStream(f).equals("create")) { System.io. os.3 Create a checksum . try { byte[] chk1 = createChecksum(filename). byte[] chk2 = new byte[chk1.*.exit(new Checksum(). InputStream is = new FileInputStream(f).chk").close().printStackTrace(). File f = new File(filename + ".length == 2) { if (args[0].printStackTrace(). } } public int create(String filename){ try { byte[] chk = createChecksum(filename).} catch (Exception e) { e. } else if (args[0].exit(new Checksum(). } } public int check(String filename){ int rc = 0. is.security. return 0. import java.*. The same program is used to check if a file has been altered by looking at previously generated . 13.out.check(args[1])).length].equals("check")) { System.create(args[1])). } catch(Exception e) { e.chk").

zip.close().length != 1) { System.out. byte[] bytes = new byte[1024]. fis.util.equals(new String(chk1))) { System.read(buffer). String fname) { try { BufferedInputStream is = new BufferedInputStream( new FileInputStream(fname)). if (numRead > 0) { complete. } is. 13.close(). } catch (IOException e) { e. rc = 2.exit(1). public class ComputeCRC32 { public static long getChecksumValue(Checksum checksum.3 Create a checksum .println("Same!").CRC32.getValue(). } catch(Exception e) { e. while ((len = is. import java.out. } } public byte[] createChecksum(String filename) throws Exception{ InputStream fis = new FileInputStream(filename). } else { System.println("Different!"). numRead). System. rc = 1. return rc.zip. len).util.zip package can be used to create a checksum. } } while (numRead != −1).err. return complete.printStackTrace().util. } is.println("Usage: java ComputeCRC32 <file>").io. int numRead.update(bytes.read(bytes)) >= 0) { checksum.close(). import java. } public static void main(String[] args) { if (args. import java. int len = 0. return rc. byte[] buffer = new byte[1024]. } } The java. MessageDigest complete = MessageDigest.*. 0. } return checksum.if (new String(chk2).printStackTrace().Checksum.getInstance("MD5"). do { numRead = fis.update(buffer.digest(). 0.

System.rgagnon. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 13. 4. username = System.security. consider making a small donation to show your support for this Web site and its content.5 Get username using NT Challenge (NTLM) Current version of this HowTo : http://www.} long cs = getChecksumValue(new CRC32().name"). something like an ASP page can be used to detect the current NT user name if the client is configured correcty.println("crc32 " + args[0] + " : " + cs).NTSystem().. If you find this article useful.getName()). 3.auth.security. do the same and compare the MD5 sums.sun.auth.4 Get the user name . and returns an MD5 sum of the result to the server.sun.module.rgagnon. On the server.out.out. See this related HowTo for a JSP hack! 13.5 public class Test { public static void main(String args[]) { com.println(NTSystem.html In application : String username.html 13.4 Get the user name Current version of this HowTo : http://www. 1. If both MD5 are identicals then the password is good. } } MD5 checksum can be used to validate a password without passing the actual password./javadetails/java−0048. If you have access to a server−side.getProperty("user. 2.com/javadetails/. System. args[0]).NTSystem NTSystem = new com. or in JDK1.com/javadetails/.. The client appends his password to the random string. The server sends a random string to the client./javadetails/java−0441.module. } } In Applet there is no way unless you ask for it or use a signed applet.

Even if the application server do not support NTLM protocol, it is possible to use it to extract the Windows username. From the server, we ask the browser to identify the current user, and "by hand", we extract the response from the answer. The browser client must support NT Challenge authentification mechanism (IE does). This is a quick HACK to extract the username! There is no security into this. Beware... [username.jsp]
<%@ page import="sun.misc.BASE64Encoder" %> <p><h1>Network Windows USERNAME without any login (ie)</h1></p> <% String auth = request.getHeader("Authorization"); if (auth == null) { response.setStatus(response.SC_UNAUTHORIZED); response.setHeader("WWW−Authenticate", "NTLM"); return; } if (auth.startsWith("NTLM ")) { byte[] msg = new sun.misc.BASE64Decoder().decodeBuffer(auth.substring(5)); int off = 0, length, offset; String s; if (msg[8] == 1) { off = 18; byte z = 0; byte[] msg1 = {(byte)'N', (byte)'T', (byte)'L', (byte)'M', (byte)'S', (byte)'S', (byte)'P', z, (byte)2, z, z, z, z, z, z, z, (byte)40, z, z, z, (byte)1, (byte)130, z, z, z, (byte)2, (byte)2, (byte)2, z, z, z, z, // z, z, z, z, z, z, z, z}; // response.setStatus(response.SC_UNAUTHORIZED); response.setHeader("WWW−Authenticate", "NTLM " + new sun.misc.BASE64Encoder().encodeBuffer(msg1).trim()); return; } else if (msg[8] == 3) { off = 30; length = msg[off+17]*256 + msg[off+16]; offset = msg[off+19]*256 + msg[off+18]; s = new String(msg, offset, length); //out.println(s + " "); } else return; length = msg[off+1]*256 + msg[off]; offset = msg[off+3]*256 + msg[off+2]; s = new String(msg, offset, length); //out.println(s + " "); length = msg[off+9]*256 + msg[off+8]; offset = msg[off+11]*256 + msg[off+10]; s = new String(msg, offset, length); out.println("Hello <span style='position:relative; width:190;" + " height:10;filter:glow(Color=#009966,Strength=1)'>");

13.4 Get the user name

out.println(s + "</SPAN>"); } %></BODY>
NOTE: A comment from Weijun Ji : This technique only works if a user has its IE browser security setting set at middle/low (or if the server is trusted like in an intranet environment). With this setting, browser will grab login username automatically. If the security setting is at high, then a window will prompt user for input. At that time, whatever username the user put in will be passed to the "NTLM program". Since the user is not authenticated, you have no way to know if this user is a true user or not. In this way, any user can pretend to be anybody else as long as he has his security level set as high.

You want to deeper into this subject, take a look at these sites : http://www.innovation.ch/java/ntlm.html http://free.tagish.net/jaas/index.jsp http://www.luigidragone.com/networking/ntlm.html Starting from jdk1.4.2, Sun provides support for NTLM, see http://java.sun.com/j2se/1.4.2/changes.html#networking For a complete solution see JCIFS (for Tomcat and others) at http://jcifs.samba.org
If you find this article useful, consider making a small donation to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998−2005 [ home ]

13.6 Check if the current user belongs a specific Windows group/role
Current version of this HowTo : http://www.rgagnon.com/javadetails/../pbdetails/pb−0227.html You can connect to the ActiveDirectory or use some API but an easy way is to use a connection to SQL Server. Send the query :
SELECT is_member('mydomain\g_dept')

and the result can be
0 1 NULL Current user is not a member of group or role. Current user is a member of group or role. Either group or role is not valid.

13.7 Prompt for password from the console
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0375.html A separate thread is used to send to the console the backspace character to erase the last−typed character.
import java.io.*;

13.6 Check if the current user belongs a specific Windows group/role

import java.awt.*; public class PwdConsole { public static void main(String[] args) throws Exception { ConsoleEraser consoleEraser = new ConsoleEraser(); System.out.print("Password? "); BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); consoleEraser.start(); String pass = stdin.readLine(); consoleEraser.halt(); System.out.print("\b"); System.out.println("Password: '" + pass + "'"); } } class ConsoleEraser extends Thread { private boolean running = true; public void run() { while (running) { System.out.print("\b "); } } public synchronized void halt() { running = false; } }

Java SE6 provides a buiilt−in mechanism to input a password from the console.
java.io.Console cons; char[] passwd; if ((cons = System.console()) != null & (passwd = cons.readPassword("[%s]", "Password:")) != null) { ... }

13.8 Display a simple username/password Dialog from an Applet
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0128.html NOTE: This way to authenticate a user is NOT secured at all since the required information is embedded in the Applet. [MyApplet.java]
import java.awt.*; import java.net.*; public class MyApplet extends java.applet.Applet { public String username = ""; public String password = ""; public void init() {

13.8 Display a simple username/password Dialog from an Applet

if (!login()) { try { getAppletContext().showDocument (new URL(getCodeBase()+"accessdenied.html"),"_top"); } catch (Exception e) {e.printStackTrace(); } } else { // here the username and password are OK } } public boolean login() { boolean userValid = false; MyLogin login = new MyLogin (new Frame("")); requestFocus(); if (login.id) { username = login.username.getText(); password = login.password.getText(); userValid = validateUser(username , password); System.out.println ("The password for " + username + " is " + (userValid?"valid":"invalid")); } else System.out.println ("Cancel was pressed."); login.dispose(); return userValid; } private boolean validateUser(String usr, String pwd) { // here you will code some logic to validate the username // password... for testing purpose : // username = java password = avaj return (usr.equals("java") &pwd.equals("avaj")); } }

[MyLogin.java]
import java.awt.*; import java.awt.event.*; public class MyLogin extends Dialog implements ActionListener { boolean id = false; Button ok,can; TextField username; TextField password;

MyLogin(Frame frame){ super(frame, "Welcome", true); setLayout(new FlowLayout()); username = new TextField(15); password = new TextField(15); password.setEchoChar('*'); add(new Label("User :")); add(username); add(new Label("Password :")); add(password);

13.8 Display a simple username/password Dialog from an Applet

addOKCancelPanel(); createFrame(); pack(); setVisible(true); } void addOKCancelPanel() { Panel p = new Panel(); p.setLayout(new FlowLayout()); createButtons( p ); add( p ); } void createButtons(Panel p) { p.add(ok = new Button("OK")); ok.addActionListener(this); p.add(can = new Button("Cancel")); can.addActionListener(this); } void createFrame() { Dimension d = getToolkit().getScreenSize(); setLocation(d.width/4,d.height/3); } public void actionPerformed(ActionEvent ae){ if(ae.getSource() == ok) { id = true; setVisible(false); } else if(ae.getSource() == can) { id = false; setVisible(false); } } }

the HTML to test it out : [login.html]
<HTML><HEAD><BODY> <TABLE><TR><TD> <APPLET CODE=MyApplet.class WIDTH=300 HEIGHT=300> </APPLET></TABLE> NOTE: View the java console for infos about the login process </BODY></HEAD> </HMTL>

A simple "Access is denied" page : [accessdenied.html]
<HTML> access is denied </HMTL>

Written and compiled Réal Gagnon ©2007 real@rgagnon.com http://www.rgagnon.com

13.8 Display a simple username/password Dialog from an Applet

13.8 Display a simple username/password Dialog from an Applet

14 Swing
14.1 java−swing

14.2 * Read me *
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0193.html NOTE: With the JDK1.2 release, it's recommended to use
import javax.swing.*;

instead of
import com.sun.java.swing.*;

IE or Netscape don't support directly Swing Applet. You must use the Java plugins. Then you will need to use the <OBJECT> (IE) or <EMBED> (Netscape) HTML tag instead of the regular <APPLET> tag.

14.3 Change component default font
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0335.html
public static void setUIFont (javax.swing.plaf.FontUIResource f){ // // sets the default font for all Swing components. // ex. // setUIFont (new javax.swing.plaf.FontUIResource // ("Serif",Font.ITALIC,12)); // java.util.Enumeration keys = UIManager.getDefaults().keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); Object value = UIManager.get (key); if (value instanceof javax.swing.plaf.FontUIResource) UIManager.put (key, f); } }

For a particuliar component
UIManager.put("Label.font",new Font("Serif",Font.ITALIC,12));
Swing UI default
If you find this article useful, consider making a small donation to show your support for this Web site and its content.

14 Swing

Written and compiled by Réal Gagnon ©1998−2005 [ home ]

14.4 Repaint problem under the mouse cursor (JDK1.2)
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0206.html You probably have installed a Microsoft Theme on your desktop. Simply switch the mouse cursor to the regular Windows mouse cursor to correct the problem.

14.5 Set the LookAndFeel
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0207.html By default, Swing will use the Metal LookAndFeel. To set the LookAndFeel to the current OS under which the JVM is running, use this snippet :
try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); }

Even with the new naming mecanism in JDK1.2, some LookAndFeel packages are keeping the oldname. Windows Motif Mac Metal Basic Multi com.sun.java.swing.plaf.windows (no change) com.sun.java.swing.plaf.motif (no change) com.sun.java.swing.plaf.mac (no change) javax.swing.plaf.metal (new) javax.swing.plaf.basic (new) javax.swing.plaf.multi (new)

These packages are located in the rt.jar file.

14.6 Use any LookAndFeel on any plateform
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0208.html There is some restriction to the usage of LookAndFeel when there are some copyright involved. For example, you can't activate the Mac LookAndFeel in a Windows environment.

14.4 Repaint problem under the mouse cursor (JDK1.2)

The trick is to fool Swing by setting the property os.name to a different value than real one to enable the use of "forbidden" LookAndFeel. From the command line, to activate Windows LookAndFeel on a non−Windows environment
java −Dos.name=windows MySwingApp

to activate Mac LookAndFeel on a non−Mac environment
java −Dos.name=mac MySwingApp

or you can do it in your source by doing something like:
Properties p = System.getProperties(); p.put("os.name", "Mac"); System.setProperties(p);
NOTE: Current Swing release for Windows does not include the necessary classes for the Mac's LookAndFeel anymore.

It's not bad idea to set the look and feel to a known good value and then try the not−so−sure value.
try { // sure look and feel UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); // not−so−sure look and feel System.setProperty("os.name", "Windows"); System.setProperty("os.version", "5.1"); UIManager.setLookAndFeel( "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch (Exception ex) { ex.printStackTrace(); }

14.7 Use a Timer
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0220.html See this How−to.

14.8 Share ActionEvent handler
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0212.html In this example, a JMenu, JToolbar and JButtons on a JFrame are sharing common ActionEvent handlers.
import javax.swing.*; import java.awt.event.*;

14.7 Use a Timer

import java.awt.*; public class OpenAction SaveAction QuitAction ShareAction extends JFrame { openAction = new OpenAction(); saveAction = new SaveAction(); quitAction = new QuitAction();

public static void main(String argv[]) { new ShareAction().setVisible(true); } ShareAction() { createMenu(); createToolBar(); createButtons(); pack(); // deal closing via the upper right "X" by redirecting to // quitAction addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { ActionEvent ae = new ActionEvent (quitAction, ActionEvent.ACTION_PERFORMED, "bebye"); JFrame j = (JFrame)e.getSource(); j.dispatchEvent(ae); } } ); } public Dimension getPreferredSize() { return new Dimension(300,300); } private void createMenu(){ JMenuBar mb = new JMenuBar(); JMenu file = new JMenu("File"); mb.add(file); file.add(openAction); file.add(saveAction); file.add(quitAction); setJMenuBar(mb); } private void createToolBar() { JToolBar bar = new JToolBar(); bar.add(openAction); bar.add(saveAction); bar.add(quitAction); getContentPane().add(bar, "North"); } private void createButtons() { JPanel j = new JPanel(); JButton b1 = new JButton("Open"); JButton b2 = new JButton("Save"); JButton b3 = new JButton("Quit"); b1.addActionListener(openAction); b2.addActionListener(saveAction); b3.addActionListener(quitAction);

14.7 Use a Timer

j.add(b1); j.add(b2); j.add(b3); getContentPane().add(j, "East"); } } class OpenAction extends AbstractAction { public OpenAction() { super("Open", new ImageIcon("open.gif")); } public void actionPerformed(ActionEvent e) { System.out.println("Open action"); } } class SaveAction extends AbstractAction { public SaveAction() { super("Save", new ImageIcon("save.gif")); } public void actionPerformed(ActionEvent e) { System.out.println("Save action"); } } class QuitAction extends AbstractAction { public QuitAction() { super("Quit", new ImageIcon("quit.gif")); } public void actionPerformed(ActionEvent e) { System.out.println("Quit action"); System.out.println("Bye."); System.exit(0); } }

14.9 Trigger a click on a Button
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0468.html Regular AWT
import java.awt.*; import java.awt.event.*; import java.applet.*; public class TestEvent extends Applet implements ActionListener { Button b2, b1; TextField t1; public void init() { setLayout(new FlowLayout()); t1 = new TextField(30); b1 = new Button("Output"); add(b1); add(t1); b2 = new Button("Fire event 1st button"); add(b2); b1.addActionListener(this);

14.9 Trigger a click on a Button

b2.addActionListener(this); } public void actionPerformed(ActionEvent e) { if (e.getSource() == b1) { t1.setText("1st button clicked"); } if (e.getSource() == b2) { // from the b2 button, we creating an event to trigger a click // on the b1 button ActionEvent ae = new ActionEvent((Object)b1, ActionEvent.ACTION_PERFORMED, ""); Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(ae); // b1.dispatchEvent(ae); can be used too. } } }

With Swing
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TestEventSwing extends JApplet implements ActionListener { JButton b1, b2; JTextField t1; public void init() { setLayout(new FlowLayout()); t1 = new JTextField(30); b1 = new JButton("Output"); add(b1); add(t1); b2 = new JButton("Fire event 1st button"); add(b2); b1.addActionListener(this); b2.addActionListener(this); } public void actionPerformed(ActionEvent e) { if (e.getSource() == b1) { t1.setText("first button clicked"); } if (e.getSource() == b2) { // from the b2 button, we trigger a click on the b1 button. // As an added bonus, a visual effect on b1 is visible! b1.doClick(); } } }
If you find this article useful, consider making a small donation to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998−2005 [ home ]

14.9 Trigger a click on a Button

14.10 Get default values for Swing−based user interface
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0507.html This little class will dump to stdout the default values used by Swing. You can redirect the result to a file with
>java UIDefaults > swing.props import import import import import java.util.Comparator; java.util.Iterator; java.util.Map; java.util.Set; java.util.TreeSet;

import javax.swing.UIManager; public class UIDefaults { public static void main(String[] args) { try { Set defaults = UIManager.getLookAndFeelDefaults().entrySet(); // this TreeSet will hold the sorted properties TreeSet ts = new TreeSet(new Comparator() { public int compare(Object a, Object b) { Map.Entry ea = (Map.Entry) a; Map.Entry eb = (Map.Entry) b; return ((String) ea.getKey()).compareTo(((String)eb.getKey())); } }); ts.addAll(defaults); for (Iterator i = ts.iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); System.out.print(entry.getKey() + " = " ); System.out.println(entry.getValue()); }

} catch (Exception ex) { ex.printStackTrace(); } } }

• For an example on how to change a default value see this HowTo • To change a value for a particuliar component, see this HowTo • Here a sample list for JavaUIDefaults
If you find this article useful, consider making a small donation to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998−2005 [ home ]

14.10 Get default values for Swing−based user interface

14.11 Close a JFrame under condition
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0340.html
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CloseOrNot extends JFrame { JTextField field1; JPanel panel; public CloseOrNot() { super( "CloseOrNot Frame" ); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); panel = new JPanel(); field1 = new JTextField( 10 ); panel.add( new JLabel("type yes to close the Frame ")); panel.add( field1 ); getContentPane().add( "Center", panel ); addWindowListener( new WindowAdapter() { public void windowOpened( WindowEvent e ){ field1.requestFocus(); } public void windowClosing( WindowEvent e ){ if (field1.getText().equals("yes")) { if (JOptionPane.showConfirmDialog (null,"Are you sure ?")==JOptionPane.YES_OPTION) { setVisible(false); dispose(); } } } } ); pack(); setVisible( true ); } public static void main(String args[]) { new CloseOrNot(); } }
If you find this article useful, consider making a small donation to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998−2005 [ home ]

14.12 Maximize a JFrame
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0479.html
import java.awt.*; import javax.swing.*;

14.11 Close a JFrame under condition

public class TestMaxJFrame extends JFrame { public TestMaxJFrame() { GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); /* The next line determines if the taskbar (win) is covered if unremarked, the task will not be covered by the maximized JFRAME. */ // this.setMaximizedBounds(env.getMaximumWindowBounds()); this.setExtendedState(this.getExtendedState() | this.MAXIMIZED_BOTH); } public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); TestMaxJFrame t = new TestMaxJFrame(); t.setVisible(true); } }
If you find this article useful, consider making a small donation to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998−2005 [ home ]

14.13 Capture System.out into a JFrame
Current version of this HowTo : http://www.rgagnon.com/javadetails/../javadetails/java−0435.html
import java.awt.*; import javax.swing.*; import java.io.*;

/** * http://tanksoftware.com/juk/developer/src/com/ * tanksoftware/util/RedirectedFrame.java * A Java Swing class that captures output to the command line ** (eg, System.out.println) * RedirectedFrame * <p> * This class was downloaded from: * Java CodeGuru (http://codeguru.earthweb.com/java/articles/382.shtml) <br> * The origional author was Real Gagnon (real.gagnon@tactika.com); * William Denniss has edited the code, improving its customizability * * In breif, this class captures all output to the system and prints it in * a frame. You can choose weither or not you want to catch errors, log * them to a file and more. * For more details, read the constructor method description */

public class RedirectedFrame extends JFrame { // Class information public static final String PROGRAM_NAME = "Redirect Frame"; public static final String VERSION_NUMBER = "1.1"; public static final String DATE_UPDATED = "13 April 2001";

14.13 Capture System.out into a JFrame

setOut(aPrintStream). this.logFile = logFile. setTitle("Output Frame"). Container c = getContentPane().out into a JFrame . int width. with the dimentions 700x600 and it doesn't * close this frame can be toggled to visible. null.setLayout(new BorderLayout()). int width.public static final String AUTHOR = "Real Gagnon − edited by William Denniss". hidden by a controlling * class by(using the example) outputFrame. TextArea aTextArea = new TextArea(). String fileName. * this will create a new RedirectedFrame that doesn't catch errors.height = height. this. String fileName. boolean logFile. * From the moment it is created. PrintStream aPrintStream = new PrintStream( new FilteredStream( new ByteArrayOutputStream())). this. * nor logs to the file.DO_NOTHING_ON_CLOSE).fileName = fileName.add("Center" . private private private private private private boolean catchErrors.13 Capture System. 700. int height.catchErrors = catchErrors.height). aTextArea). this. false. int closeOperation) { this.setVisible(true|false) * @param catchErrors set this to true if you want the errors to * also be caught * @param logFile set this to true if you want the output logged * @param fileName the name of the file it is to be logged to * @param width the width of the frame * @param height the height of the frame * @param closeOperation the default close operation * (this must be one of the WindowConstants) */ public RedirectedFrame (boolean catchErrors. boolean logFile. System. this.width = width. JFrame. c. c. int height. * all System. /** Creates a new RedirectFrame.out messages 14. this.logFile = logFile.closeOperation = closeOperation. 600. setSize(width. int closeOperation. displayLog().out messages and error messages (if requested) * are diverted to this frame and appended to the log file * (if requested) * * for example: * RedirectedFrame outputFrame = * new RedirectedFrame (false. // catches System.

Dimension dd = getSize(). aTextArea. 14.swing. int off. setVisible(true).width − abounds. (dim. int len) throws IOException { String aString = new String(b . // catches error messages // set the default closing operation to the one given setDefaultCloseOperation(closeOperation). } class FilteredStream extends FilterOutputStream { public FilteredStream(OutputStream aStream) { super(aStream). aTextArea. requestFocus(). true).14 Remove the titlebar of JInternalFrame .setErr(aPrintStream).plaf. aWriter.height) / 2). len). if (logFile) { FileWriter aWriter = new FileWriter(fileName. Image im = tk. Rectangle abounds = getBounds().append(aString).gif").getUI()). } } } private void displayLog() { Dimension dim = getToolkit().height − abounds.. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 14./javadetails/java−0333.com/javadetails/.getImage("myicon. setIconImage(im).setNorthPane(null).close().append(aString).getScreenSize().if (catchErrors) System. consider making a small donation to show your support for this Web site and its content.rgagnon.html ((javax.basic.BasicInternalFrameUI) myInternalFrame.write(aString). setLocation((dim.width) / 2. Toolkit tk = Toolkit. off . } } If you find this article useful.getDefaultToolkit(). } public void write(byte b[]) throws IOException { String aString = new String(b). aWriter.14 Remove the titlebar of JInternalFrame Current version of this HowTo : http://www. } public void write(byte b[].

*.add(pan.html The JTextPane can display simple HTML page. javax. java.15 Have borders on a JWindow/JFrame Current version of this HowTo : http://www.14. 14. win.getContentPane().setPage(url). jf.event.tactika. java.rgagnon. Then the JPanel is extended giving the impression that its borders are the JWindow one. JScrollPane js = new JScrollPane(). js.swing.*.com/realhome/contents.setBorder(new LineBorder(Color..net.swing. public class MyWindow{ public static void main(String s[]) { JWindow win = new JWindow(). win.15 Have borders on a JWindow/JFrame . pan.add(js).getViewport().16 Display HTML in a JScrollPane Current version of this HowTo : http://www. pan.awt. win.blue)).com/javadetails/. tp.setSize(200.com/javadetails/. jf.event. jf. import import import import javax.getContentPane().swing. } } 14. JPanel pan = new JPanel().awt.. jf.setSize(400. java. java.html You can't have a border directly on a JWindow or JFrame.200).awt.*. public class TestShowPage { public static void main(String args[]) { JTextPane tp = new JTextPane().setVisible(true).add(new JButton("World")).*. pan."Center").setVisible(true).awt. pan. import import import import javax. try { URL url = new URL("http://www. java.*./javadetails/java−0205.*.rgagnon. You need to put a JPanel with the desired border using the default JWindow/JFrame LayouManager (a BorderLayout).border.*.add(new JButton("Hello")).pack().500).add(tp). JFrame jf = new JFrame()./javadetails/java−0204.html").setLayout(new FlowLayout()).*.

rgagnon.html import java. URL url = getClass()..getResource("contents.setPage(new URL(url. . JOptionPane. to set an anchor.. } public static int okcancel(String theMessage){ 14.*. import java. . theMessage. 14. "alert". tp.swing.html").setPage(url).html").com/javadetails/.awt. } } } If the HTML is a located into a jar.17 Use a JOptionPane Current version of this HowTo : http://www.. ..event. "alert". } public static int yesnocancel(String theMessage){ int result = JOptionPane.} catch (Exception e) { e. public class MessageBox { /* These are a list of STATIC MODAL dialogs int return codes of button pressed: −1 0 1 2 − − − − WINDOW CLOSED − the X PRESSED YES and OK NO CANCEL (thanks to flipside for the idea) */ public static int yesno(String theMessage){ int result = JOptionPane. return result.getResource("contents./javadetails/java−0376. theMessage.toExternalForm() + "#section42")).. .printStackTrace(). URL url = getClass().showConfirmDialog((Component) null.. tp..YES_NO_OPTION).*. you get the URL then add the "#anchor". JOptionPane..YES_NO_CANCEL_OPTION).showConfirmDialog((Component) null.awt.*. import javax. return result..17 Use a JOptionPane .

"alert". JOptionPane.util. java. Locale locale. System. one for english messages and buttons and the other one for french.DEFAULT_OPTION).out.println("ret : " + i ).out. i = MessageBox. Create 2 properties files. return result. "alert".*. } public static void main(String args[]){ int i = MessageBox.yesnocancel("Are your sure ?").out. theMessage.OK_CANCEL_OPTION).println("ret : " + i ).int result = JOptionPane. [JOptionPane_en.awt..properties] Yes=Yes No=No Cancel=Cancel SaveMsg=Do you want to save your data [JOptionPane_fr.println("ret : " + i ).out. System.ok("Done. i = MessageBox. JOptionPane./javadetails/java−0138. public class MessageBoxExample extends JPanel implements ActionListener { JButton go.swing."). AbstractButton button. ButtonGroup group. theMessage.yesno("Are your sure ?"). java.awt.rgagnon.println("ret : " + i ).18 Localize a JOptionPane dialog Current version of this HowTo : http://www.event. System.okcancel("Are your sure ?").18 Localize a JOptionPane dialog . return result. one for french. System. } } 14. i = MessageBox. Press the button to display a localized JOptionPane according to the radio button selected.showConfirmDialog((Component) null.*. java. 14.*.properties] Yes=Oui No=Non Cancel=Annuler SaveMsg=Voulez−vous sauvegarder vos donnees Then import import import import javax. one for english .html This example will show 2 radio buttons.com/javadetails/. } public static int ok(String theMessage){ int result = JOptionPane.*.showConfirmDialog((Component) null.

setUILanguage(). locale = Locale. group.18 Localize a JOptionPane dialog . frame.FRANCE.setActionCommand("en"). add(button). UIManager. public MessageBoxExample() { group = new ButtonGroup().getString("SaveMsg").addActionListener(this).getString("Cancel")). 200).cancelButtonText". button.getBundle("JOptionPane". } else { // the button action result = JOptionPane. button. group. if (e.US. rb.noButtonText". else locale = Locale. true).String msg .out. button = new JRadioButton("Francais").addActionListener(this). } public void setUILanguage() { ResourceBundle rb.put("OptionPane. rb. button.US. add(button). System.add(button). locale).addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System. UIManager. // default value button = new JRadioButton("English".put("OptionPane. add(go).msg).showConfirmDialog(this. 14.addActionListener(this). MessageBoxExample panel = new MessageBoxExample().exit(0). } public static void main(String s[]) { JFrame frame = new JFrame(""). go.put("OptionPane.setActionCommand("fr").US. UIManager.println(result). button. go = new JButton("Do it"). } public void actionPerformed(ActionEvent e) { int result.equals("en")) locale = Locale. rb.yesButtonText". rb = ResourceBundle. locale = Locale.getString("Yes")).add(button). } } public Dimension getPreferredSize(){ return new Dimension(200. msg = rb.getString("No")).getSource() instanceof JRadioButton) { if (e.getActionCommand().

0. int rc = JOptionPane. JOptionPane. } 14. "No". as well as messages produced by the tools provided with the JRE. So you don't have to do anything to display the JFileChooser in the right language. Create 2 properties files. include Swing dialogs.")..println(buttons[rc] + " was clicked").println("Dialog closed without clicking a button. 14. if (rc==−1) { System.com/javadetails/.19 Customize JOptionPane buttons . null.} } ).html String[] buttons = {"Yes". one for french (these files are incomplete but should be enough to get you started). one for french. buttons. 0.getPreferredSize()). } else { System. "Yes to all". buttons[2]).setVisible(true). frame./javadetails/java−0310."Center").. messages written by the runtime environment to the standard output and standard error streams.19 Customize JOptionPane buttons Current version of this HowTo : http://www.html Modern Swing release have now built−in ready−to−use translations for the JFileChooser. Press the button to display a localized JFileChooser according to the radio button selected. } } 14.showOptionDialog(null.20 Localize a JFileChooser Current version of this HowTo : http://www.WARNING_MESSAGE.out. one for english. "Confirmation".out.rgagnon. "Do you really want to delete this file [" + filename + "]?". "Cancel"}.setSize(panel. frame.add(panel. The language is choosen based on the current Locale.com/javadetails/.rgagnon. The user interface elements provided by the J2SE Runtime Environment 5. These user interface elements are localized into the following languages: Sun Supported Locales This example will show 2 radio buttons. one for english ./javadetails/java−0299. frame.getContentPane().

go = new JButton("Do it"). Locale locale.add(button).[JFileChooser_en.properties] Title=Real's JFileChooser lookInLabelText=Current filesOfTypeLabelText=File type upFolderToolTipText=go up [JFileChooser_fr. button = new JRadioButton("Francais"). button. java.*.event.*.US. } public void setUILanguage() { ResourceBundle rb.setActionCommand("en"). AbstractButton button.addActionListener(this).awt. group. java. true). button.java] import import import import javax.*.addActionListener(this). add(go). locale = Locale. public LocalizeJFileChooser() { group = new ButtonGroup().setActionCommand("fr"). go.addActionListener(this).properties] Title=JFileChooser de R\u00e9al lookInLabelText=Courant filesOfTypeLabelText=Type de fichier upFolderToolTipText=Remonte Then [LocalizeJFileChooser. public class LocalizeJFileChooser extends JPanel implements ActionListener { JButton go.awt.util.swing.*. add(button).19 Customize JOptionPane buttons . protected JFileChooser z_chooser. 14. button.US. String msg . java. add(button). button. locale = Locale.add(button). group. // default value button = new JRadioButton("English". String z_choosertitle. ButtonGroup group.

200).filesOfTypeLabelText". You can examine the Swing sources to get these values or check http://www. UIManager.getString("lookInLabelText")).cancelButtonToolTipText=Cancel FileChooser. rb.gargoylesoftware. rb. setUILanguage(). UIManager.getActionCommand().equals("en")) locale = Locale. if (z_chooser.setCurrentDirectory(new java.html for a list of them.updateButtonToolTipText=Update FileChooser. if (e. else locale = Locale.getString("Title").detailsViewButtonToolTipText FileChooser.helpButtonText=Help FileChooser.setDialogTitle(z_choosertitle).newFolderToolTipText FileChooser. z_chooser.put ("FileChooser.upFolderToolTipText".put ("FileChooser. /* do the same with : FileChooser. z_chooser.updateButtonText=Update FileChooser.getSource() instanceof JRadioButton) { if (e. locale). } 14. z_choosertitle = rb.lookInLabelText".getString("filesOfTypeLabelText")).showOpenDialog(this) != JFileChooser.openButtonText=Open FileChooser.saveButtonToolTipText=Save FileChooser. UIManager.FRANCE.helpButtonToolTipText=Help Almost all Swing widgets can be customize this way.com/papers/plafdiff.")).19 Customize JOptionPane buttons . } else { z_chooser = new JFileChooser().rb = ResourceBundle. } } public Dimension getPreferredSize(){ return new Dimension(200.File(".getBundle("JFileChooser".US.openButtonToolTipText=Open FileChooser.homeFolderToolTipText FileChooser.cancelButtonText=Cancel FileChooser. rb.put ("FileChooser.APPROVE_OPTION) return.listViewButtonToolTipTextlist FileChooser.io. */ } public void actionPerformed(ActionEvent e) { int result.getString("upFolderToolTipText")).saveButtonText=Save FileChooser.fileNameLabelText FileChooser.

out. // if (chooser. LocalizeJFileChooser panel = new LocalizeJFileChooser(). } } ).out.getCurrentDirectory()). System.setSize(panel.exit(0). // chooser."Center").println("getSelectedFile() : " + chooser. } } 14.io. frame. public class DemoJFileChooser extends JPanel implements ActionListener { JButton go.rgagnon. chooser.*.. frame.*.setCurrentDirectory(new java. chooser.swing. chooser.getContentPane(). JFileChooser chooser.21 Select a directory with a JFileChooser .setFileSelectionMode(JFileChooser. add(go).getPreferredSize()).awt.println("getCurrentDirectory(): " + chooser.util. java.APPROVE_OPTION) { System.21 Select a directory with a JFileChooser Current version of this HowTo : http://www.setAcceptAllFileFilterUsed(false). chooser = new JFileChooser(). frame.*. } public void actionPerformed(ActionEvent e) { int result.")). String choosertitle.awt.DIRECTORIES_ONLY).event.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System./javadetails/java−0370. java.setVisible(true).add(panel.public static void main(String s[]) { JFrame frame = new JFrame("").setDialogTitle(choosertitle).addActionListener(this). // // disable the "All files" option.showOpenDialog(this) == JFileChooser. } else { 14.getSelectedFile()). go.*. java.com/javadetails/. public DemoJFileChooser() { go = new JButton("Do it").File(". frame.html import import import import javax.

com/javadetails/."Center").html No easy way to disable the "New Folder" button.22 Disable the JFileChooser's "New folder" button . String choosertitle. public class DemoJFileChooser extends JPanel implements ActionListener { JButton go.getPreferredSize()). frame.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System. } public void actionPerformed(ActionEvent e) { int result.*.getContentPane().out.*.util. public DemoJFileChooser() { go = new JButton("Do it"). 200). frame. DemoJFileChooser panel = new DemoJFileChooser().*./javadetails/java−0569.System.exit(0). JFileChooser chooser.22 Disable the JFileChooser's "New folder" button Current version of this HowTo : http://www.add(panel. } public static void main(String s[]) { JFrame frame = new JFrame(""). } } public Dimension getPreferredSize(){ return new Dimension(200.swing. java. consider making a small donation to show your support for this Web site and its content.awt.println("No Selection "). 14. frame.awt.event.*.setVisible(true).. You need to iterate the JFileChooser components until the right one and disable it. go. add(go). } } If you find this article useful. import import import import javax. java. } } ). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 14.rgagnon. frame.setSize(panel. java.addActionListener(this).

frame."Center").showOpenDialog(this). } else if (comp instanceof Container) { disableNewFolderButton((Container)comp).io.out.getComponentCount().println("getSelectedFile() : " + chooser.getIcon(). if (comp instanceof JButton) { JButton b = (JButton)comp.chooser = new JFileChooser().")). } } 14.add(panel. } } } public Dimension getPreferredSize(){ return new Dimension(200.setEnabled(false).setDialogTitle(choosertitle). } } public void disableNewFolderButton( Container c ) { int len = c.getSelectedFile()). Icon icon = b. // int rc = chooser. DemoJFileChooser panel = new DemoJFileChooser().getIcon("FileChooser. if (rc == JFileChooser.newFolderIcon")) b.setVisible(true). frame. } } ).getCurrentDirectory()). for (int i = 0. frame.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.println("No Selection!").File(". chooser.setCurrentDirectory(new java. i++) { Component comp = c.APPROVE_OPTION) { System. if (icon != null && icon == UIManager. i < len.setSize(panel. 200). chooser. } public static void main(String s[]) { JFrame frame = new JFrame(""). frame. System.println("getCurrentDirectory(): " + chooser.getContentPane().getPreferredSize()). disableNewFolderButton(chooser).out.23 Validate a filename from a JFileChooser . } else { System.23 Validate a filename from a JFileChooser 14.exit(0).getComponent(i).out.

html import import import import javax. public class DemoJFileChooser extends JPanel implements ActionListener { JButton go. "Open Error". } public static void main(String s[]) { JFrame frame = new JFrame("").println("No Selection!"). JOptionPane.event. System.out.ERROR_MESSAGE). add(go).*.com/javadetails/. public DemoJFileChooser() { go = new JButton("Do it").matches(regexp) // while(rc == JFileChooser. } if (rc == JFileChooser..*.rgagnon. 200). chooser.swing. } else { System.")).showOpenDialog(this). go.out./javadetails/java−0568.setCurrentDirectory(new java.io.APPROVE_OPTION && !chooser.getSelectedFile().getSelectedFile()).awt. // // loop until a .*.APPROVE_OPTION) { System. String choosertitle.java file is selected // // possible to perform complex validation // using a regular expression with .showMessageDialog(null.Current version of this HowTo : http://www. "The file " + chooser.23 Validate a filename from a JFileChooser .println("getCurrentDirectory(): " + chooser. java. rc = chooser.*.showOpenDialog(this). } } public Dimension getPreferredSize(){ return new Dimension(200.File(".getCurrentDirectory()). java.out.addActionListener(this).".util. chooser = new JFileChooser().java")){ JOptionPane.setDialogTitle(choosertitle).getSelectedFile() + " is not java source file. chooser.endsWith(". java.getName(). JFileChooser chooser. // int rc = chooser.awt.println("getSelectedFile() : " + chooser. } public void actionPerformed(ActionEvent e) { int result. 14.

24 Make a JFrame looks like a JDialog .swing. } public static void main(String[] args){ SwingUtilities. frame.html Make a JFrame unresizable and with no min/max button.awt.SwingUtilities. public class JFrameWithNoMinMax extends JFrame { public JFrameWithNoMinMax() { createAndShowUI().addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System. getRootPane().add(panel.24 Make a JFrame looks like a JDialog Current version of this HowTo : http://www.Dimension. java. javax.setSize(panel. } } 14.JFrame./javadetails/java−0582. // System.. } private void createAndShowUI(){ setTitle("This JFRAME looks like JDialog"). 14. setDefaultCloseOperation(EXIT_ON_CLOSE).exit(0). java.JRootPane.event. javax.swing. setLocationRelativeTo(null). javax. } } ). javax.awt. setSize(new Dimension(500. frame.awt.DemoJFileChooser panel = new DemoJFileChooser().swing.event.com/javadetails/.println("Window Closing"). java.getPreferredSize()).setWindowDecorationStyle(JRootPane.ActionListener. import import import import import import import import import java.PLAIN_DIALOG). The difference with JDialog is that a JFrame is shown on the taskbar (win) while a JDialog is not.setVisible(true).WindowEvent.100)).awt. frame. setResizable(false).WindowAdapter.JLabel. //addWindowListener(new WindowAdapter(){ // public void windowClosing(WindowEvent e) { // System.exit(0).invokeLater(new Runnable(){ public void run(){ new JFrameWithNoMinMax().swing.getContentPane()."Center").setVisible(true).event.rgagnon. setUndecorated(true).swing.out. // } //}). javax.JButton. frame.

} public void insertUpdate(DocumentEvent e){ disableIfEmpty(e).event. } public void disableIfEmpty(DocumentEvent e) { button.text.*.25 Based on JTextField content.swing.com/javadetails/. getContentPane(). enable or disable a JButton .setEnabled(false). } } 14.swing. } public void changedUpdate(DocumentEvent e) { disableIfEmpty(e)./javadetails/java−0196.25 Based on JTextField content.} }). getContentPane(). } public void removeUpdate(DocumentEvent e){ disableIfEmpty(e).setEnabled(e.rgagnon. javax. enable or disable a JButton Current version of this HowTo : http://www. JButtonStateController(JButton b) { button = b. JTextField textfield.awt.html import import import import java.add(textfield). textfield = new JTextField(10).getDocument(). document. document = textfield. Document document. public class DemoJButtonDisabled extends JApplet { JButton button. button.add(button).setLayout(new FlowLayout()).getLength() > 0).*.*.getDocument().addDocumentListener (new JButtonStateController(button)). } } class JButtonStateController implements DocumentListener { private JButton button. public void init() { getContentPane().swing. } } 14..*. javax. button = new JButton("foo"). javax.

swing.equals(FLOAT) || (acceptedChars..*.html The following class will help a JTextField to filter numeric or alphanumeric characters.*. public JTextFieldFilter() { this(ALPHA_NUMERIC). for (int i=0.valueOf(str. i <str.") != −1) { 14. if (acceptedChars. public static final String NUMERIC = "0123456789". import javax. public static final String UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ". public static final String ALPHA_NUMERIC = ALPHA + NUMERIC.indexOf(str. AttributeSet attr) throws BadLocationException { if (str == null) return. } public JTextFieldFilter(String acceptedchars) { acceptedChars = acceptedchars. public static final String ALPHA = LOWERCASE + UPPERCASE. } } public void insertString (int offset.".swing. i++) { if (acceptedChars.text. public class JTextFieldFilter extends PlainDocument { public static final String LOWERCASE = "abcdefghijklmnopqrstuvwxyz"./javadetails/java−0197.toUpperCase(). protected String acceptedChars = null.com/javadetails/.14. String str.equals(ALPHA_NUMERIC)){ negativeAccepted = negativeaccepted. acceptedChars += "−". public static final String FLOAT = NUMERIC + ".charAt(i))) == −1) return.26 Apply special filter to a JtextField Current version of this HowTo : http://www.26 Apply special filter to a JtextField .equals(FLOAT + "−") &negativeAccepted)) { if (str.rgagnon.equals(FLOAT) || acceptedChars. } if (acceptedChars.equals(UPPERCASE)) str = str.equals(NUMERIC) || acceptedChars. protected boolean negativeAccepted = false.indexOf(". else if (acceptedChars. } public void setNegativeAccepted(boolean negativeaccepted) { if (acceptedChars.equals(LOWERCASE)) str = str.length().toLowerCase(). import javax.

add(tf1c).setDocument (new JTextFieldFilter(JTextFieldFilter.*. tf1b = new JTextField(10).setLayout(new FlowLayout()).tf2. public class TESTJTextFieldFilter extends JApplet{ JTextField tf1. 14. JTextFieldFilter jtff = new JTextFieldFilter(JTextFieldFilter.26 Apply special filter to a JtextField . str. tf1c.add(l2).add(tf3). // l1c = new JLabel("only float(can be negative)"). // l3 = new JLabel("only 'abc123%$'"). attr). getContentPane(). import javax.insertString(offset. // l1b = new JLabel("only float").setDocument (new JTextFieldFilter(JTextFieldFilter. // l2 = new JLabel("only uppercase").indexOf("−") != −1) { if (str.indexOf(".l2.if (getText(0. getContentPane().add(l1c).add(tf2).FLOAT).FLOAT)). } } } if (negativeAccepted &str.*. getContentPane(). getContentPane().add(l1).l1b. tf2. tf1. jtff. getContentPane().NUMERIC)). tf1b. getLength()).l3. } } super.setDocument (new JTextFieldFilter(JTextFieldFilter.tf3.UPPERCASE)). tf2 = new JTextField(10).add(l3). getContentPane(). getContentPane().add(tf1b). getContentPane().setNegativeAccepted(true).l1c. // l1 = new JLabel("only numerics").add(tf1). getContentPane(). JLabel l1. getContentPane().indexOf("−") != 0 || offset != 0 ) { return.add(l1b).") != −1) { return.swing.awt. tf3 = new JTextField(10). } } import java. tf1 = new JTextField(10). tf1c = new JTextField(10). public void init() { getContentPane().tf1b.setDocument(jtff).tf1c.

setSize(300. 100).text. f. mf1.EXIT_ON_CLOSE). You can provide an input mask like (###) ###−#### for a telephone number.swing. public class JTextFieldLimit extends PlainDocument { private int limit. } } 14.rgagnon.. public class FormattedSample { public static void main (String args[]) throws ParseException { JFrame f = new JFrame("JFormattedTextField Sample").java. f.sun. and it will not accept any input that doesn't follow that format.html import com. // canadian Social Security Number MaskFormatter mf1 = new MaskFormatter("###−###−###").*.14.limit = limit. } public void insertString (int offset.add(ftf1).tf3. java.27 Limit JTextField input to a maximum length . Container content = f./javadetails/java−0198. AttributeSet attr) throws BadLocationException { 14. JFormattedTextField ftf1 = new JFormattedTextField(mf1). content.ParseException.getContentPane().*. f.Container.text.PAGE_AXIS)). content. javax.limit = limit.setLayout(new BoxLayout(content. this. you have the JFormattedTextField class. String str. import import import import java. JTextFieldLimit(int limit) { super(). javax.swing.setDefaultCloseOperation(JFrame. } } With JDK.*.awt.27 Limit JTextField input to a maximum length Current version of this HowTo : http://www. toUppercase = upper. } JTextFieldLimit(int limit.setPlaceholderCharacter('_').setVisible(true). // optional uppercase conversion private boolean toUppercase = false.com/javadetails/.swing.setDocument (new JTextFieldFilter("abc123%$")). JFormattedTextField ftf2 = new JFormattedTextField(mf2).text. BoxLayout. content. boolean upper) { super(). this. // telephone number MaskFormatter mf2 = new MaskFormatter("(###) ###−####").add(ftf2).

event. tf2 = new JTextField(5). JLabel label. public class DemoJTextFieldWithLimit extends JApplet{ JTextField textfield1. getContentPane(). getContentPane().setLayout(new FlowLayout()).setDocument (new JTextFieldLimit(10)).*.awt./javadetails/java−0199.add(label1).awt. 14. getContentPane().toUpperCase().insertString(offset.html The problem is when the lostFocus occurs on a Component.length()) <= limit) { if (toUppercase) str = str. import javax. This can be done with invokeLater method of the SwingUtilities class.add(label).*. str..28 Validate a value on the lostFocus event Current version of this HowTo : http://www. tf2.swing.28 Validate a value on the lostFocus event . super. import java. public class DemoLostFocus extends JApplet { JTextField tf1.*.setLayout(new FlowLayout()).if (str == null) return. // label = new JLabel("must be 'a' or 'b' ").awt.swing. // label1 = new JLabel("max 10 chars"). We can't use Toolkit.add(textfield1).add(tf1). } } } import java. textfield1. } } 14. textfield1 = new JTextField(15). the gainedFocus is already sent for the next component in the SystemEventQueue. import javax.getDefaultToolkit().com/javadetails/. attr).getSystemEventQueue() directly to remove the gainedFocus event because of security restriction in Applet. if ((getLength() + str. We must grab this event.*. JLabel label1.*. tf1 = new JTextField(5). and request the focus for the previous component (if there is a validation error). import java.add(tf2). getContentPane(). getContentPane(). public void init() { getContentPane(). public void init() { getContentPane().rgagnon.

event.swing. BorderLayout. InputVerfier.out.beep().show().pack(). tf = new JTextField ("howto is required").SOUTH).awt.*. public FocusGrabber(JComponent component) { this. import import import import java. if (!content.util. getContentPane().tf1. f. SwingUtilities. which can be used to do that.grabFocus(). } } JDK1. getContentPane().28 Validate a value on the lostFocus event .getText(). } public void run() { component.invokeLater(new FocusGrabber(tf1)).NORTH). javax.equals("b")) { Toolkit. public void focusLost(FocusEvent e) { if (!e.add (tf2.3 provides a new class.*. java. f. tf. BorderLayout.getDefaultToolkit().tf2.component = component.add (tf.addFocusListener( new FocusListener() { public void focusGained(FocusEvent e) {}.*. // and will allow focus to change only if the required string // is typed. addWindowListener(new WindowCloser()). } public static void main (String [] args) { Frame f = new VerifierTest (). tf2 = new JTextField ("howto come here").setInputVerifier(new HowtoVerifier()). java. } } class FocusGrabber implements Runnable { private JComponent component. System.awt.isTemporary() &isEnabled() ) { String content = tf1.println("illegal value! " + content ). } } class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent e) { 14. } }} }). class VerifierTest extends JFrame { public VerifierTest () { JTextField tf. // the first JTextField expects the string "howto" as input.equals("a") &!content.*.

equals("howto")) { SwingUtilities.setBorder( new LineBorder(Color. } })..getText(). Here a bad textfield will show a red border. but with some browsers (like Netscape)..Window win = e. simply request the focus for the JTextfield.*.swing.setVisible(false).*. return false.event. return pass. import java. a good one will be black. } SwingUtilities.29 Make sure that my jTextfield has the focus when a JFrame is created Current version of this HowTo : http://www..29 Make sure that my jTextfield has the focus when a JFrame is created . if (!pass./javadetails/java−0200.border. } }). . } } class HowtoVerifier extends InputVerifier { public boolean verify(JComponent input) { JTextField tf = (JTextField) input.. import javax. you need to do it.exit(0).invokeLater(new Runnable(){ public void run(){ input. win. import java.createBlackLineBorder() ). } } It's not a bad idea to give a visual cue that the textfield is not validated. 14.*. } } .invokeLater(new Runnable(){ public void run(){ input.setBorder( LineBorder.*.rgagnon. 14.getText(). return true.RED) ).getWindow().equals("howto"). From there. String pass = tf.awt. String pass = tf. class HowtoVerifier extends InputVerifier { public boolean verify(final JComponent input) { JTextField tf = (JTextField) input. This is not needed with the Appletviewer or in Application.html In a JFrame. import javax. use a small WindowAdapter to listen to the WindowOpened event.com/javadetails/.awt.. System.swing.

public class MyFrame extends JFrame { JTextField field1. JPanel panel. addWindowListener( new WindowAdapter() { public void windowOpened( WindowEvent e ){ field1.html When the user inputs an invalid value into JFormattedTextField.awt. public class MyFrameApplet extends JApplet { public void init() { MyFrame myFrame = new MyFrame(). setVisible( true ). class MyJFormattedTextField extends JFormattedTextField { .swing. panel ). pack(). import javax../javadetails/java−0427.30 Stop the beep on JFormattedTextField Current version of this HowTo : http://www.requestFocus(). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 14. panel.*. } } To try it : import java. import java.com/javadetails/.rgagnon. public MyFrame() { super( "This is my Frame" ).event. panel. JTextField field2.awt. protected void invalidEdit() {} . field2 = new JTextField( 10 ).*. field1 = new JTextField( 10 ). consider making a small donation to show your support for this Web site and its content.add( field2 ).add( field1 ). getContentPane().. To avoid this annoying beep. the default behavior is to emit a beep. simply overload the invalidEdit() method. } } 14.add( new JLabel("Field 1:")). } If you find this article useful. panel. panel.add( "Center".. } } ).*...30 Stop the beep on JFormattedTextField . panel = new JPanel().add( new JLabel("Field 2:")).

swing.31 Right justified JTextfield content Current version of this HowTo : http://www.rgagnon.31 Right justified JTextfield content .rgagnon.*.setHorizontalAlignment(JTextField..requestFocus(). import java. *.. public class Test extends JApplet { JTextField textfield./javadetails/java−0493.com/javadetails/.*.RIGHT).awt.event.32 Set the focus on a particuliar JTextField Current version of this HowTo : http://www.33 Make JTextField unselectable Current version of this HowTo : http://www.swing../javadetails/java−0546.util.com/javadetails/.*. java.*. // Right−justify the text textfield.html import javax.html import import import import java.html SwingUtilities. javax./javadetails/java−0510. class UnselectableJTextField extends JFrame { 14.awt.invokeLater(new Runnable() { public void run() { myJTextField. getContentPane(). public void init() { getContentPane().*. consider making a small donation to show your support for this Web site and its content.com/javadetails/.add(textfield). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 14.rgagnon. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 14. If you find this article useful. consider making a small donation to show your support for this Web site and its content. textfield = new JTextField(10). java.awt.14. } } If you find this article useful. } }).setLayout(new FlowLayout()).

rgagnon. BorderLayout.add (tf1. _openedIcon = opened.setVisible(false). String link.0. we define the class representing a node. tf2 = new JTextField ("you can't select with the mouse"). f. RealSwingNode (String title. win.add (tf2.*. f. getContentPane(). private ImageIcon _closedIcon. } 14.34 Use a JTree to navigate in a site . import javax. ImageIcon opened) { _title = title.pack(). System. ImageIcon closed. public class RealSwingNode extends Object { private String _title.setVisible(true).. } } } 14. } class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent e) { Window win = e./javadetails/java−0209. 2 icons (open and close). // getContentPane(). This node contains a title (the label). private String _link.com/javadetails/.exit(0). BorderLayout. private ImageIcon _openedIcon. addWindowListener(new WindowCloser()).setHighlighter(null).getWindow(). NOTE: This Tree Applet is different since it's plain JDK1.html This How−to will show you how to build a Tree (like this one) using Swing. _link = link. } public static void main (String [] args) { Frame f = new UnselectableJTextField ().34 Use a JTree to navigate in a site Current version of this HowTo : http://www.public UnselectableJTextField () { JTextField tf1.SOUTH).swing. _closedIcon = closed.NORTH).2 Applet. // disable mouse or keyboard selection to prevent "cut and paste" tf2. First. tf1 = new JTextField ("you can select with the mouse").tf2. a URL.

34 Use a JTree to navigate in a site . import java. RealSwingTreeIconRenderer() { _label = new JLabel().awt.getBackground()). } public Component getTreeCellRendererComponent (JTree tree.setFont(tree.getUserObject() instanceof RealSwingNode) { _userObject = (RealSwingNode) node. boolean selected. boolean expanded.setIcon(null).setIcon(_userObject.getOpenedIcon()). } } if(_userObject != null) { if (expanded) _label.*. import javax.getBackground()). else _label. if (selected){ _label. Object value. _label.setBackground(tree. } ImageIcon getOpenedIcon() { return _openedIcon.swing.swing.getUserObject(). _label.setIcon(_userObject.tree. } else if(value instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode node. } ImageIcon getClosedIcon() { return _closedIcon.getFont()). } else { _label. } else { _label. } if (value instanceof RealSwingNode) { _userObject = (RealSwingNode) value.setBackground(tree. boolean hasFocus) { RealSwingNode _userObject = null.getTitle()).getForeground()).getClosedIcon()). node = (DefaultMutableTreeNode) value. This is done by implementing a Renderer class. public class RealSwingTreeIconRenderer extends Object implements TreeCellRenderer { JLabel _label.setForeground(tree.*.setText(_userObject. boolean leaf. _label.*.setOpaque(true). import javax.getForeground()).String getTitle() { return _title. } public String toString() { return _title. _label.setForeground(tree. } String getLink() { return _link. if (node. int row. 14. } } Then we define how the node would be shown in the Tree. _label.

java.getParameter("targetframe"). RealSwingTreeIconRenderer rstir.net. try { UIManager. RealSwingNode rsn = null.out. private Font f.swing.*. System. String strValue. int token. private String targetFrame. java. oldvalue=0.tree.println("[RealSwingTree] Begin populateTree() " ). TreeSelectionModel tsm. image2idx=0. } } The next step is building the JTree in a JPanel.printStackTrace(). import import import import import import import import javax. boolean rootDone=false._label. lnkValue. DefaultMutableTreeNode node = null.*. targetFrame = parentApplet. imageValue.swing.io. image1idx=0. private JTree tree.34 Use a JTree to navigate in a site . try { initTreeIcons(). value=0.setText(value. } } public void setParentApplet(JApplet j) { parentApplet = j.event. java. We use a datafile to define the Tree nodes.name")). 14. private ImageIcon treeIcons[].event.*.awt. public RealSwingTree() { System.getSystemLookAndFeelClassName()). javax.getProperty("os. java.*. we must pass a JApplet reference to be able to read some parameters passed via the HTML PARAM tags.toString()).util. DefaultMutableTreeNode currentNode = null.awt. Since this Tree is designed to be used in Applet.*.swing. boolean itemDone=true.println(System. } public void initTree() { // build the tree from the datafile DefaultMutableTreeNode rootNode = null. } catch (Exception ex_ignored) { ex_ignored. } return _label.*.*. rootvalue=0. public class RealSwingTree extends JPanel implements TreeSelectionListener { private JApplet parentApplet.*.out. java.setLookAndFeel( UIManager. javax.

add(node).nextToken(). if (value >= oldvalue) { if (value==oldvalue) { // *** sibling if (currentNode. rsn = new RealSwingNode(strValue. parentApplet.nextToken().getParameter("datafile")). true). rsn = new RealSwingNode (strValue.quoteChar('"'). oldvalue−−.equals(rootNode)) rootNode.34 Use a JTree to navigate in a site . StreamTokenizer st = new StreamTokenizer(r).equals(rootNode)) 14. lnkValue = st.nval).add(node).nextToken().openStream())).parseInt(st. token = st. token = st. st. treeIcons[image1idx]. token = st. "". null). dmtn. } } else { // *** new branch. lnkValue = st. Reader r = new BufferedReader (new InputStreamReader(urlFile.sval. // // datafile structure <level> <label> <link> <image1> <image2> // while ((token = st.add(node). true).eolIsSignificant(false). st.TT_EOF ) { // get level value = new Double(st. lnkValue.sval.nextToken().sval).sval.nextToken(). else { DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)currentNode.getCodeBase(). null. node = new DefaultMutableTreeNode(rsn. image1idx = Integer.getParent(). } else { token = st. } DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)currentNode.getParent(). strValue = st. token = st. image2idx = Integer.URL urlFile = new URL(parentApplet. if (!rootDone) { // do the root first token = st. strValue = st.parseInt(st.getParent(). rootDone = true.nextToken()) != StreamTokenizer.parseNumbers(). } } else { // *** child currentNode. rootNode = node. node = new DefaultMutableTreeNode(rsn.nextToken(). if (dmtn. treeIcons[image2idx]). must get back to the right level while (value < oldvalue) { currentNode = (DefaultMutableTreeNode)currentNode.sval. st.sval).intValue().

setShowsRootHandles(true). String leaveImagesList.getSelectionModel().setSelectionMode(TreeSelectionModel.addElement(s). Integer. Font.setRootVisible(true). tsm = tree.getParameter("leaveimageslist").getParameter("images"). leaveImagesList = parentApplet. ". Color bgcolor = new Color( Integer.SINGLE_TREE_SELECTION).println("[RealSwingTree] End populatetree()"). } catch (Exception e) {e.addTreeSelectionListener(this).PLAIN. tree.getParameter("point"))).nextToken(). String pathImages. rstir = new RealSwingTreeIconRenderer(). i < leaveImage. Vector leaveImage = new Vector(). tree.").println("begin initImage()").34 Use a JTree to navigate in a site .add(node)."Center"). } tree = new JTree(rootNode). pathImages = parentApplet.setRowHeight(0).parseInt(parentApplet.getParameter("rootimage").getParameter("font").out.size()]. oldvalue = value. } public void initTreeIcons() { String rootImage. } } currentNode = node. rootImage = parentApplet.out.add(node). tree. for(int i=0.intValue()). leaveImage. tree.setCellRenderer(rstir). tree.printStackTrace().valueOf (parentApplet. StringTokenizer leavesList = new StringTokenizer(leaveImagesList.hasMoreTokens()){ String s=leavesList.getParameter("bgcolor"). setFont(f). while(leavesList.rootNode. else dmtn. setLayout(new BorderLayout()). i++) { try { URL imageURL = new URL 14. 16). add(new JScrollPane(tree). System. Font f = new Font (parentApplet. } treeIcons = new ImageIcon[leaveImage. tsm. } System.size(). setBackground(bgcolor).

34 Use a JTree to navigate in a site . System.println(" url: " + newURL. } catch (Exception e) { e.getSelectionPath()..getCodeBase() + "/" + pathImages + "/" + (String)leaveImage.getLink()). } catch(Exception e) { e. import java. rst. System.. } } Here a sample datafile.out. The structure is "[level] [label] [link] [image1] [image2]".println("Loading .(parentApplet.println("end initImage()").toString() + " target:" +targetFrame).*.out. rsn = (RealSwingNode)dmtn.out. 400).getCodeBase() + rsn." + (String)leaveImage.println("Click! link: " + rsn.swing. public class RealSwingTreeApplet extends JApplet { RealSwingTree rst.getUserObject(). 14. } public void valueChanged(TreeSelectionEvent tse) { DefaultMutableTreeNode dmtn. RealSwingNode rsn.elementAt(i)).targetFrame).out.getLastPathComponent().initTree(). treeIcons[i] = new ImageIcon(imageURL).getLink(). } } } } public Dimension getPreferredSize() { return new Dimension(250.getAppletContext().*. public void init() { rst = new RealSwingTree(). } } Let's make a simple Applet to try it out. } } System.setParentApplet(this). TreePath path = tree. parentApplet.showDocument (newURL. System. if (!rsn.elementAt(i)).add(rst).equals("")) { try { URL newURL = new URL (parentApplet.awt.printStackTrace(). rst. if (path != null) { dmtn = (DefaultMutableTreeNode) path.printStackTrace(). The image number is the index of the image passed via the PARAM leaveimageslist. import javax.getLink()). getContentPane().

. you need to execute the Applet under the Java plugin.page.jpg. you need to use the <EMBED> tag with Netscape or <OBJECT> tag with IE. with Netscape.35 Expand or collapse a JTree Current version of this HowTo : http://www.2" width="200" height="2000" code="RealSwingTreeApplet.jpg fpage..jpg fopen.html" 0 "Java How−to" "" "0" "1" 1 "What's new" "java−new.2/plugin−install.2.html" "2" "2" 1 "General" "" "0" "1" 2 "part 1" "java−g1.com/javadetails/.*. pluginspage="http://java.jpg"> </APPLET></BODY></HTML> The <APPLET> tag and Swing applet are ok with Appletviewer.. 14.2 support for APPLET!! </NOEMBED> </EMBED> </BODY></HTML> Finally. Since there is almost no error checking.jpg 14.35 Expand or collapse a JTree . all PARAM tags are required.sun.gif"> <PARAM NAME="leaveimageslist" VALUE="fclose./images"> <PARAM NAME="targetframe" VALUE="_top"> <PARAM NAME="rootimage" VALUE="root. <HTML><BODY> <APPLET CODE="RealSwingTreeApplet..html"> <NOEMBED> No JDK 1.rgagnon.txt] 0 "Welcome | Bienvenue" "welcome.[treedata..jpg.html import javax./javadetails/java−0210. other params here .version=1.txt"> <PARAM NAME="bgcolor" VALUE="FFFFFF"> <PARAM NAME="font" VALUE="Courier"> <PARAM NAME="point" VALUE="11"> <PARAM NAME="images" VALUE=". you may want to grab these images used in this How−to .com/products/plugin/1. the HTML will be like this : <HTML><BODY> <EMBED type="application/x−java−applet.html" "2" "2" Here the HTML used to test the Tree.fopen. root.class" NAME="RealTree" HEIGHT=2000 WIDTH=196> <PARAM NAME="datafile" VALUE="treedata.txt" bgcolor="FFFFFF" .gif fclose. Therefore.swing. but in most browser.class" datafile="treedata. So for example.

SimpleTree panel.add(node2). node1.tree.300). b3. node3.util.black). java.add(b2. } } class MyJFrame extends JFrame implements ActionListener { JButton b1. node3. win. b3. true). getContentPane().exit(0). panel = new SimpleTree(). setForeground(Color. } } class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent e) { Window win = e. node1 = new DefaultMutableTreeNode("node 1". node1. java.awt.add(panel.import import import import javax.addActionListener(this). node3 = new DefaultMutableTreeNode("node 3" . node4 = new DefaultMutableTreeNode("node 4" . root."Center"). true).add(b3."Center"). public SimpleTree() { root = new DefaultMutableTreeNode("root". true). getContentPane()."West"). java. } public static void main(String s[]){ MyJFrame frame = new MyJFrame("Tree Collapse Expand"). node4. System. } public Dimension getPreferredSize(){ return new Dimension(200. add(new JScrollPane((JTree)tree). b2.*. 120).*.addActionListener(this).*.*."North"). node2 = new DefaultMutableTreeNode("node 2" .awt. MyJFrame(String s) { super(s). root. setBackground(Color. expandAll(panel. b2 = new JButton("Collapse"). getContentPane().35 Expand or collapse a JTree . setVisible(true).tree). node2. 14. getContentPane()."East"). tree = new JTree(root).add(node1).lightGray). b1 = new JButton("Expand").add(node4).swing. b3 = new JButton("Expand to last"). true). setSize(300. b1.event. b2. public class SimpleTree extends JPanel { JTree tree.add(node3).addActionListener(this).add(b1.getWindow().setVisible(false). setLayout(new BorderLayout()). DefaultMutableTreeNode root. true).

} */ public void collapseAll(JTree tree) { int row = tree.tree).scrollPathToVisible(new TreePath(root. tree.getModel().getChild(node. if (ae.getSource() == b1) expandAll(panel. TreePath p = new TreePath(node).getSource() == b3) expandToLast(panel. while (row >= 0) { tree.tree). addWindowListener(new WindowCloser()). } public void expandAll(JTree tree) { int row = 0.scrollPathToVisible(p).pathByAddingChild(node). row−−.getPath())).setDefaultCloseOperation(JFrame.getChildCount(node). while (row <tree.getModel(). if (node == null) return. Object node = data. if (count == 0) break. } } } 14.expandRow(row).collapseRow(row).36 Have a popup attached to a JTree .getSource() == b2) collapseAll(panel. if (ae. } } public void expandToLast(JTree tree) { // expand to the last leaf from the root DefaultMutableTreeNode root.getRowCount()) { tree.getRowCount() − 1.36 Have a popup attached to a JTree 14.DO_NOTHING_ON_CLOSE). } /* // alternate version. } tree.getRoot().getLastLeaf(). p = p. } public void actionPerformed(ActionEvent ae) { if (ae.Kaufhold public void expandToLast(JTree tree) { TreeModel data = tree. while (true) { int count = data. row++.getRoot().tree). suggested by C. root = (DefaultMutableTreeNode) tree. node = data. count − 1).

/javadetails/java−0211.com/javadetails/.lightGray). frame.*. // define the popup popup = new JPopupMenu(). mi.*.setActionCommand("insert").tree.addActionListener(this). 300). node3 = new DefaultMutableTreeNode("node 3".awt.exit(0). win. setLayout(new BorderLayout()). node1 = new DefaultMutableTreeNode("node 1". true). node2.*.setVisible(true). java. 14.black). System.add(node3).*. javax.swing. tree = new MyJTree(root).add(node1).getContentPane(). JMenuItem mi. true). frame. public class TreeWithPopup extends JPanel { DefaultMutableTreeNode root. add(new JScrollPane((JTree)tree). java.setVisible(false).rgagnon. frame.event. node3.. java.add(node2).setSize(panel.36 Have a popup attached to a JTree ."Center"). frame.getPreferredSize()). node1.Current version of this HowTo : http://www. mi = new JMenuItem("Insert a children"). mi.addWindowListener(new WindowCloser()).setBackground(Color. TreeWithPopup panel = new TreeWithPopup().setDefaultCloseOperation(JFrame.html import import import import import javax.getWindow().swing. node2 = new DefaultMutableTreeNode("node 2" . } public static void main(String s[]){ JFrame frame = new JFrame("Tree With Popup"). node1.util. frame.awt. } } class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent e) { Window win = e.DO_NOTHING_ON_CLOSE). frame. public TreeWithPopup() { MyJTree tree. true). } } class MyJTree extends JTree implements ActionListener{ JPopupMenu popup. } public Dimension getPreferredSize(){ return new Dimension(300. root.*. MyJTree (DefaultMutableTreeNode dmtn) { super(dmtn)."Center"). root = new DefaultMutableTreeNode("root". true). frame. root.add(panel.setForeground(Color.

html import import import import javax. true). true). mi.getSelectionPath(). n2 = new DefaultMutableTreeNode("node 2" .nodeStructureChanged((TreeNode)dmtn).setActionCommand("remove").n4. node. // thanks to Yong Zhang for the tip for refreshing the tree struct ((DefaultTreeModel )this. dmtn. public class TraverseSimpleTree extends JPanel { JTree tree. popup.rgagnon. javax. true).awt.getLastPathComponent().add(mi).getY() ).getSource(). n4 = new DefaultMutableTreeNode("node 4" .com/javadetails/. n2.getModel()) .*. popup. n1.event. n1 = new DefaultMutableTreeNode("node 1".add(node).addActionListener(this).getActionCommand().nodeStructureChanged((TreeNode)dmtn).show( (JComponent)e. mi.*.getActionCommand().setLightWeightPopupEnabled(true). java. } if (ae.37 Traverse a JTree Current version of this HowTo : http://www.swing. dmtn = (DefaultMutableTreeNode) path.awt. popup. TreePath path = this.equals("remove")) { node = (DefaultMutableTreeNode)dmtn.*.. } } } ).equals("insert")) { node = new DefaultMutableTreeNode("children"). n3. addMouseListener ( new MouseAdapter () { public void mouseReleased( MouseEvent e ) { if ( e.setOpaque(true). n3 = new DefaultMutableTreeNode("node 3" .popup. public TraverseSimpleTree() { root = new DefaultMutableTreeNode("root".getX(). java. if (ae.n5.tree.getModel()) .37 Traverse a JTree .swing.removeAllChildren(). ((DefaultTreeModel )this.*. mi = new JMenuItem("Remove this node"). node. true). } public void actionPerformed(ActionEvent ae) { DefaultMutableTreeNode dmtn./javadetails/java−0313.isPopupTrigger()) { popup. e. true). 14. DefaultMutableTreeNode root.getParent(). } } } 14. e.add(mi).

n4. } 14. setBackground(Color. b2.lightGray).toString()).n5 = new DefaultMutableTreeNode("node 5" . 120).tree). root.println(root.add(b1.exit(0).addActionListener(this).add(n5). } } class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent e) { Window win = e.getModel().out. } public Dimension getPreferredSize(){ return new Dimension(200. setVisible(true).add(n2).add(n1). setLayout(new BorderLayout()).getRoot(). } public static void main(String s[]){ MyJFrame frame = new MyJFrame("Traverse Tree"). getContentPane(). walk(model. b1. true). win.println("Tree is empty. setSize(300. TraverseSimpleTree panel. root."West"). addWindowListener(new WindowCloser()).setVisible(false)."Center"). tree = new JTree(root).black). getContentPane().add(n4). } public void traverse(JTree tree) { TreeModel model = tree. n3.DO_NOTHING_ON_CLOSE).300). setDefaultCloseOperation(JFrame. b1 = new JButton("Traverse (check the console)")."). } public void actionPerformed(ActionEvent ae) { if (ae. setForeground(Color. } } class MyJFrame extends JFrame implements ActionListener { JButton b1.getSource() == b1) traverse(panel. System.getWindow()."Center").root). panel = new TraverseSimpleTree(). add(new JScrollPane((JTree)tree). MyJFrame(String s) { super(s).out. System. } else System.add(panel.37 Traverse a JTree . n1. b3.add(n3). if (model != null) { Object root = model.

*.awt.39 Explore directories with a JTree Current version of this HowTo : http://www.tree./javadetails/java−0324.*.getChild(o. .event.*. java.awt. Object o){ int cc. Angled Vertical lines between nodes at the same level.swing./javadetails/java−0325.rgagnon.util.toString()+"−−").toString()).. Or from the command line java −DJTree.out. javax.. This is the default setting.io.html import import import import import import javax. cc = model.*. java. } } } } 14. walk(model.out.38 Show dotted lines in a JTree Current version of this HowTo : http://www. See also List of undocumented properties to change the behavior of Swing in Suns JVM.swing.*..*. tree. for( int i=0.38 Show dotted lines in a JTree . Horizontal A single horizontal line between nodes immediately attached to the root node.isLeaf(child)) System.html In your code . if (model.child ). horizontal line to child node. 14. 14.getChildCount(o). "Angled").lineStyle". java..com/javadetails/.putClientProperty("JTree.com/javadetails/. java. i < cc.rgagnon.print(child.protected void walk(TreeModel model.. i ).lineStyle=Angled MyApp Other possible values : None No lines are drawn anywhere on the tree. i++) { Object child = model. else { System..println(child.

println("DIRECTORY − " + f.out. add(new JScrollPane((JTree)tree). public SimpleTree() { root = new DefaultMutableTreeNode("root". tree.isDirectory()) { // We keep only JAVA source file for display in this HowTo if (f.listFiles()."Center"). addWindowListener(new WindowCloser()).setRootVisible(false).add(child). DefaultMutableTreeNode root. System.getName(). node. setDefaultCloseOperation(JFrame. fList[i]).out."Center"). node.300). } } class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent e) { Window win = e.length. getList(root.add(child). SimpleTree panel. } } 14. b3. } } public static void main(String s[]){ MyJFrame frame = new MyJFrame("Directory explorer").add(panel. i++) getList(child. panel = new SimpleTree(). new File("c:/temp")). for(int i = 0. i <fList. win.getName()).DO_NOTHING_ON_CLOSE).getName()). MyJFrame(String s) { super(s). b2.public class SimpleTree extends JPanel { JTree tree.exit(0). File f) { if(!f. true). 120). DefaultMutableTreeNode child = new DefaultMutableTreeNode(f). } public Dimension getPreferredSize(){ return new Dimension(200. tree = new JTree(root).setVisible(false). setLayout(new BorderLayout()).endsWith("java")) { System.38 Show dotted lines in a JTree .getWindow(). File fList[] = f. } public void getList(DefaultMutableTreeNode node. } } class MyJFrame extends JFrame { JButton b1. getContentPane(). setSize(300. DefaultMutableTreeNode child = new DefaultMutableTreeNode(f). } } else { System.println("FILE − " + f. setVisible(true).

[JDK1.getKeyStroke("ctrl A")./javadetails/java−0398. } }). basicTreeUI. [JDK1.41 Single selection in a JTree Current version of this HowTo : http://www. tree. "you can't collapse this JTree").getUI().SINGLE_TREE_SELECTION).addTreeWillExpandListener (new TreeWillExpandListener() { public void treeWillExpand(TreeExpansionEvent e) { } public void treeWillCollapse(TreeExpansionEvent e) throws ExpandVetoException { throw new ExpandVetoException(e.14..getInputMap()..rgagnon. If you find this article useful.getSelectionModel(). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 14. tree../javadetails/java−0339.put(ks.html myJTree.rgagnon.html myJTree. setSelectionMode(TreeSelectionModel.com/javadetails/.com/javadetails/.unregisterKeyboardAction(ks)./javadetails/java−0395.3+] KeyStroke ks = KeyStroke. 14.40 Prevent JTree collapsing Current version of this HowTo : http://www. "none").42 Reduce JTree children indentation Current version of this HowTo : http://www. consider making a small donation to show your support for this Web site and its content.html BasicTreeUI basicTreeUI = (BasicTreeUI) myJTree.getKeyStroke("ctrl A").com/javadetails/.40 Prevent JTree collapsing .setRightChildIndent(10).rgagnon. 14. Also you may want to disable the CTRL−A key which select the entire tree.2] KeyStroke ks = KeyStroke.

node3 = new DefaultMutableTreeNode("node 3" .add(node2).*.swing.rgagnon. new ImageIcon("treeMinus. public SimpleTree() { root = new DefaultMutableTreeNode("root". new ImageIcon("treeMinus.43 Use + or − for JTree Icons .put("Tree.swing. true).html The default look and feel for a JTree.add(node1). true). setLayout(new BorderLayout()). node1 = new DefaultMutableTreeNode("node 1". UIManager.*. javax.*. node3.event.*.collapsedIcon". 14. root.43 Use + or − for JTree Icons Current version of this HowTo : http://www.expandedIcon". node1.put("Tree.awt. public class SimpleTree extends JPanel { JTree tree. If you want to use the more regular − and + sign to collapse or expand a tree node. node2 = new DefaultMutableTreeNode("node 2" . root.put("Tree. Example import import import import import javax.com/javadetails/. you need to call UIManager.collapsedIcon".put("Tree. java.gif")). new ImageIcon("treePlus.14.awt.gif")). to replace default images. DefaultMutableTreeNode root. node1./javadetails/java−0517. node4 = new DefaultMutableTreeNode("node 4" . UIManager. true)..gif")).util. java.add(node4).tree. java.add(node3). node2.*. UIManager.expandedIcon". true). node4. node3. true).

com/javadetails/. } public static void main(String s[]){ MyJFrame frame = new MyJFrame("SimpleTree"). } } The required small GIFs : If you find this article useful. System.new ImageIcon("treePlus. add(new JScrollPane((JTree)tree). addWindowListener(new WindowCloser()).44 Change the JTable header color Current version of this HowTo : http://www.yellow). If you find this article useful. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 14. consider making a small donation to show your support for this Web site and its content./javadetails/java−0334.add(panel. setForeground(Color. } } class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent e) { Window win = e.DO_NOTHING_ON_CLOSE).44 Change the JTable header color . consider making a small donation to show your support for this Web site and its content. setVisible(true). } } class MyJFrame extends JFrame { SimpleTree panel.setForeground(new Color(0). Written and compiled by Réal Gagnon ©1998−2005 [ home ] 14.exit(0).setBackground(new Color(0).black). setSize(300. setDefaultCloseOperation(JFrame.getWindow(). getContentPane().rgagnon. MyJFrame(String s) { super(s).300).getTableHeader(). anHeader.setVisible(false).. } public Dimension getPreferredSize(){ return new Dimension(200. tree = new JTree(root).gif"))."Center"). 120). win."Center"). anHeader. panel = new SimpleTree().black).lightGray). setBackground(Color.html JTableHeader anHeader = aTable.

*.. frame. "Andrews".length.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent e){ if (e.awt.event. }. JScrollPane scrollpane = new JScrollPane(aTable). aTable. import java. } public String getColumnName(int column) {return names[column].*. listMod.getContentPane().*.event.getClickCount() == 2){ System.14.setPreferredSize(new Dimension(300. aTable = new JTable(dataModel). {"Alan".swing. } public int getRowCount() { return data. "Last Name".addListSelectionListener(this).event. new Integer(1)}. "Chung". public class SimpleTable implements ListSelectionListener { JTable aTable. final Object[][] data = { {"Mark". 300)).*.setSelectionMode(ListSelectionModel.*. } }.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.add(scrollpane).getClass(). final String[] names = {"First Name". import java.*.rgagnon.pack().com/javadetails/.} public Class getColumnClass(int col) { return getValueAt(0. new Integer(3)}. frame.setVisible(true). int row. } public void setValueAt(Object aValue.}}). new Integer(2)}.getSelectionModel().awt.swing.table. import java. "Id" }. {"Tom". import javax. listMod. int column) { data[row][column] = aValue. import javax. public SimpleTable() { JFrame frame = new JFrame("Table"). "Ball"./javadetails/java−0336.awt. ListSelectionModel listMod = aTable.println(" double click" ). int col) { return data[row][col]. scrollpane.out. frame. frame.45 Double click on a JTable .col).} public Object getValueAt(int row. 14.swing.html import javax.length. TableModel dataModel = new AbstractTableModel() { public int getColumnCount() { return names.exit(0).SINGLE_SELECTION).45 Double click on a JTable Current version of this HowTo : http://www.

} System. [DataFileTableModel. import javax. Object value. Fields are separated by the "|" character.rgagnon. } } } public static void main(String[] args) { new SimpleTable()./javadetails/java−0213.dat] Id|Name|City|Phone 102|Beth Reiser|New York|(212)5558725 111|Dylan Ricci|Syracuse|(315)5554486 116|Brian Gugliuzza|Mamaroneck|(914)5553817 120|Gertrude Stein|Elmsford|(914)5553476 131|Daljit Sinnot|Bohemia|(516)5559811 First we need a TableModel to define the data structure to used by the JTable.java] import javax.i). i++) { // get Table data TableModel tm = aTable. consider making a small donation to show your support for this Web site and its content.table. if (selRows.swing.out.println("Selection : " + value ).} } } ). if (!e. int[] selRows.getModel().46 Read a data file into a JTable Current version of this HowTo : http://www. System.getValueAt(selRows[0].html The first line of the data file contains the column names. [customers.getSelectedRows().swing. import javax.*.*.. 14. } public void valueChanged(ListSelectionEvent e) { int maxRows.46 Read a data file into a JTable .*.event.swing. value = tm. i <3 .println().com/javadetails/. } } If you find this article useful. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 14.out.length > 0) { for (int i= 0.getValueIsAdjusting()) { selRows = aTable.

nextToken()). "|").close(). import java. try { FileInputStream fin = new FileInputStream(datafile). initVectors(). } 14. } public Class getColumnClass(int columnIndex){ return String. while(st1. // extract column names StringTokenizer st1 = new StringTokenizer(br. // extract data while ((aLine = br. while(st2.readLine().addElement(st2. columnNames = new Vector().hasMoreTokens()) columnNames.nextToken()). } catch (Exception e) { e. int columnIndex) { return false. } public String getColumnName(int columnIndex) { String colName = "". protected Vector columnNames . } public boolean isCellEditable(int rowIndex. } public int getColumnCount(){ return columnNames.size(). public DataFileTableModel(String f){ datafile = f.elementAt(columnIndex).*.class.*.printStackTrace().io.size() / getColumnCount(). } br.readLine()) != null) { StringTokenizer st2 = new StringTokenizer(aLine. public class DataFileTableModel extends AbstractTableModel { protected Vector data. BufferedReader br = new BufferedReader(new InputStreamReader(fin)). "|"). protected String datafile.import java.addElement(st1. } public void initVectors() { String aLine . data = new Vector(). return colName.util. if (columnIndex <= getColumnCount()) colName = (String)columnNames. } } public int getRowCount() { return data.hasMoreTokens()) data.46 Read a data file into a JTable .

add(panel. DataFileTableModel model. } public Dimension getPreferredSize(){ return new Dimension(400. setFont(f). frame.24).lightGray). frame. } } [DataFileTable. f = new Font("SanSerif". JScrollPane scrollpane = new JScrollPane(table). 300).getWindow(). java. public class DataFileTable extends JPanel { public DataFileTable(String dataFilePath) { JTable table.swing. frame. model = new DataFileTableModel(dataFilePath).awt. java.*.awt. panel = new DataFileTable("customers.*.black). 14.setVisible(true).public Object getValueAt(int rowIndex. frame.io.Font.java] import import import import import javax. frame.PLAIN. int columnIndex) { return.*.addWindowListener(new WindowCloser()). add(scrollpane).createDefaultColumnsFromModel().setDefaultCloseOperation(JFrame. } public static void main(String s[]) { JFrame frame = new JFrame("Data File Table").getContentPane(). } } class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent e) { Window win = e. setLayout(new BorderLayout()). int rowIndex.dat").*.util.46 Read a data file into a JTable . DataFileTable panel.setBackground(Color. java. table. frame.DO_NOTHING_ON_CLOSE).setModel(model)."Center").setForeground(Color. int columnIndex) { return (String)data.setSize(panel. frame. java. table.event. } public void setValueAt(Object aValue. Font f.*. table = new JTable().getPreferredSize()).elementAt ( (rowIndex * getColumnCount()) + columnIndex).

com/javadetails/.*.PLAIN.html We use the Observer/Observable mechanism to detect if the data file have been modifed since the last time. setLayout(new BorderLayout()).swing.io. 14.24). setFont(f). java.html aTable..Font.rgagnon. java.awt.awt./javadetails/java−0338. System. Font f. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 14. Some minor modifications are needed for the DataFileTable class.47 Disable row selection in a JTable . This class now implements the Observer interface (see the update() method which will be called when the Observable object send a notification). java. public DataFileTable(String dataFilePath) { DataFileWatchdog wd. [DataFileTable.*.rgagnon. aTable.*.event.*.util. If you find this article useful.47 Disable row selection in a JTable Current version of this HowTo : http://www.*.com/javadetails/.java] import import import import import javax. f = new Font("SanSerif". public class DataFileTable extends JPanel implements Observer { protected JTable table. We use the same data file and DataFileTableModel as the previous How−to. protected DataFileTableModel model./javadetails/java−0214.exit(0). } } 14. consider making a small donation to show your support for this Web site and its content..win.setColumnSelectionAllowed(false). java.setRowSelectionAllowed(false).setVisible(false). aTable.setCellSelectionEnabled(false).48 Read a data file into a JTable and reload if data file have changed Current version of this HowTo : http://www.

} } class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent e) { Window win = e. wd.repaint(). } } The DataFileWatchdog. public class DataFileWatchdog extends Observable implements ActionListener { 14. frame.47 Disable row selection in a JTable . java. table.createDefaultColumnsFromModel(). } public static void main(String s[]) { JFrame frame = new JFrame("Data File Table"). frame.getPreferredSize()).setSize(panel.addWindowListener(new WindowCloser()). 300). frame. then all registered Observers are notified about it. is simple.setVisible(true). // this watchdog (an Observable object) // is monitoring any file change wd = new DataFileWatchdog(dataFilePath). frame. add(scrollpane). java.addObserver(this).io. java.exit(0). frame.*.setVisible(false). System. Object arg) { // reload data because data file have changed model.setDefaultCloseOperation(JFrame. panel = new DataFileTable("customers. frame.lightGray).DO_NOTHING_ON_CLOSE). table. table = new JTable().getContentPane().java] import import import import javax. } public void update(Observable o.awt.setModel(model).*."Center").event.setForeground(Color. JScrollPane scrollpane = new JScrollPane(table).getWindow(). win. table. } public Dimension getPreferredSize(){ return new Dimension(400.model = new DataFileTableModel(dataFilePath). frame. an Observable object. If the timestamp is different then the last one.util.Timer.dat"). [DataFileWatchdog.add(panel.setBackground(Color.initVectors(). We use a Swing Timer to check every second if a given file have changed. DataFileTable panel.black).swing.*.

import javax.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.*. long actualLastModified = f. "Chung".event.start(). 14. new Integer(1)}./javadetails/java−0216..}}). setChanged().*. import javax.event.*.lastModified().html To hide one column (or more) in a JTable. {"Alan". lastModified = f.lastModified() . you must use the TableModel.Timer t = new Timer(1000. public class TableHideColumn implements ListSelectionListener { JTable tableView. } } } See also this related howto. To get back the hidden data. frame. } public void actionPerformed(ActionEvent e) { File f = new File(file). final Object[][] data = { {"Mark". public TableHideColumn() { JFrame frame = new JFrame("Table"). import java.rgagnon. // We specify only 2 column names. }. the last one is hidden final String[] names = {"First Name".49 Hide a column in JTable . new Integer(3)}. new Integer(2)}.this).com/javadetails/.java] import javax. // check every second long lastModified.awt. String file. import java. "Last Name" }.exit(0).awt. import java. 14.*. {"Tom".49 Hide a column in JTable Current version of this HowTo : http://www. if (lastModified != actualLastModified) { // the file have changed lastModified = actualLastModified.swing.*. "Andrews". File f = new File(file).swing.*.event. // original timestamp t. "Ball". notifyObservers().swing. DataFileWatchdog (String s) { file = s.awt. [TableHideColumn.table. don't give a column name.

} public String getColumnName(int column) {return names[column].println().codeguru. JScrollPane scrollpane = new JScrollPane(tableView).getContentPane().setPreferredSize(new Dimension(300.out.add(scrollpane).setSelectionMode(ListSelectionModel.getSelectedRows(). System. ListSelectionModel listMod = tableView. frame.getValueAt(selRows[0].out. scrollpane.getClass(). int column) { data[row][column] = aValue.length. 300)).length > 0) { for (int i= 0.experts−exchange.com/Programming/Programming_Languages/Java/Q_20394392. For a better way check out these links : http://www.html 14. i++) { // get Table data TableModel tm = tableView. value = tm. } System.com/java/articles/660.col). } } This technique is not the best one since a exception is generated when Swing tries to display an "hidden column". } } } public static void main(String[] args) { new TableHideColumn(). } }. i < 3 .length.} public Class getColumnClass(int col) { return getValueAt(0. if (!e.SINGLE_SELECTION).} public Object getValueAt(int row. listMod.TableModel dataModel = new AbstractTableModel() { public int getColumnCount() { return names.setVisible(true). int[] selRows.i). tableView = new JTable(dataModel). } public void valueChanged(ListSelectionEvent e) { int maxRows. Object value. int col) { return data[row][col].getModel(). } public int getRowCount() { return data. int row.shtml http://www.addListSelectionListener(this).print(value + " " ). } public void setValueAt(Object aValue. if (selRows. frame. listMod.49 Hide a column in JTable .pack(). frame.getSelectionModel().getValueIsAdjusting()) { selRows = tableView.

50 Scroll a JTable to the last row Current version of this HowTo : http://www. getModel(). true).51 Transfer a ResultSet to a JTable Current version of this HowTo : http://www. // tanks to umit ozkan for the bug fix! for(int i=0.rgagnon. 14. int column) { Rectangle rect = getCellRect(row.com/javadetails/. // jump to first row showCell(0.sql. column.com/javadetails/. clearSelection().i<colNo.next()){ Object[] objects = new Object[colNo]. showCell(rowcount."col 2". DefaultTableModel aModel = (DefaultTableModel) aTable.getObject(i+1). row).executeQuery("select col1.col2.i++){ objects[i]=rs. scrollRectToVisible(rect)./javadetails/java−0309..setModel(aModel).rgagnon.setColumnIdentifiers(tableColumnsName). // the query ResultSet rs = statement.ResultSetMetaData rsmd = rs.50 Scroll a JTable to the last row . Written and compiled by Réal Gagnon ©1998−2005 [ home ] 14. while(rs.col3 from mytable"). aModel. consider making a small donation to show your support for this Web site and its content.fireTableDataChanged().14. // notify the model } If you find this article useful. setRowSelectionInterval(row. public void showCell(int row.getMetaData(). } aTable.html // in the your JTable // jump to last row rowCount = table.getColumnCount()./javadetails/java−0291. } aModel..getRowCount () − 1."col 3"}. // Loop through the ResultSet and transfer in the Model java.getModel().addRow(objects). 0). int colNo = rsmd.html // TableModel definition String[] tableColumnsName = {"col 1". 0).

.out.event.VK_ENTER) { System. 14.rgagnon./javadetails/java−0201.setHorizontalScrollBar(new JScrollBar()).length > 1) return. myTable.awt.html import javax. me.52 Have on a JScrollPane/JTable an horizontal JScrollbar .com/javadetails/./javadetails/java−0397.html JScrollPane myScrollPane.getClickCount() == 2) { System. myTable = new Jtable(x.. if (ob. if (ob.out.println("Sending ACTION_PERFORMED to ActionListener"). addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { if (al == null) return.actionPerformed(new ActionEvent(this. JTable myTable.com/javadetails/.14. public ActionJList(String[] it){ super(it). ActionEvent.actionPerformed(new ActionEvent(this. myScrollPane. addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent ke) { if (al == null) return.53 Make a JList select an item on doubleclick or the ENTER key Current version of this HowTo : http://www. Object ob[] = getSelectedValues().toString())). public class ActionJList extends JList { /* ** sends ACTION_PERFORMED event for double−click ** and ENTER key */ ActionListener al. ob[0].setAutoResizeMode (JTable. if (me. myScrollPane = new JScrollPane(myTable).*. al.*.setAutoResizeMode (JTable.y). ActionEvent.AUTO_RESIZE_OFF). import java. 14.println("Sending ACTION_PERFORMED to ActionListener").consume().52 Have on a JScrollPane/JTable an horizontal JScrollbar Current version of this HowTo : http://www.swing. al. Object ob[] = getSelectedValues(). myTable.length > 1) return.ACTION_PERFORMED. } } }).ACTION_PERFORMED. if (ke.getKeyCode() == KeyEvent.rgagnon.AUTO_RESIZE_OFF).

import java. "item 8" .54 Make a JList like a scrolling text display . "item 6". } } class PanelWithActionJList extends JPanel { public PanelWithActionJList() { setLayout(new GridLayout(1.ob[0].*. "item 4". ajl. "item 3" . "item 2". ajl.toString())).add(new PanelWithActionJList()). import java. ke. } }). "item 5".swing.*.swing. String[] items = { "item 0".setVisibleRowCount(5).com/javadetails/. } public void addActionListener(ActionListener al){ this.getViewport().54 Make a JList like a scrolling text display Current version of this HowTo : http://www. public class TestActionJList { public static void main(String args[]) { JFrame jf = new JFrame(). } } 14.pack().consume(). add(jsp).getSelectedValue()). final ActionJList ajl = new ActionJList(items).event.getContentPane().*. jf.println("action in Panel " + ajl.setVisible(true). "item 1".html import javax. jsp. jf.setSelectedIndex(0). "item 9" }. 14. JScrollPane jsp = new JScrollPane().*. "item 7".out. } } To try it: import javax.1)).rgagnon.awt.awt.add(ajl).. } } }). jf.al = al./javadetails/java−0202. this.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent ae) { System.

setDefaultCloseOperation(JFrame. add(new JScrollPane(list)).util. dlm.com/javadetails/.add(ex.swing.awt.mj. public MyJList() { setLayout(new BorderLayout()).setLayout(new FlowLayout()).getModel().mj.list. } }). import java.list.html This snippet uses these 2 images import javax. JListExample.mj. } } class MyJList extends JPanel { JList list.import java. } } 14. list = new JList().getContentPane(). frame.event. ex.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent ae) { DefaultListModel dlm = (DefaultListModel)JListExample. frame.DO_NOTHING_ON_CLOSE). button.util.list.list.*.*.55 Have images in a JList Current version of this HowTo : http://www.setVisible(true).setSize(300.ensureIndexIsVisible (JListExample.*.rgagnon. frame. frame. } public Dimension getPreferredSize() { return new Dimension(150.getSize() − 1). import java.currentTimeMillis())).*.add(button).55 Have images in a JList . import java.awt.*. 250). JFrame frame = new JFrame("JList Scrolling Display")..mj = new MyJList()./javadetails/java−0203. public static void main(String s[]) { JListExample ex = new JListExample().addElement ((Object) new Long(System.setModel (new DefaultListModel()).getContentPane(). JButton button = new JButton("Insert"). ex.mj. 14. frame.getContentPane().awt. public class JListExample extends JPanel { static MyJList mj. 300).mj). import java.getModel(). frame.*.

JListWithImages jlwi = new JListWithImages().boolean cellHasFocus) { Component component = (Component)value. javax.swing. vector. component.add(new JLabel("Another line for Gumby")).300). jp2.awt. java. } class CustomCellRenderer implements ListCellRenderer { public Component getListCellRendererComponent (JList list.setVisible(true).setBackground (isSelected ? Color. // first line JPanel jp1 = new JPanel().*.*. vector.setSize(300. The version below is showing each line left justified instead. frame.addElement(jp2). // second line JPanel jp2 = new JPanel(). panel.black : Color. jp1.gif"))).white : Color. JPanel panel = new JPanel().add(panel). frame. return component.setForeground(Color.getContentPane(). public class JListWithImages extends JList { public JListWithImages() { 14. jp1.gif"))).add(new JLabel(new ImageIcon("gumby2. panel.add(new JLabel(new ImageIcon("gumby. jlwi.util.add(new JLabel("A line for Gumby")).white). } public static void main(String[] args) { JFrame frame = new JFrame().*. jp2.setForeground (isSelected ? Color. panel. boolean isSelected.*.gif"))).black). } } } The above How−to use the default layout.addElement(jp1).add(jlwi). import import import import javax. so each line line in the JList are centered.setBackground(Color. jp2. Object value.white).add(new JLabel(new ImageIcon("gumby.border. jp1. component. java.public class JListWithImages extends JList { public JListWithImages() { setCellRenderer(new CustomCellRenderer()).add(new JLabel(new ImageIcon("gumby2.black).gif"))).55 Have images in a JList .swing. Vector vector = new Vector(). frame. int index.setListData(vector).

JListWithImages jlwi = new JListWithImages().awt.setListData(vector).white : Color. vector. } public static void main(String[] args) { JFrame frame = new JFrame().*.event.gif"))). boolean isSelected. vector. } class CustomCellRenderer implements ListCellRenderer { public Component getListCellRendererComponent (JList list.swing.addElement(jp1).56 Add a row and clear a JList Current version of this HowTo : http://www.gif")))..add(new JLabel("Another line for Gumby")). panel.*.LEFT)).com/javadetails/.setVisible(true).add(new JLabel(new ImageIcon("gumby.add(new JLabel(new ImageIcon("gumby.add(jlwi).white).setBackground (isSelected ? Color. jlwi. public class ClearJList extends JPanel 14.black : Color. Object value.setCellRenderer(new CustomCellRenderer()).add(new JLabel(new ImageIcon("gumby2.gif"))). frame. java.addElement(jp2).white). jp2.setSize(300.add(new JLabel(new ImageIcon("gumby2. jp2.rgagnon.black). component.gif"))). component.awt.add(panel). jp1.300). frame. return component.add(new JLabel("A line for Gumby")). // second line JPanel jp2 = new JPanel(new FlowLayout(FlowLayout.getContentPane().html import import import import javax.*.setBorder(new LineBorder(Color./javadetails/java−0217. // first line JPanel jp1 = new JPanel(new FlowLayout(FlowLayout.56 Add a row and clear a JList .setForeground (isSelected ? Color.boolean cellHasFocus) { Component component = (Component)value.setForeground(Color.setBackground(Color.black).LEFT)). java.*. jlwi. int index.black)). frame. Vector vector = new Vector(). JPanel panel = new JPanel().util. panel. java. jp1. } } } // NEW // NEW 14. jp2. panel. jp1.

addActionListener(this).addElement ((Object) Integer. } public void actionPerformed(ActionEvent ae) { if (ae.setModel(new DefaultListModel()). } public Dimension getPreferredSize(){ return new Dimension(50. } } 14.*.awt.getContentPane(). frame. int i = 1. public class SortJList extends JPanel implements ActionListener{ 14. list = new JList().event. add(jb2 = new JButton("Clear"). jb1. public ClearJList(){ Vector data. // import java.addActionListener(this). import java."Center").rgagnon.*. jb2.getSource() == jb1) { // add DefaultListModel dlm = (DefaultListModel) list. ClearJList panel = new ClearJList().setModel(new DefaultListModel()). frame.Collator. add(jb1 = new JButton("Add").text.setVisible(true).util.. dlm.getModel().*."Center"). "West")./javadetails/java−0218.*.57 Sort a JList . jb2. setLayout(new BorderLayout()).DO_NOTHING_ON_CLOSE).toString(i++)).200).com/javadetails/. "East").setSize(200. JList list.swing.add(panel. add(new JScrollPane(list). list. frame. import java.util. 50).57 Sort a JList Current version of this HowTo : http://www.awt.Locale. import java. import java.html import javax.implements ActionListener{ JButton jb1. } } public static void main(String s[]) { JFrame frame = new JFrame("Clear JList").setDefaultCloseOperation(JFrame. frame. } else { // clear list.

length == 1) return.i++){ a[i] = (String)dlm. add(jb2 = new JButton("Sort").addElement ((Object) tf. int numItems = dlm.i++) { dlm. for (int i = 0.FRENCH.getInstance(). jb2.getSource() == jb1) { // add dlm = (DefaultListModel)list.setModel(new DefaultListModel()).a). (String[])a). "North"). add(tf = new JTextField(). JTextField tf. list. i++) { for (int j = i + 1. String[] a = new String[numItems].JButton jb1. add(jb1 = new JButton("Add"). } sortArray(Collator.getText()). add(new JScrollPane(list). setLayout(new BorderLayout()). if (strArray. // Locale loc = Locale. j++) { if( collator.getInstance(loc)."Center").i<numItems. strArray[j] ) > 0 ) { tmp = strArray[i].getModel(). i < strArray.compare(strArray[i].getElementAt(i). i).getModel(). strArray[j] = tmp. } } } } public static void main(String s[]) { JFrame frame = new JFrame("Sort JList"). } else { // sort dlm = (DefaultListModel) list. if (ae.i<numItems. "East"). int i = 1.length.setElementAt(a[i].57 Sort a JList . JList list.addActionListener(this). strArray[i] = strArray[j]. } public void actionPerformed(ActionEvent ae) { DefaultListModel dlm. jb1. jb2. // sortArray(Collator. 14. list = new JList(). for (int i=0. j < strArray.addActionListener(this). dlm. } } } public static void sortArray(Collator collator. public SortJList(){ Vector data. String[] strArray) { String tmp. for (int i=0. 50).getSize(). "West").length. } public Dimension getPreferredSize(){ return new Dimension(50.

ListModel dlm = list.getPoint()).setSize(panel.. add(new JScrollPane(list)).awt.*."Center").event. 14.*.addElement("line 3").SortJList panel = new SortJList()..rgagnon.getClickCount() == 2){ int index = list..58 Double click on a JList . list.getModel().*. public ActionJList(JList l){ list = l.util.setVisible(true). list.DO_NOTHING_ON_CLOSE). Object item = dlm.com/javadetails/.getElementAt(index).addElement("line 1").getPreferredSize()). java. public class DClickJList extends JPanel { public DClickJList() { JList list = new JList(). } public static void main(String s[]){ JFrame frame = new JFrame("DClickJList").add(panel.. frame.setVisible(true).getContentPane(). data.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE).swing. data. DClickJList panel = new DClickJList(). } public Dimension getPreferredSize() { return new Dimension(100.locationToIndex(e. frame.200). } public void mouseClicked(MouseEvent e){ if(e. 100). frame. java.setListData(data).setSize(200.setDefaultCloseOperation(JFrame. frame. } } class ActionJList extends MouseAdapter{ protected JList list.ensureIndexIsVisible(index).addElement("line 2"). frame. java.58 Double click on a JList Current version of this HowTo : http://www.setSelectedIndex(0).*."Center").add(panel. Vector data = new Vector().addMouseListener(new ActionJList(list)). list.html import import import import javax./javadetails/java−0219. frame. list.awt. data.getContentPane(). frame. frame. } } 14.

println("Double clicked on " + item). setLayout(new BorderLayout()).getY()).setModel(new DefaultListModel()).Separator()). int i = 1.addActionListener(this). public class PopUpJList extends JPanel implements ActionListener{ JButton jb1.addActionListener(this).rgagnon. popupMenu = new JPopupMenu().out.addActionListener(this). me.*. list = new JList().*. java.isPopupTrigger()) if (SwingUtilities. } public Dimension getPreferredSize(){ return new Dimension(50.swing.isSelectionEmpty() &list./javadetails/java−0393. java.59 Have a PopUp on a JList . list.addActionListener(this). public PopUpJList(){ Vector data. add(jb2 = new JButton("Clear"). me. jmi2.add(jmi2 = new JMenuItem("Clear")).System. JMenuItem jmi1.*. "West"). popupMenu.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { // if right mouse button clicked (or me. jmi2. JList list.awt.awt."Center").*. } } } ).getX(). 50). jmi1. popupMenu. JPopupMenu popupMenu. "East").add(jmi1= new JMenuItem("Add")).show(list. popupMenu.com/javadetails/.getSelectedIndex()) { popupMenu. add(new JScrollPane(list). jb2.isRightMouseButton(me) &!list.59 Have a PopUp on a JList Current version of this HowTo : http://www.add(new JPopupMenu.locationToIndex(me. jb1.util. add(jb1 = new JButton("Add").. java.getPoint()) == list.html import import import import javax. } } } 14. list.event. 14. jb2.

rgagnon.com/javadetails/. dlm.awt. } } 14.*. frame.html To the top myJTextArea.getSource() == jb1 || ae. frame.toString(i++)). import javax. If you find this article useful.getSource() == jmi1) { // add DefaultListModel dlm = (DefaultListModel) list.swing.setVisible(true). public class SelectableJLabel extends JPanel { 14.*.."Center").60 Set the cursor position in a JTextArea .add(panel.61 Make a JLabel selectable with the mouse Current version of this HowTo : http://www. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 14. import java.setCaretPosition(myJTextArea.60 Set the cursor position in a JTextArea Current version of this HowTo : http://www. PopUpJList panel = new PopUpJList(). } else { // clear list.setCaretPosition(0).setDefaultCloseOperation(JFrame./javadetails/java−0296.getLength()).rgagnon.html Simulate the "look and feel" of a JLabel with a JTextfield.getDocument(). To the end myJTextArea.getContentPane().com/javadetails/. } } public static void main(String s[]) { JFrame frame = new JFrame("PopUp JList").getModel(). frame./javadetails/java−0332.addElement ((Object) Integer..setModel(new DefaultListModel()).setSize(200. frame. consider making a small donation to show your support for this Web site and its content.200).} public void actionPerformed(ActionEvent ae) { if (ae.DO_NOTHING_ON_CLOSE).

frame.com/javadetails/.getPreferredSize()).getStyle() ^ Font.foreground")).deriveFont(f.DO_NOTHING_ON_CLOSE).public SelectableJLabel() { // a regular JLabel add(new JLabel("You can't select me")).deriveFont(f. f.setBorder(null).setEditable(false).BOLD))./javadetails/java−0304. f./javadetails/java−0349. add(f). // bold label.63 Bold / Unbold a JLabel Current version of this HowTo : http://www.html Font f = label.setForeground(UIManager. 100). } } 14.getFont("Label.setDefaultCloseOperation(JFrame..setFont(f. // unbold label.setBackround(myColor) 14.setVisible(true).getColor("Label. f.html The JLabel background is transparent by default.getContentPane().com/javadetails/. f. 14.getFont().rgagnon.setOpaque(true). } public static void main(String s[]){ JFrame frame = new JFrame("SelectableJLabel").add(panel."Center"). so changing the background color doesn't seem to do anything. frame.setFont(UIManager. } public Dimension getPreferredSize() { return new Dimension(100.BOLD)).getStyle() | Font.font")). frame.rgagnon.setFont(f. frame. SelectableJLabel panel = new SelectableJLabel().setSize(panel.. // a look−alike JLabel JTextField f = new JTextField("You can select me").62 Change JLabel background color . aJLabel.62 Change JLabel background color Current version of this HowTo : http://www. Do something like this : aJLabel.

setLayout(new FlowLayout()).com/javadetails/.*. But don't be to fancy since the HTML support is minimal.swing..2) implements simple HTML rendering for its components. import java.*./javadetails/java−0326. JLabel lbl = new JLabel(htmlText).1 (or better) offers the possibility to use HTML tag to format the JLabel's text.event. 14.awt.rgagnon. 300)./javadetails/java−0315.exit(0).com/javadetails/.14.rgagnon. setVisible(true). String htmlText = "<html><p><font color=\"#800080\" "+ "size=\"4\" face=\"Verdana\">HTML in JLabel</font></p>"+ "<font size=\"2\"><u>"+ "underline is possible</u><br><b> and bold too</b></font>"+ "". addWindowListener(wndCloser).html Since Swing (JDK1. getContentPane(). JLabel longLabel = new JLabel(). HTML tags must be in lowercase and simple. WindowListener wndCloser = new WindowAdapter(){ public void windowClosing(WindowEvent e) { System.*. it's possible to display underlined string (on JLabel or JButton for example).html Swing 1. } public static void main(String args[]){ new UnderlineInSwing(). longLabel.setText("<html><body>This is a <p><b>" + "<font size=\"+2\">a label on</font>" + "</b><p>three lines.64 Multi−line JLabel ..64 Multi−line JLabel Current version of this HowTo : http://www. getContentPane().65 Underline a string Current version of this HowTo : http://www. } } 14.1.add(lbl). public class UnderlineInSwing extends JFrame { public UnderlineInSwing() { super("Underline In Swing"). setSize(400. import java. } }.awt.</body></html>"). import javax.

com/javadetails/..setText("Real's HowTo").*. 14.. 14. java.setLayout(new FlowLayout()). javax. public class TooltipInSwing extends JFrame { public TooltipInSwing() { super("TooltipInSwing").66 Update a JLabel Current version of this HowTo : http://www. new ColorUIResource(.2) implements simple HTML rendering for its components.69 Change a JTooltip font Current version of this HowTo : http://www. 14. SwingUtilities.67 Have Multi−line string in a JToolTip Current version of this HowTo : http://www.rgagnon.rgagnon. myComponent.swing.*.setToolTipText ("<html><p>This ToolTip is</p><p>two lines</p></html>")..html UIManager. getContentPane(). Here a list of the resource names and their default values. 300).68 Change Tooltip color Current version of this HowTo : http://www./javadetails/java−0365.swing.html myLabel.awt.G=204..com/javadetails/./javadetails/java−0529.html import import import import javax./javadetails/java−0337. The same feature is true for JToolTip.updateComponentTreeUI(myLabel). 14.rgagnon.B=255] NOTE:Most Swing resources can be customize this way.com/javadetails/. it's possible to display underlined string (on JLabel or JButton for example).*./javadetails/java−0392.com/javadetails/.14.)).*.swing. The default value is javax.rgagnon.ColorUIResource[R=204.put("Tooltip..background".66 Update a JLabel .awt.event. setSize(400..html We saw that since Swing (JDK1.plaf.plaf. java.

300). setSize(400. new FontUIResource("SansSerif". consider making a small donation to show your support for this Web site and its content.add(b1). public class TooltipInSwing extends JFrame { public TooltipInSwing() { super("TooltipInSwing").*.// globally UIManager. import java. // only one String html = "<html><p><font color=\"#800080\" " + "size=\"4\" face=\"Verdana\">tool tip verdana" + "</font></p></html>". 18)).setToolTipText(html). setVisible(true). } } If you find this article useful.exit(0). import java. Written and compiled by Réal Gagnon ©1998−2006 [ home ] 14. } }.setDismissDelay(Integer.font". b2.70 Keep a JTooltip visible Current version of this HowTo : http://www.setToolTipText("tool tip sansserif bold").MAX_VALUE). JButton b1 = new JButton("tooltip 1").awt. getContentPane().BOLD. default is 4 sec. getContentPane().70 Keep a JTooltip visible . WindowListener wndCloser = new WindowAdapter(){ public void windowClosing(WindowEvent e) { System. getContentPane().add(b2). Font..awt.sharedInstance().*. ToolTipManager.put("ToolTip.add(b1).com/javadetails/. 14.swing.rgagnon.*. b1. // set a new dismiss delay to a really big value.setLayout(new FlowLayout()). JButton b1 = new JButton("Simple tooltip 1").html import javax.event. getContentPane(). } public static void main(String args[]){ new TooltipInSwing(). b1. JButton b2 = new JButton("tooltip 2").setToolTipText("simple tool tip without a dismiss delay")./javadetails/java−0528. addWindowListener(wndCloser).

setVisible(true). icon. File file = new File(s). } } output : Second technique import java.awt. frame..*. System.shell.add(ficon).71 Display icon associated with an executable Current version of this HowTo : http://www./javadetails/java−0439.ShellFolder.getContentPane(). // show the icon JLabel ficon = new JLabel(s.*.LEFT).awt.ShellFolder sf = sun.rgagnon. } }. // Get metadata and create an icon sun.71 Display icon associated with an executable .pack().getFolderType()). frame.println("type = " + sf. 14. JFrame frame = new JFrame(). public class IconExtract1 { public static void main(String[] args) throws Exception { String s = "c:/windows/regedit. SwingConstants.getIcon(true)). frame. Written and compiled by Réal Gagnon ©1998−2006 [ home ] 14. } } If you find this article useful.exe". consider making a small donation to show your support for this Web site and its content.com/javadetails/.exit(0).swing.*.io.out.getShellFolder(file).shell.io. } public static void main(String args[]){ new TooltipInSwing(). Icon icon = new ImageIcon(sf.WindowListener wndCloser = new WindowAdapter(){ public void windowClosing(WindowEvent e) { System.html First technique import java. setVisible(true). import javax. addWindowListener(wndCloser).

setVisible(true).*. import java. public class IconExtract2 { public static void main(String[] args) throws Exception { String s = "c:/windows/regedit. // Get metadata and create an icon Icon icon = FileSystemView.filechooser. Icon icon = chooser. JFrame frame = new JFrame().getContentPane(). icon. frame.exe".*. SwingConstants. SwingConstants. import import import import java.filechooser. } } output: If you need more generic image.LEFT).71 Display icon associated with an executable .pack(). you use a JFileChooser and extract the image for a file or directory.getSystemIcon(file). javax.*. frame. frame.getContentPane().add(ficon).setVisible(true). frame. File file = new File(s).awt.getFileSystemView().awt. JFrame frame = new JFrame(). frame.pack().getIcon(file). } } output for a directory : output for a file : 14.LEFT).swing.import javax.swing.*.*.io. frame.FileSystemView.swing.add(ficon). javax. File file = new File(s). public class IconExtract3 { public static void main(String[] args) throws Exception { String s = "c:/windows/regedit.exe". icon. java.*. JFileChooser chooser = new JFileChooser(). // show the icon JLabel ficon = new JLabel(s. import javax. // show the icon JLabel ficon = new JLabel(s.swing.

// Create a menu JMenu menu = new JMenu("Menu Label"). } public void doit() { JFrame frame = new JFrame("Real's HowTo"). } }.add(item).swing.72 Have items in JMenubar at rightmost position .add(Box. // shift to the right menuBar.setSize(300.add(new JButton(actionQuit)). Adding such a glue component to the menubar will cause remaining menus/components to 'flow' to the right. } } 14.awt.. menu.72 Have items in JMenubar at rightmost position Current version of this HowTo : http://www.setJMenuBar(menuBar). frame. frame.setVisible(true).rgagnon. frame.createGlue()). Written and compiled by Réal Gagnon ©1998−2007 [ home ] 14. consider making a small donation to show your support for this Web site and its content. import javax.add(menu).*. menuBar. JMenuBar menuBar = new JMenuBar().createGlue() will create a "greedy" component: when it is added to a container it takes all remaining horizontal and vertical space.event.html javax.exit(0).If you find this article useful. import java.*. class RightJMenuBar { public static void main(String args[]) { new RightJMenuBar().com/javadetails/. menuBar./javadetails/java−0486.doit(). // this button will be shifted right on the menubar Action actionQuit = new AbstractAction("Quit") { public void actionPerformed(ActionEvent evt) { System. JMenuItem item = new JMenuItem("item").Box.swing.300).

gif"))). add(b3).setVerticalTextPosition(SwingConstants. b3.*. new ImageIcon (new URL("http://www. // text on the center b2 = new JButton("Special".setHorizontalTextPosition(SwingConstants.rgagnon.swing.com/images/gumby. b2. b2. b3.printStackTrace(). new ImageIcon (new URL("http://www.net. add(b1). // text on the top b3 = new JButton("Special".com/javadetails/.*. } } } How it looks : Written and compiled Réal Gagnon ©2007 real@rgagnon.com/images/gumby. public void init() { setLayout(new FlowLayout()).rgagnon.com http://www. new ImageIcon (new URL("http://www.If you find this article useful.*.rgagnon. import javax.gif"))). import java.CENTER).rgagnon.TOP).awt.setHorizontalTextPosition(SwingConstants. } catch (Exception e) { e.rgagnon.com/images/gumby.com 14. public class TestJButton extends JApplet { JButton b1. try { b1 = new JButton("Regular".CENTER). consider making a small donation to show your support for this Web site and its content. add(b2).73 Have an JButton with an Image Current version of this HowTo : http://www.73 Have an JButton with an Image . Written and compiled by Réal Gagnon ©1998−2005 [ home ] 14.html import java. b3./javadetails/java−0548.gif")))..

14.73 Have an JButton with an Image .

public ConsumeData(InputStream is) { this.java] import java.rgagnon. public abstract class ProduceData implements Runnable { OutputStream os.start().2 Pipe the output of a thread to the input of another one Current version of this HowTo : http://www. Pipeline Thread +−−−−−−−−−−+ | thread A | +−−−−−−−−−−+ (PRODUCE) +−−−−−−−−−−+ | thread B | +−−−−−−−−−−+ (CONSUME) −−− > [ProduceData.*..html We use the PipedOutputStream/PipedInputStream duo. } public abstract boolean dataConsumption().1 java−thread 15. public ProduceData(OutputStream os) { this.os = os.15 Thread 15. t./javadetails/java−0140. } } [ConsumeData. } public abstract boolean dataProduction(). Thread t = new Thread(this). Thread t = new Thread(this). public void run() { while(dataProduction()) .*.com/javadetails/.is = is. public abstract class ConsumeData implements Runnable { InputStream is. t. 15 Thread . When these streams are connected together what is written in the PipedOutputStream can be read in PipedInputStream. That connection acts like a queue (FIFO).io.start().io.java] import java.

out. } } return done. } public boolean dataProduction() { byte[] j = new byte[1]. try { for (. System. } public boolean dataConsumption() { int i = 0.public void run(){ while(dataConsumption()).java] import java. this.printStackTrace().output = os. [SendProduction.input = is.util. SendProduction(OutputStream os) { super(os).read().Random(). while(!done) { try { j[0] = (byte)(Math. java. System.Random r = new java.*. } } We implement the method to receive and process the data.java] import java.util. this. } catch (Exception e) { e.println(" " + i).print(".nextInt()) % 255).io..out.abs(r. return true.write(j).*. boolean done = false. } } Next we implement the methods to prepare/send the data.").io. } } 15 Thread . [ReceiveProduction. public class ReceiveProduction extends ConsumeData { InputStream input. output. ReceiveProduction(InputStream is) { super(is).) { i = input. public class SendProduction extends ProduceData { OutputStream output.

AtomicInputStream(int atom) { super().. new ReceiveProduction(is).io.catch (Exception e) { e./javadetails/java−0141.printStackTrace().io.*.atom = atom.*.html The idea is to make the READ operation ATOMIC.java] import java. } return true. } catch (Exception e) {} } } 15.java] import java.rgagnon. os.3 Pipe the output of a thread to the input of other threads Current version of this HowTo : http://www. } 15. } } [TestThread. Once the READING is started for one thread.class are the same as the previous JAVA How−to. PipedInputStream is = new PipedInputStream().connect(is). it cannot be interrupted by another one. Pipeline Thread +−−−−−−−−−−+ | thread A | +−−−−−−−−−−+ (produce) +−−−−−−−−−−+ −−−− > | thread B | | +−−−−−−−−−−+ | (consume) | | | +−−−−−−−−−−+ +− > | thread C | +−−−−−−−−−−+ (CONSUME) The ProduceData. new SendProduction(os). [AtomicInputStream.3 Pipe the output of a thread to the input of other threads . public class TestThread { public static void main(String a[]){ try { PipedOutputStream os = new PipedOutputStream().class and ConsumeData. this.com/javadetails/. public class AtomicInputStream extends PipedInputStream { int atom = 0.

0. public class SendProduction extends ProduceData { OutputStream os. 0. return −1. this.printStackTrace().as = as.public synchronized int atomicRead(byte[] x) try { read(x. this.os = os.out. System.io.println (Thread. atom).3 Pipe the output of a thread to the input of other threads .*..*. try { for (. } return atom. j[0] = 0 .read(i). ReceiveProduction(AtomicInputStream as) { super(as).currentThread(). } } return done. } } { [SendProduction. 15. } public boolean dataProduction() { byte[] j = new byte[3]. public class ReceiveProduction extends ConsumeData { AtomicInputStream as. j[2] = 2.getName()+": " + i[0] + " " + i[1] + " " + i[2]). } catch (Exception e) { e.io. SendProduction(OutputStream os) { super(os). } catch (Exception e) { e. } } [ReceiveProduction. } public boolean dataConsumption() { byte [] i = new byte[3]. 3). while(!done) { try { os. return true. boolean done = false.printStackTrace().write(j. j[1] = 1.java] import java.java] import java.) { as.

new ReceiveProduction(as). j < i.currentThread().io.connect(as). simply create a AtomicOutputStream class with a synchronized atomicWrite method in it. } 15. See this HowTo.getName() + " " + j)./javadetails/java−0142. To support many producers.4 Wait the for the completion of a thread .com/javadetails/. new ReceiveProduction(as). } catch (Exception e) { e.getName() + " FINISHED").println (Thread.} } catch (Exception e) { e. Using a PipedOutputStream is complicated.out.. AtomicInputStream as = new AtomicInputStream(3). a simpler solution is to use Queue (especially with Java 5).printStackTrace(). A producer sends data to the Queue and the the consumers extract the data.html public class testThread implements Runnable { int i.rgagnon. this.out. j++) { System. } System. os. } } } That's OK for the situation One Producer and Many consumers.i = i. 15.currentThread().printStackTrace().4 Wait the for the completion of a thread Current version of this HowTo : http://www. public class TestThread { public static void main(String a[]){ try { PipedOutputStream os = new PipedOutputStream(). new SendProduction(os). } public void run() { for (int j=0.java] import java. testThread(int i) { super().println (Thread. } return true.*. } } [TestThread. new ReceiveProduction(as).

"Test thread 1"). if (!checkState()) break.5 Control a thread from outside Current version of this HowTo : http://www. static final int STOP = 2./javadetails/java−0143. t1. if (s == RUN) notify(). t2. Thread t1 = new Thread(tt1. } catch (Exception e) { e.join().join(). private int state = RUN.public static void main(String a[]) { try { testThread tt1 = new testThread(50). System. } private boolean boolean checkState() { while (state == SUSPEND) { try { wait().printStackTrace(). } } } 15. return true. testThread tt2 = new testThread(75).out.html public class TT extends Thread { static final int RUN = 0.rgagnon.com/javadetails/. } } 15.start(). static final int SUSPEND = 1.println("Main FINISHED").. Thread t2 = new Thread(tt2. t1."Test thread 2"). } catch (Exception e) {} } if (state == STOP) return false.5 Control a thread from outside . t2. public synchronized void setState(int s) { state = s. } public void run() { while true { doSomething().start().

awt.6 Create a Timer object .util.swing./javadetails/java−0144. //Terminate the thread } } public static void main ( String args [ ] ) { System.Frame dummy = new java. TimerDemo() { t. dummy.*.cancel ( ) .start(). { public ToDo ( int seconds ) { timer = new Timer ( ) .util.out. } public void actionPerformed(ActionEvent e) { if (e. } } Swing also provide a Timer class. import java." ) .println ("\007Being ticked " + Calendar. public class ToDo Timer timer.com/javadetails/. new ToDo ( 5 ) .schedule ( new ToDoTask ( } ) .println ( "Waiting.out.util.out.awt. public class TimerDemo implements ActionListener { Timer t = new Timer(1000.util.Frame(). 15. // create a dummy frame to keep the JVM running // (for demonstation purpose) java.6 Create a Timer object Current version of this HowTo : http://www. import java.html JDK 1. It's time to do something!" ) . } public static void main(String args[]) { TimerDemo td = new TimerDemo().TimerTask.3 (or better) provides new classes called java.event.getTime()).util. class ToDoTask extends TimerTask { public void run ( ) { System. A Timer object will send an ActionEvent to the registered ActionListener.getSource() == t) { System. import javax. import java. import java. timer.setVisible(true). seconds*1000 ) .Timer.getInstance().*.TimerTask.println ( "Schedule something to do in 5 seconds.awt.Timer. System." ) .15.out.rgagnon.this).Timer and java.println ( "OK.. timer.

com/javadetails/. which extends the Thread class. } catch (InterruptedException e) { e.out.*.html public class Wait { public static void oneSec() { try { Thread. DelayedMethod dm.com/javadetails/.7 Pause the execution .printStackTrace(). } catch (InterruptedException e) { e.rgagnon. java.*.7 Pause the execution Current version of this HowTo : http://www.println("Wait one second"). } } public static void manySec(long s) { try { Thread. This Thread will receive a pointer to the "parent class" in its constructor.oneSec().println("Done").sleep(1000). } } 15.out.sleep(s * 1000). Wait.html In the following example.currentThread(). b2.println("Done\nWait five seconds"). 15. import import import import java.awt. } } } public class TestWait { public static void main(String args[]) { System.applet.*./javadetails/java−0146.awt.rgagnon.manySec(5).out.} } } 15. java. DelayedMethod.. java. we are using a special class.event.*.net. public class AnnoyingPopUps extends Applet implements ActionListener { Button b1. System./javadetails/java−0145.printStackTrace().currentThread().8 Execute a method at a specified time interval Current version of this HowTo : http://www.. This pointer will be used to call a know method at a specified interval. Wait. System.

// customize this too! } catch (InterruptedException ignored) {} 15. int delay) { this.int x = 0. public void init() { b1 = new Button("Start Annoying Popops"). 1000). d.delay = delay.getWindow().dispose().b2.addActionListener(this).addActionListener(this). this.show().delay = 2000. } class SimplePopUp extends Dialog { SimplePopUp() { super(new Frame(). } public void actionPerformed(ActionEvent ae) { if (ae. } DelayedMethod(AnnoyingPopUps myObj. add(b2). x). } } class DelayedMethod extends Thread { AnnoyingPopUps myObj = null.7 Pause the execution . } else if(ae.oktorun = false.myObj = myObj. d. } public void run() { while (true) { try { sleep(delay). this. b1.setLocation(x . add(b1). // customize for your need boolean oktorun = false. } } ).addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { e. this. b2 = new Button("Stop Annoying Popops"). }s } public void displayPopup() { SimplePopUp d = new SimplePopUp(). DelayedMethod(AnnoyingPopUps myObj) { this.getSource() == b2) { dm.myObj = myObj.start(). if (oktorun) myObj.oktorun = true.displayPopup(). int delay. "annoying popup"). dm = new DelayedMethod(this. x = x + 5. // 1 second dm.getSource() == b1) { dm.

com/javadetails/. // start right now and after every 5 sec. 1.Timer and java.").out. stpe./javadetails/java−0595. SimpleTask02 st02 = new SimpleTask02().TimeUnit.util.html JDK1.scheduleAtFixedRate(st02.println(current−−).concurrent. 2.5 provides a mechanism to create a pool a scheduled task (java.util. public class DemoScheduledTask { public static void main(String args[]) { // pool size == 5 ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(5).println("Real's HowTo").util. 5. JDK1.concurrent. } } } } 15. public void run() { if (current > 0) { System.TimerTask).util. import java.9 Execute a process at regular interval Current version of this HowTo : http://www.} } } } Want to Try it? NOTE: Check this How−to to achieve to same goal by using the Timer object. SimpleTask01 st01 = new SimpleTask01(). stpe.ScheduledThreadPoolExecutor (javadoc)). TimeUnit.out..out.scheduleAtFixedRate(st01. 15. } } class SimpleTask02 implements Runnable { int current = 10. TimeUnit. import java.SECONDS).3 introduces a way to execute a process at regular interval (java.ScheduledThreadPoolExecutor.concurrent.SECONDS). if (current == 0) { System. } } class SimpleTask01 implements Runnable { public void run() { System.println("end. 0. // start in 1 sec and after every 2 sec.util.rgagnon.9 Execute a process at regular interval .

ConcurrentModificationException at java. public static void main(String[] args) throws Exception { new Producer().com/javadetails/.addElement(new Object()). java.start().15.sleep(1).){ try { Thread.printStackTrace()./javadetails/java−0373.AbstractList$Itr..iterator().){ try { Thread. while (it.hasNext()) it.size() > 1000) data. public class RW { private static Vector data = new Vector(). } public void run(){ for(.*. } static class Consumer extends Thread { Consumer(){ super("Consumer").10 Handle concurrent read/write Current version of this HowTo : http://www.start().checkForComodification(Unknown Source) at java. if (data.10 Handle concurrent read/write .util. } public void run(){ for(.AbstractList$Itr. } } } } The following Exception is generated very quickly because the Producer is trying to modify the data (a Vector) while the Consumer is using it.rgagnon.next().sleep(1).util. } catch (Exception e){ e. } data. } Iterator it = data..util. } } } static class Producer extends Thread { Producer(){ super("Producer"). } catch (Exception e){ e.removeAllElements().printStackTrace(). new Consumer().next(Unknown Source) 15..html Take the following program import java.util.

import java.){ try { Thread..11 Communicate between threads using a Queue .next().11 Communicate between threads using a Queue Current version of this HowTo : http://www.addElement(new Object()). } public void run(){ for(. } public void run(){ for(.){ try { Thread. } } } } static class Producer extends Thread { Producer(){ super("Producer").java:26) The solution is to use the keyword synchronized to put a lock on the data while we are using it..*./javadetails/java−0555. new Consumer().at RW$Consumer. } synchronized(data){ Iterator it = data.. } catch (Exception e){ e.rgagnon.iterator(). } } } } 15.sleep(1). public class RW { private static Vector data = new Vector().util.hasNext()) it. while (it.sleep(1).size() > 1000) data. } static class Consumer extends Thread { Consumer(){ super("Consumer").removeAllElements(). } catch (Exception e){ e. public static void main(String[] args) throws Exception { new Producer().com/javadetails/.printStackTrace().start().run(RW. if (data.html 15. } data.printStackTrace().start().

import java.out. public class PrepareProduction implements Runnable{ private final BlockingQueue<String> queue. The java. A Producer opens a file and puts the data into BlockingQueue. public class DoProduction implements Runnable { private final BlockingQueue<String> queue. queue. input. import java.*. 15.put(thisLine). PrepareProduction(BlockingQueue<String> q) { queue = q.println ("Start " + Thread. queue.util.dat"). // special marker for the consumer threads // to mark the EOF queue.put("*"). If there is no data in the Queue.io.println("Start PrepareProduction"). BufferedReader input = new BufferedReader (new InputStreamReader(fin)). while ((thisLine = input. } catch (Exception e) { e. queue.BlockingQueue.11 Communicate between threads using a Queue .util. } public void run() { String thisLine. DoProduction(BlockingQueue<String> q) { queue = q.put("*"). the BlockingQueue will wait. } } } A Consumer extract a value from the Queue and execute an operation.out. System.util. mport java.put("*").getName()).put("*"). } fin.put("*"). try { FileInputStream fin = new FileInputStream("d:/input_data. queue.close().printStackTrace().currentThread(). } public void run() { try { System. queue.put("*"). queue.BlockingQueue is designed to work in a multi−threaded world.close().readLine()) != null) { queue. queue.put("*").put("*").concurrent. The end−of−data is marked by the presence of a special marker (the "*" in this example).Using BlockingQueue class A new class in Java 5 can be used to communicate data to many Consumer classes from a Producer class.concurrent. queue.concurrent.put("*").*.

join(). /* do something with value */ value = queue. DoProduction(q)).start().equals("*")) { //System. c2. DoProduction(q)).BlockingQueue. c6. DoProduction(q)).start()."). c5.start().join(). c4.join().join().join(). c6. c4. c9.start(). } } } A test class import java. c9. c7.take().11 Communicate between threads using a Queue .start().start(). DoProduction(q)).util.join().out. 15. while (!value.util. c3.currentThread(). c7.start(). c5. DoProduction(q)).concurrent. DoProduction(q)).join().join(). p1. public class Test { public static void main(String[] args) throws Exception { BlockingQueue<String> q = new LinkedBlockingQueue<String>().println // (Thread.println("Done. } } catch (Exception e) { System.LinkedBlockingQueue.join(). DoProduction(q)).start(). System.start(). c1.getName()+": " + value ). DoProduction(q)).println (Thread.out. c3.getMessage()). c2.getName() + " " + e.start().join(). Thread Thread Thread Thread Thread Thread Thread Thread Thread Thread p1 c1 c2 c3 c4 c5 c6 c7 c8 c9 = = = = = = = = = = new new new new new new new new new new Thread(new Thread(new Thread(new Thread(new Thread(new Thread(new Thread(new Thread(new Thread(new Thread(new PrepareProduction(q)). DoProduction(q)). c1. p1.concurrent. import java.take(). c8.currentThread().String value = queue. c8.out.

add(thisLine).add("*"). queue. import java. while ((thisLine = input.} } Using a LinkedList If you need don't need all the benefits of BlockingQueue then a simple LinkedList can be more appropriate. 15.*.add("*").add("*").add("*"). queue.out. // special marker for EOF queue.readLine()) != null) { queue. } public void run() { try { System. } } } The Consumer import java. Since you are in a multi−threaded world.dat").close().util.*. public class DoProduction implements Runnable { private final List<String> queue.util. queue. } catch (Exception e) { e. } fin. queue.close(). System. especially if you need to process large amount of data in a batch process.add("*"). queue.add("*"). } public void run() { String thisLine. DoProduction(List<String> q) { queue = q. PrepareProduction(List<String> q) { queue = q. Keep in mind that theses examples are minimal and need more error checking! First the Producer import java. it's safer to use the synchronized version of the LinkedList implementation.printStackTrace(). input.add("*").add("*").println("Start " + Thread. queue.io. public class PrepareProduction implements Runnable{ private final List<String> queue.11 Communicate between threads using a Queue . BufferedReader input = new BufferedReader (new InputStreamReader(fin)). queue.getName()).*. queue.println("Start PrepareProduction").out.add("*").currentThread(). try { FileInputStream fin = new FileInputStream("d:/input_data.

util. String value = queue.start().remove(0). c5. Thread Thread Thread Thread Thread Thread Thread Thread Thread Thread p1 c1 c2 c3 c4 c5 c6 c7 c8 c9 = = = = = = = = = = new new new new new new new new new new Thread(new Thread(new Thread(new Thread(new Thread(new Thread(new Thread(new Thread(new Thread(new Thread(new PrepareProduction(q)).start(). c4. c7. DoProduction(q)).out. c9.11 Communicate between threads using a Queue . } } } The test import java.start().start(). System. DoProduction(q)). c3. public class Test { public static void main(String[] args) throws Exception { List q = Collections.join().equals("*")) { System.start(). DoProduction(q)).out.start(). DoProduction(q)). } } catch (Exception e) { System. p1. p1.join(). c6.join().join().getName() +": " + value ). c4.println(Thread. c3. c6. DoProduction(q)). c8.getMessage()). c8.*.println("Done. c2.out. c2. c7.start().start(). DoProduction(q)).join(). c1.join().getName() + " " + e.start(). while (!value.synchronizedList (new LinkedList<String>()). DoProduction(q)). c1.currentThread().join(). } 15.join().currentThread().join().// you may need to wait for the first data available // with a BlockingQueue it's done for you. c5.remove(0). DoProduction(q)).start(). DoProduction(q)). /* do something with value */ value = queue.").println(Thread. c9.join().

com http://www.11 Communicate between threads using a Queue .rgagnon.com 15.} Written and compiled Réal Gagnon ©2007 real@rgagnon.

4.sun.2 Create a Taglet to document database access (Javadoc) Current version of this HowTo : http://www.address:city. employee and address.1 java−varia 16.util.javadoc..firstname.Map. } will be documented as 16.country * @return value */ public String newMethod() { return "yo".lastname.com/javadetails/.2.doclets.taglet.java */ city country package com.1 newMethod public java. /** * This is a taglet to document tables and fields used by a classes * example : @table employee:lastname. import com.String newMethod() Returns: value Table(s): firstname lastname The "table" taglet source /* * Table. then the javadoc tag /** *@table employee:firstname. it is possible to create a taglet to be used with javadoc to customized the generated documentation.rgagnon.address:city. import com.Taglet.lang./javadetails/java−0473.16 Varia 16.tools.*. import java.html Since JDK1. If a method interact with 2 tables. This example implements a new javadoc tag to document which tables a class is dealing with.sun.country * * @author Réal Gagnon 16 Varia .rgagnon.

* @return true since <code>@todo</code> * can be used in field documentation and false * otherwise.*/ public class Table implements Taglet{ private static final String NAME = "table". 16 Varia . } /** * Will return true since <code>@todo</code> * can be used in method documentation. } /** * Will return true since <code>@todo</code> * can be used in field documentation. private static final String HEADER = "Table(s):". * @return true since <code>@todo</code> * can be used in method documentation and false * otherwise. } /** * Will return true since <code>@todo</code> * can be used in method documentation. * @return true since <code>@todo</code> * can be used in constructor documentation and false * otherwise. * @return true since <code>@todo</code> * can be used in overview documentation and false * otherwise. */ public boolean inConstructor() { return true. */ public boolean inField() { return false. } /** * Will return true since <code>@todo</code> * can be used in constructor documentation. */ public boolean inMethod() { return true. */ public String getName() { return NAME. } /** * Will return true since <code>@todo</code> * can be used in package documentation. /** * Return the name of this custom tag. */ public boolean inOverview() { return true. * @return true since <code>@todo</code> * can be used in package documentation and false * otherwise.

for (int i=0.split(":").").remove(tag." + " border−width:thin\">" + current[0] + "</TH>". output += "<TH ALIGN=\"center\" STYLE=\"border−style:solid. } tagletMap. } /** * Will return false since <code>@todo</code> * is not an inline tag.getName(). } /** * Register this Taglet. return its string representation. if (current. * @param tagletMap the map to register this tag to.getName()). output += "<TD><TABLE style=\"border−style:solid.text(). */ public String toString(Tag tag) { String output = "".getName()). Taglet t = (Taglet) tagletMap. } /** * Given the <code>Tag</code> representation of this custom * tag. i++){ // deals with the current table and its fields String current[] = tables[i]." + " border−width:thin\">". String tables [] = tag. */ public boolean isInlineTag() { return false.*/ public boolean inPackage() { return true.get(tag. */ public boolean inType() { return true.length. i < j . * @return true since <code>@todo</code> * can be used in type documentation and false * otherwise. if (t != null) { tagletMap. * @return false since <code>@todo</code> * is not an inline tag.put(tag.length > 1) { 16 Varia . int j = tables. } /** * Will return true since <code>@todo</code> * can be used in type documentation (classes or interfaces). */ public static void register(Map tagletMap) { Table tag = new Table(). if (j > 0) { output = "<DT><B>" + HEADER + "</B><DD><TABLE><TR>". tag).split(". * @param tag the <code>Tag</code> representation of this custom tag.

rgagnon. } String result = "". n++) { output += "<TR><TD ALIGN=\"center\">" + fields[n] + "</TD></TR>". For example. */ public String toString(Tag[] tags) { if (tags. The required class files are in the lib\tools. Assuming the SDK is installed at C:\Program Files\j2sdk1. } } Compile your taglet.taglet. i < tags. } output += "</TR></TABLE>". This example calls javadoc on package com.class.3 Generate the Javadoc "en français" Current version of this HowTo : http://www.Table −tagletpath c:\dev\work\java\taglet com."). int k = fields.1 : javac −classpath "C:\Program Files\j2sdk1.java Run the javadoc tool using the −taglet and −tagletpath options./javadetails/java−0437.com/javadetails/. If you find this article useful. } return result . } return output.length.jar" com\rgagnon\taglet\Table. for (int n=0. return its string representation. then you should set tagletpath to C:\taglets.length. n < k . including Table taglet tags: C:\dev\Work\java\taglet>javadoc −taglet com.. Use javac compiler version 1.0 (or later) in the Java 2 SDK.jar file in the SDK.html 16. if your taglet class file is defined to be in package com.4.taglet and is stored in C:\taglets\com\rgagnon\taglet\Table. for (int i = 0.3 Generate the Javadoc "en français" .split(".4. } /** * Given an array of Tags representing this custom * tag. Written and compiled by Réal Gagnon ©1998−2005 [ home ] 16.rgagnon.package1 Download this taglet here.rgagnon. i++) { result += toString(tags[i]). * @param tags the array of Tags representing of this custom tag. } } output += "</TABLE>".String fields[] = current[1]. consider making a small donation to show your support for this Web site and its content.1\lib\tools.length == 0) { return null.4.package1.

doclet.</i>]]></bottom> </javadoc> 16.Since=Since\: doclet. The tools. 2003 Real's Howto.properties. NOTE : Make sure the −locale switch is the first one.Since=Depuis\: doclet. we need a file called standard_fr.standard.Generated_Docs_Untitled=Generated Documentation (Untitled) [standard_fr.Warn_inline_taglet=Inline tag {0} should only be used with a {1}.properties used by Javadoc to generated the labels..properties in com. [standard. Using Ant.Warn_inline_taglet=Inline tag {0} should only be used with a {1}.standard.properties (extract)] doclet.ClassUse_Subinterface=Sous−interfaces de {0} dans {1} doclet.tools.Packages=Paquetages doclet.properties.ClassUse_Subinterface=Subinterfaces of {0} in {1} doclet. Copy it under the name standard_fr. the standard.Generated_Docs_Untitled=Documentation g\u00E9n\u00E9r\u00E9e Once everything translated.jar making sure that the file is located in the right package (along standard.SerialData=Donn\u00E9e s\u00E9rialis\u00E9e\: doclet.properties (extract)] doclet.3 Generate the Javadoc "en français" .Window_Split_Index={0}\: {1}−Index doclet.. doclet.sun.The javadoc utili