IMAGE Team - The Pantheon project

Java Hints and Tips

How to change the default charset?

   private static void changeDefaultCharsetSet( String encoding ) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException {
      Class c = Charset.class;
      Field defaultCharsetField = ch.getDeclaredField("defaultCharset");
      defaultCharsetField.setAccessible(true);
      defaultCharsetField.set(null, Charset.forName(encoding));
   }

   changeDefaultCharset("UTF-8");

How to set default button in a window?

   JButton applyButton = new JButton("OK");
   applyButton.addActionListener( new ActionListener() {
      public void actionPerformed(ActionEvent e) {
         applyAction();
      }
   } ); 
   getRootPane().setDefaultButton(applyButton);

How to cancel dialog using 'escape' key?

Old version

   JButton cancelButton = new JButton();
   Action cancelKeyAction = new AbstractAction("Cancel")) {
      public void actionPerformed(ActionEvent e) {
         cancelAction();
      }
   };
   cancelButton.setAction(cancelKeyAction);
   KeyStroke cancelKeyStroke = KeyStroke.getKeyStroke((char)KeyEvent.VK_ESCAPE);
   getRootPane().registerKeyboardAction(cancelKeyAction, cancelKeyStroke, JComponent.

New version

   JButton cancelButton = new JButton();
   Action cancelKeyAction = new AbstractAction("Cancel")) {
      public void actionPerformed(ActionEvent e) {
         cancelAction();
      }
   };
   cancelButton.setAction(cancelKeyAction);
   InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
   ActionMap actionMap = getRootPane().getActionMap();
   KeyStroke cancelKeyStroke = KeyStroke.getKeyStroke((char)KeyEvent.VK_ESCAPE,0);
   inputMap.put(cancelKeyStroke, "cancel");
   actionMap.put("cancel", cancelKeyAction);

How to customize tree node handles?

JTree tree = new JTree();
BasicTreUI ui= (BasicTreeUI)tree.getUI();
ui.setExpandedIcon(expandIcon);
ui.setCollapsed(collapseddIcon);

Where can I find new look and feel?

How to force repaint a container?

  1. validate() method: The validate() method is used to cause a container to lay out its subcomponents again.
  2. paintImmediately(Rectangle r).

How to create an image file from a JPanel contents?

   JPanel jp = new JPanel();
   ...
   BufferedImage area = (BufferedImage)this.createImage(jp.getWidth(),jp.getHeight());
   if (area != null) {
      Graphics2D gc = area.createGraphics();
      jp.paint(gc);
      try {
         File outputfile = new File("toto.png");
         ImageIO.write(area, "png", outputfile);
       } catch (IOException e) {
       }
   }

How to refer to the 'this' pointer of a class in an inner class?

Use the 'Class.this' variable:

public class X{

   private class Y {
       public void f() {
           ... X.this ...
       }
   }
}

How to prevent JTextPane from word wrapping?

Override the method:

public boolean getScrollableTracksViewportWidth ( ) {
   return false ;
}

How to get the list of valid @SuppressWarnings types?

Because, the warning types of javac are non-standard, the only way to get the list is to use:

javac -X
(see lint options)

For example, javac 1.6.0_11 returns:

The list of warning type with Eclipse can be get from the Eclipse server: http://help.eclipse.org

For example: The list of tokens of Eclipse version 3.3 is:

How to suppress compiler warnings?

Use the annotation @SuppressWarnings{type} where type is a valid warning type (see the list above).

For example:

		@SuppressWarnings("unchecked")
		LinkedList[] graphSimple = new LinkedList[n];
		for(int i = 0; i < n; i++)
			graphSimple[i] = new LinkedList();

How to mix color for characters in JLabel or JTable?

The label string must begin with "<html>" (not "<HTML>"). Any HTML content is available, for example:

String labelText ="<html>This is an example of <FONT COLOR=RED>Red</FONT> and <FONT COLOR=BLUE>Blue</FONT> text.</html>";

How to get the absolute path of a jar file?

public class Toto {
   private String _jarPath;
   Class c = Toto.class;
   URL tmp= c.getResource(c.getSimpleName() + ".class");
   String s = tmp.getFile();
   int xi = s.indexOf('!'); // Jar file uses the ! meta character
   if (xi>0) s = s.substring(0,xi);
   try {
	URL u = new URL(s);
	_jarPath = new File( u.toURI() ).getParent();
   } catch ( URISyntaxException e1 ) {
	_jarPath =  new File( s).getParent();
   } catch (  MalformedURLException e2 ) {
	_jarPath =  new File( s).getParent();
   }
   System.out.prinln("Jar directory: "+_jarPath);
}

How to get the current working directory?

  String homePath=System.getProperty("user.dir");

How to get the home directory?

  String homePath=System.getProperty("user.home");

The Pantheon project
Image Team GREYC Laboratory
UMR CNRS 6072 - ENSICAEN - University of Caen, France
This page was last modified on 12 April 2012