code stench

Don’t iterate to find an index. Why? You already know the index.

int toFind = ...;
for (int i=0;i

Just use array[toFind].doSomething(). Iterate only when you are matching some other non-index attribute.

The same applies even if you have lists, or if you're looking for toFind-1.

saving a onscreen component to image file

I have a custom JPanel with the paintComponent() overridden to draw something custom. To export it to an image file, I drew the component into another graphics object.


JPanel custom = ...;
BufferedImage image = new BufferedImage(...);
custom.paint(image.getGraphics());

After this the image would have contained what it looks like on screen. The next step is straightforward: save the image:

ImageIO.write(image, "png", file);

Additional tip: Knowing how Swing render lightweight components is very useful.

Custom JFileChooser

The default JFileChooser doesn’t prompt to overwrite files when saving. It also doesn’t automatically add an extension to the file if the user didn’t type one. I had to do a custom one to support these features for better usability.

The limitation of this specific implementation is it only supports one “image” extension, and it’s not i18n-ed. Customize it more for your own needs.

private class CustomFileChooser extends JFileChooser {
  private String extension;
  public CustomFileChooser(String extension) {
    super();
    this.extension = extension;
    addChoosableFileFilter(new FileNameExtensionFilter(
      String.format("%1$s Images (*.%1$s)", extension), extension));
  }

  @Override public File getSelectedFile() {
    File selectedFile = super.getSelectedFile();

    if (selectedFile != null) {
      String name = selectedFile.getName();
      if (!name.contains("."))
        selectedFile = new File(selectedFile.getParentFile(), 
          name + '.' + extension);
    }

    return selectedFile;
  }

  @Override public void approveSelection() {
    if (getDialogType() == SAVE_DIALOG) {
      File selectedFile = getSelectedFile();
      if ((selectedFile != null) && selectedFile.exists()) {
        int response = JOptionPane.showConfirmDialog(this,
          "The file " + selectedFile.getName() + 
          " already exists. Do you want to replace the existing file?",
          "Ovewrite file", JOptionPane.YES_NO_OPTION,
          JOptionPane.WARNING_MESSAGE);
        if (response != JOptionPane.YES_OPTION)
          return;
      }
    }

    super.approveSelection();
  }
}

Dump XML in Java

In this example, node is the XML node (which can be a document) you want to dump. You’ll see the XML in System.out. If you like the output in a String (e.g. for logging), use a StringWriter as the output.


Transformer serializer = TransformerFactory.newInstance().newTransformer();
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.transform(new DOMSource(node), new StreamResult(System.out));