Java Problems And Solutions

Testing if a file or directory exists
Use the following java code to solve this problem: /** *  Verifies if a file or directory exists. */ public static final boolean dirFileExists (String sPath) {  File fl = new File (sPath); return fl.exists; }

Application Path
To get the application path, try to get the first path of the classpath, like this:

public static final void readApplicationPath {   StringTokenizer classPath = new StringTokenizer (System.getProperty("java.class.path","."),";"); appPath = classPath.nextToken; }

Getting directories entries
You can use the following system properties to get some important directories that can be used in your application:

Syntax:

String myProperty = System.getProperty("java.class.path");


 * java.class.path 	:Java class path
 * java.home 	:Java installation directory
 * java.io.tmpdir 	:Default temp file path
 * java.library.path 	:List of paths to search when loading libraries
 * user.dir 	:User's current working directory
 * user.home	:User's home directory

System Properties
There are other properties that could be very helpful. Try to execute the following code and find out yourself: Properties teste = System.getProperties; Enumeration propNames = teste.propertyNames; while (propNames.hasMoreElements) {      String name = (String) propNames.nextElement; Konstant.print(name + " : " + teste.getProperty(name)); }

Problems with location and country configuration
Import the package: java.util.Locale

The following code sets the default locale for the actual instance of the Java Virtual Machine, but it does not affect the host locale. Ex: public static void setDefault(Locale newLocale) { Locale.setDefault (Locale.US);         // or

Locale.setDefault (Locale.GERMANY);    // or

Locale.setDefault (new Locale("pt","BR")); }
 * The first two solutions use the defined constants for coutries.
 * The last solution uses the two-letters codes for language and country as parameters to set the Locale.

Formating numbers
Use the following java code to solve this problem: try { String number = "3,1994768678"; Double teste = (Double) NumberFormat.getInstance.parseObject(number); Konstant.print( NumberFormat.getInstance.format(teste)); teste = (Double) NumberFormat.getInstance.parse("3,11145"); Konstant.print( NumberFormat.getInstance.format(teste));

// this pattern enable a positive pattern (+#,##0.00) // and a negative pattern (-#,##0.00). Separate them with ; String pattern ="+#,##0.00;-#,##0.00"; DecimalFormat f = new DecimalFormat(pattern); double myNumber = Functions.Object2Double("9,45").doubleValue; String sValue = f.format(myNumber); System.out.println(sValue); } catch (Exception exc) {  Konstant.print("not a number"); }

Enumeration
Use the following java code to solve this problem: Enumeration ctrlNames = req.getParameterNames;

while(ctrlNames.hasMoreElements) { out.println((String)ctrlNames.nextElement + ""); }

Using Destructors
Use the following java code to solve this problem: protected void finalize { // free resources }

Validating Email Address
Use the following java code to solve this problem: public static final String VALID_EMAIL_PATTERN = "([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]"       + "{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))"        + "([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)";

public boolean validateEmail (String emailAddress) {       if (emailAddress.matches (VALID_EMAIL_PATTERN)) { return true; } else { return false; } }

Sending an E-Mail
Use the following java code to solve this problem: public void sendMail {       //Set the host smtp address Properties props = new Properties; props.setProperty("mail.smtp.user", "user"); props.setProperty("mail.from", "user@company.de"); props.setProperty("mail.smtp.host", "smtp.mysmtpserver.com"); props.setProperty("password", "myPassword"); //       props.setProperty("mail.debug", "true"); props.put("mail.smtp.auth", Boolean.TRUE.toString);

Authenticator authenticator = new JMailSenderAuthenticator(props); // create some properties and get the default Session Session session = Session.getDefaultInstance( props, authenticator ); session.setDebug( true );

// create a message Message msg = new MimeMessage( session ); int adrListeLang =1; Vector adrListe = new Vector; adrListe.add("user@company.de"); String adrSender = "userSender@othercompany.de"; String message="Hi, User1! How are you?"; try {         // set the from and to address InternetAddress addressFrom = new InternetAddress(adrSender ); msg.setFrom( addressFrom );

InternetAddress[] addressTo = new InternetAddress[ adrListeLang ]; for (int i = 0; i < adrListeLang; i++) {           addressTo[ i ] = new InternetAddress( (String) adrListe.elementAt( i ) ); System.out.println( "Mail an " + (String) adrListe.elementAt( i ) ); }         msg.setRecipients( Message.RecipientType.TO, addressTo ); msg.setRecipient( Message.RecipientType.CC, new InternetAddress( adrSender ) ); // Optional : You can also set your custom headers in the Email if you Want msg.addHeader("Organization", "Name of my Company");

// Setting the Subject and Content Type msg.setSubject( "Here is my Subject" ); msg.setContent( message, "text/plain" ); msg.setSentDate(new Date); // send message Transport.send(msg); }       catch( AddressException adrEx ) {         System.out.println( adrEx.getMessage ); }        catch( MessagingException messEx ) {         System.out.println( messEx.getMessage ); }               }

Applet Tag for HTML
Use the following java code to solve this problem: 

Generating Keys and Signing Applets
To Generate a key and sign an Applet you have to follow these steps:

SET PATH = E:\Programme\j2sdk1.4.2_06\BIN SET JDK_HOME=E:\Programme\j2sdk1.4.2_06
 * Set the following variables in your environment:


 * You have firstly to generate a key and the time to expire. You have to do it once.

Syntax :  keytool -genkey -alias -validity Example:  keytool -genkey -alias LOUCOAPPLET -validity 365
 * Than you can sign your jar file with the alias. Don’t forget to enter the password that you entered before.

Syntax :  jarsigner Example:  jarsigner applet.jar LOUCOAPPLET
 * Now you can test your applet in your browser.

JDBC Connections
The standard syntax for JDBC URLs is shown here. It has three parts, which are separated by colons.

jdbc: : 

Starting a java application in windows without a console window
Create a batch file and use the javaw.exe in another console session using the following code as example: start "JHaushalt" /B javaw.exe -jar jHaushalt.jar

Deserializing (or unmarshal) a serialized object instance
There is a know problem with Stream Unique Identifiers

While attempting to deserialize (or unmarshal) a serialized object instance, you may generate an exception with a message similar to: java.rmi.UnmarshalException: Error unmarshaling return; nested exception is: java.io.InvalidClassException: RMIParm; Local class not compatible: stream classdesc serialVersionUID=9468404698496832181 local class serialVersionUID=7528655624442771181 at java.lang.Throwable.(Compiled Code) at java.rmi.UnmarshalException.(Compiled Code) at RMIServer_Stub.getParm(RMIServer_Stub.java:40) at RMIClient.main(RMIClient.java:7)

This error occurs as a result of the class that was serialized and deserialized having been changed at some point. For example, it can occur when a server attempts to return an instance of an object to a client through Remote Method Invocation (RMI) while the client and server have different definitions of the class. This commonly occurs and can take place when the class is modified and recompiled on the client after being copied to the server. Another scenario might involve writing an object instance to disk, changing the source code for the class and recompiling it, then attempting to read the class instance stored in the disk file. In these cases, the reader's version of the class definition is different from that of the writer, and the exception indicates that these are potentially incompatible versions of the same class. However, it may be that the changes made to the class should not cause older versions to break, such as when new methods or variables are added. In this case, you can avoid problems unmarshalling old class instances by explicitly defining the Stream Unique Identifier (SUID). The SUID is nothing more than a value (usually the hash value for the class definition) that uniquely identifies a class definition. You can determine the SUID for a given serializable class by using the serialver utility included with the Java Development Kit (JDK):

serialver myclass

This will produce output similar to:

myclass: static final long serialVersionUID = -3920827908241085518L;

Adding this statement to the class you wish to modify will allow you to successfully deserialize or unmarshal modified versions of the class. For more information, see the section on the versioning of serializable objects in the Object Serialization Specification document that is included with the JDK.

I think you can use the following code in your class to solve this problem:

private static final long serialVersionUID = 1L;

Showing a modal dialog with default buttons
If you want to customize your message use the JOptionPane object. Example:

Object antwort; String Answer[] = { "Option 1", "Option 2" }; JOptionPane Frage = new JOptionPane(       "Möchten Sie wirklich den Datensatz löschen ?",        JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION,  null, Answer, Answer[1]); // show the dialog dialog.setVisible(true); antwort = Frage.getValue;

But in this case, the default button is not the option 2. I don't know why. Maybe a bug of JDK 1.5 ?

Well, if you want to show your buttons with different labels and set a default button that is not the first button, then try this:

Object antwort; String Answer[] = { "Option 1", "Option 2" }; int ant = JOptionPane.showOptionDialog(ParentComponent	, "Möchten Sie wirklich den Datensatz löschen ?"		, Functions.getApplicationTitel		, JOptionPane.YES_NO_OPTION		, JOptionPane.QUESTION_MESSAGE		, null		, Answer		, Answer[1] );

Wrapping Text
To wrap a text inside a JLabel or other JComponent (not tested) you have to write the text as HTML. Example: JLabel txtMessage = new JLabel; txtMessage.setText(" A very long text... ");

Problem with Repaint/Validate
To validate intern components of a container like JFrame, JInternFrame and so on try to use the following command:

myJFrame.repaint;

If it doesn't work try one of the following commands:

myJFrame.validate; myJFrame.revalidate;

Open and Save Dialog
Try to reuse this method.

private void openFile {     JFileChooser fileChooser = new JFileChooser;

fileChooser.setFileSelectionMode(        JFileChooser.FILES_AND_DIRECTORIES ); int result = fileChooser.showOpenDialog( this );

// user clicked Cancel button on dialog if ( result == JFileChooser.CANCEL_OPTION ) return;

if (fileChooser.getSelectedFile.isDirectory ) txtFilename.setText (fileChooser.getSelectedFile.getPath); else txtFilename.setText (fileChooser.getSelectedFile.getParent); }

Font Dialog
This is a known problem and two freeware solutions were found:

void testFontChosser { // import com.lamatek.swingextras.JFontChooser; // http://www.roseindia.net/search/showtutorials.php?id=1255 Font f = new Font ("Arial",Font.PLAIN, 12); JFontChooser jfc = new JFontChooser(f); jfc.showDialog(null, "test"); System.out.println(jfc.getFont);

// import ZoeloeSoft.projects.JFontChooser.JFontChooser; // http://sourceforge.net/projects/jfontchooser/ ZoeloeSoft.projects.JFontChooser.JFontChooser jfc2 = new ZoeloeSoft.projects.JFontChooser.JFontChooser(null); jfc2.setVisible(true); jfc2.dispose; System.out.println(jfc2.getFont); }

Setting the Applications Font
public static void changeUserFont(Font font) { if (font!=null) { Vector keysForFont = getAllUIKeysForFont; for (String key : keysForFont) { UIManager.put(key, font); }               UIManager.put("InternalFrame.titleFont", font.deriveFont(Font.BOLD, font.getSize+2)); }   }

Don't forget to update the UI afterwards: SwingUtilities.updateComponentTreeUI(Component c);

If you want the Font to be updated immediatly, you should use FontUIResource. (Therefore it's enough to send an FontUIResource Object to the method above).

File Extension
The following method returns the file extension:

/*    * Get the extension of a file. */     public static String getExtension(File f) { String ext = null; String s = f.getName; int i = s.lastIndexOf('.');

if (i > 0 && i < s.length - 1) { ext = s.substring(i+1).toLowerCase; }       return ext; }

Calling stored procedures
Use the code bellow to call stored procedures in Oracle:

stmt = conn.prepareCall("{ call insert_document_creanta( ?, ?, ?, ?) }"); stmt.setInt(1, s.getClientId.intValue); stmt.setString(2, s.getWarehouse); stmt.setString(3, s.getInvoiceSeries); stmt.registerOutParameter(4, java.sql.Types.NUMERIC); stmt.execute;

id = new Integer(stmt.getInt(4));

Use the code bellow to call stored procedures in Access, Sybase, etc.

sql = new StringBuffer("exec Update_News_With_Keywords"); CallableStatement CALLUpdateNewsWithKeywords;    //(stored procedure in the DB) CALLUpdateNewsWithKeywords = Functions.connection.prepareCall(sql.toString);

Using the class Enum
You may find these classes (added in Java 5) useful. This representation is extremely compact and efficient. The space and time performance of this class should be good enough to allow its use as a high-quality, typesafe alternative to traditional int-based "bit flags."


 * EnumSet
 * a high-performance Set implementation backed by a bit-vector. All elements of each EnumSet instance must be elements of a single enum type.


 * EnumMap
 * a high-performance Map implementation backed by an array. All keys in each EnumMap instance must be elements of a single enum type.

Here is a good example of using the class Enum:

public enum Rank { DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE } public static void main(String[] args) { setRanks(EnumSet.of(Rank.JACK, Rank.THREE, Rank.EIGHT, Rank.TEN, Rank.DEUCE)); } public static void setRanks(EnumSet ranks) {	   for (Rank d : ranks) System.out.println(d); if (ranks.contains(Rank.ACE)) System.out.println("Ace is there"); else System.out.println("Ace is NOT there"); if (ranks.contains(Rank.TEN)) System.out.println("TEN is there"); else System.out.println("TEN is NOT there"); }

Fixing Problems with JTable's width and horizontal scrolling
Trying to simply put the table into a JScrollPane doesn't enable horizontal scrolling, until table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); is called.

But calling this may cause some space on the right side of the table, if available. This is caused by a problem in JTables auto-resizing. To fix it, insted setting autoResizeMode off, you should subclass JTable and override getScrollableTracksViewportWidth as follows: /**    * Returns false to indicate that horizontal scrollbars are required * to display the table while honoring perferred column widths. Returns * true if the table can be displayed in viewport without horizontal * scrollbars. *     * @return true if an auto-resizing mode is enabled *  and the viewport width is larger than the table's      *   preferred size, otherwise return false. * @see Scrollable#getScrollableTracksViewportWidth */   @Override public boolean getScrollableTracksViewportWidth { if (autoResizeMode != AUTO_RESIZE_OFF) { if (getParent instanceof JViewport) { return (((JViewport) getParent).getWidth > getPreferredSize.width); }	}	return false; }

Cryptography using 192 / 256 bits
I found some restrictions reading forums and the website of SUN related to cryptography. And it is not possible to use cryptography using 192 / 256 bits key sizes, unless you install on the client the Unlimited Strength Jurisdiction Policy Files.

The file contained there says:

"Due to import control restrictions, the version of JCE policy files that are bundled in the JDK(TM) (1.4 or 5.0) environment allow "strong" but limited cryptography to be used."

To solve this problem you have to follow these steps:

1) Download the unlimited strength JCE policy files: 1.4 or 5.0

2) Uncompress and extract the downloaded file.

This will create a subdirectory called jce. This directory contains the following files:

README.txt           This file COPYRIGHT.html       Copyright information local_policy.jar     Unlimited strength local policy file US_export_policy.jar Unlimited strength US export policy file

3) Install the unlimited strength policy JAR files.

To utilize the encryption/decryption functionalities of the JCE framework without any limitation, first make a copy of the original JCE policy files ( and in the standard place for JCE jurisdiction policy JAR files) in case you later decide to revert to these "strong" versions. Then replace the strong policy files with the unlimited strength versions extracted in the previous step.

The standard place for JCE jurisdiction policy JAR files is:


 * /lib/security        [Solaris]
 * \lib\security        [Win32]

Replace the files and in the standard place for JCE	jurisdiction policy JAR files. Use the system property java.home to know where is the actual jre installed. Then concanate the path /lib/security.

Caching Problems using JDBC
Sometimes, you can execute a SQL statement like this:

SELECT count(*) FROM DEPT

It returns 10 for example. But if you add or delete a row using an extern program the result continues to be 10 in java without a restart.

Solution: for each SELECT statement you must set the property setAutoCommit of the connection object to false and then execute the method after the statement.

How to use and convert enum classes
The example below shows an enum class that has predefined Strings for each value:

public enum EnumChartType { BARCHART, CANDLESTICK, LINE_OPEN, LINE_CLOSE; @Override public String toString { switch(this) { case BARCHART:  return "Bar Chart"; case CANDLESTICK:   return "Candlestick"; case LINE_OPEN:  return "Line (Open)"; case LINE_CLOSE:  return "Line (Close)"; }       return ""; } }

If you want to convert from String to your enum class use the method valueof. The parameter must be exactly the value defined in the enum class as string. Example:

EnumChartType type = EnumChartType.valueOf("CANDLESTICK"); log.debug("Chart Type: " + type); log.debug("Name: " + type.name);

Setting focus to a component
Use the following command:

myComponent.requestFocus;

If you want that a component gains the focus the first time a window is activated, execute the following command after the component has been realized, but before the frame is displayed:

myComponent.requestFocusInWindow;

Changing Look and Feel
To change the "Look and Feel" in Java implement the following code into your application: private static void initializeLookAndFeel { try { // set the default Look and Feel UIManager.setLookAndFeel(new SubstanceCremeCoffeeLookAndFeel); SubstanceLookAndFeel.setCurrentTheme(new SubstanceAquaTheme); // Use Substance on all frames and dialogs SubstanceLookAndFeel.setToUseConstantThemesOnDialogs(true); UIManager.put(SubstanceLookAndFeel.TABBED_PANE_CLOSE_BUTTONS_PROPERTY, Boolean.TRUE); // prepare the system JFrame.setDefaultLookAndFeelDecorated(true); System.setProperty("sun.awt.noerasebackground", "true"); JDialog.setDefaultLookAndFeelDecorated(true); // Apply it to the main window SwingUtilities.updateComponentTreeUI(myJFrame); } catch (Exception e) { log.warn("Look and Feel could not be loaded", e); }   }

In the example above the Substance Library was used to modify the "Look and Feel", but you can also use JGoodies or Javootoo.

Text Changed Event
If you want to know when the text was changed of your JTextField try the solution below:

textField.getDocument.addDocumentListener(new DocumentListener {      public void changedUpdate(DocumentEvent e) {           // TODO: The text was modified exactly here       }       public void removeUpdate(DocumentEvent e) {           // TODO       }       public void insertUpdate(DocumentEvent e) {           // TODO        }   });

Date Picker
If you want to use a date picker in your Swing GUI, then it is better to download the jar file of the project [SwingLab's SwingX]. If you are using Netbeans try to add this new control to the Control Palette.



How to send keys to a Component
Sendkeys is a small method that is equivalent to pressing a key on the keyboard. It is very useful in Visual Basic. Example: SendKeys "{Tab}"    - is equivalent to hitting the tab key on the keyboard SendKeys "{Enter}"  - hits the enter key

In Java, you have to construct a KeyEvent and push it in the system queue. Solution:

//get the system event queue EventQueue q = this.getToolkit.getSystemEventQueue; //play some events long time = System.currentTimeMillis; //ttt is the text component to which you send the keystrokes. //note, it must be visible. KeyEvent E1 = new KeyEvent((Component)ttt, KeyEvent.KEY_PRESSED, time - 7, 0, KeyEvent.VK_A, 'a'); KeyEvent E2 = new KeyEvent((Component)ttt, KeyEvent.KEY_RELEASED, time - 6, 0, KeyEvent.VK_A, 'a'); KeyEvent E3 = new KeyEvent((Component)ttt, KeyEvent.KEY_TYPED, time - 5, 0, KeyEvent.VK_UNDEFINED, 'a'); q.postEvent(E1); q.postEvent(E2); q.postEvent(E3);