概要

JFileChooserの詳細ファイル一覧でファイル名が省略されている場合にJToolTipでそれを表示します。

サンプルコード

JButton button3 = new JButton("JTable tooltips");
button3.addActionListener(e -> {
  JFileChooser chooser = new JFileChooser();
  Optional.ofNullable(chooser.getActionMap().get("viewTypeDetails"))
    .ifPresent(a -> a.actionPerformed(
      new ActionEvent(e.getSource(), e.getID(), "viewTypeDetails")));
  stream(chooser)
    .filter(JTable.class::isInstance)
    .map(JTable.class::cast)
    .findFirst()
    .ifPresent(MainPanel::setCellRenderer);
  int retvalue = chooser.showOpenDialog(log.getRootPane());
  if (retvalue == JFileChooser.APPROVE_OPTION) {
    log.setText(chooser.getSelectedFile().getAbsolutePath());
  }
});
// ...
private static void setCellRenderer(JTable table) {
  table.setDefaultRenderer(Object.class, new TooltipTableCellRenderer());
}
// ...
class TooltipTableCellRenderer implements TableCellRenderer {
  private final TableCellRenderer renderer = new DefaultTableCellRenderer();
  @Override public Component getTableCellRendererComponent(
      JTable table, Object value, boolean isSelected, boolean hasFocus,
      int row, int column) {
    JLabel l = (JLabel) renderer.getTableCellRendererComponent(
        table, value, isSelected, hasFocus, row, column);
    Insets i = l.getInsets();
    Rectangle rect = table.getCellRect(row, column, false);
    rect.width -= i.left + i.right;
    Optional.ofNullable(l.getIcon()).ifPresent(icon ->
        rect.width -= icon.getIconWidth() + l.getIconTextGap());
    FontMetrics fm = l.getFontMetrics(l.getFont());
    String str = Objects.toString(value, "");
    l.setToolTipText(fm.stringWidth(str) > rect.width ? str : null);
    return l;
  }
}
View in GitHub: Java, Kotlin

解説

参考リンク

コメント