Extreme Java When vanilla Java is not enough

14Feb/084

Long lines in Java Tooltips (or multiline tooltips)

Do you want to show a tooltip with more than one line? Are your tooltips too large to fit in one line? The solution is easier than you think. Tooltips, in Java, accept HTML code:

jcomponent.setToolTipText("HTML tooltip");

It isn't a Firefox, but is very powerful. And, when I said HTML, I also think about CSS. So, you can set your tooltips using this evil cheat:

<html><body>
<strong><div style="width: 300px; text-justification: justify;"></strong>
Blah Blah Blah (repeat "blah" 100 times)
</div>
</html></body>

Have you seen automatic line breaks and the justification? Oh, yeah!

BTW, do you remember old days, when you couldn't believe WordPad didn't have justified text? :)

14Feb/080

Copying file in Java – NIO version

In old days, copying a file in Java wasn't easy: you had to create a array buffer to read from source and write to destination. Now, with NIO from JDK, it's a matter of creating the streams and let the API do the dirty job.

FileChannel src = new FileInputStream(srcFile).getChannel();
FileChannel dst = new FileOutputStream(dstFile).getChannel();
try {
  dst.transferFrom(src, 0, src.size());
} finally  {
  src.close();
  dst.close();
}
14Feb/081

Tooltip on JTable cells

This is a easy one (but it is not obvious): how to define tooltips in JTable's cells. Just create a class like this one:

public class ToolTipTable extends JTable {
  @Override
  public Component prepareRenderer(TableCellRenderer renderer,
        int row, int column) {
    Component c = super.prepareRenderer(renderer, row, column);
    if (c instanceof JComponent) {
      JComponent jc = (JComponent) c;
      jc.setToolTipText((String) getValueAt(row, column));
    }
    return c;
  }
}

This example will set cells' tooltip to its own content. Very useful if you have large contents on small cells.

Tagged as: , 1 Comment