概要

JTableのセル内ではなく、内部のリンク上にカーソルがきた場合だけHoverするように設定します。

サンプルコード

// @see SwingUtilities2.pointOutsidePrefSize(...)
private static boolean pointInsidePrefSize(JTable table, Point p) {
  int row = table.rowAtPoint(p);
  int col = table.columnAtPoint(p);
  TableCellRenderer tcr = table.getCellRenderer(row, col);
  Object value = table.getValueAt(row, col);
  Component cell = tcr.getTableCellRendererComponent(
    table, value, false, false, row, col);
  Dimension itemSize = cell.getPreferredSize();
  Insets i = ((JComponent) cell).getInsets();
  Rectangle cellBounds = table.getCellRect(row, col, false);
  cellBounds.width = itemSize.width - i.right - i.left;
  cellBounds.translate(i.left, i.top);
  return cellBounds.contains(p);
}

private static boolean isURLColumn(JTable table, int column) {
  return column >= 0 && table.getColumnClass(column).equals(URL.class);
}

@Override public void mouseMoved(MouseEvent e) {
  JTable table = (JTable) e.getSource();
  Point pt = e.getPoint();
  int prev_row = row;
  int prev_col = col;
  boolean prev_ro = isRollover;
  row = table.rowAtPoint(pt);
  col = table.columnAtPoint(pt);
  isRollover = isURLColumn(table, col) && pointInsidePrefSize(table, pt);
  if ((row == prev_row && col == prev_col && isRollover == prev_ro) ||
      (!isRollover && !prev_ro)) {
    return;
  }
  // >>>> HyperlinkCellRenderer.java
  Rectangle repaintRect;
  if (isRollover) {
    Rectangle r = table.getCellRect(row, col, false);
    repaintRect = prev_ro ?
      r.union(table.getCellRect(prev_row, prev_col, false)) : r;
  } else { //if (prev_ro) {
    repaintRect = table.getCellRect(prev_row, prev_col, false);
  }
  table.repaint(repaintRect);
  // <<<<
  //table.repaint();
}

@Override public void mouseExited(MouseEvent e)  {
  JTable table = (JTable) e.getSource();
  if (isURLColumn(table, col)) {
    table.repaint(table.getCellRect(row, col, false));
    row = -1;
    col = -1;
    isRollover = false;
  }
}

@Override public void mouseClicked(MouseEvent e) {
  JTable table = (JTable) e.getSource();
  Point pt = e.getPoint();
  int ccol = table.columnAtPoint(pt);
  if (isURLColumn(table, ccol) && pointInsidePrefSize(table, pt)) {
    int crow = table.rowAtPoint(pt);
    URL url = (URL) table.getValueAt(crow, ccol);
    System.out.println(url);
    try {
      Desktop.getDesktop().browse(url.toURI());
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}
View in GitHub: Java, Kotlin

解説

  • SwingUtilities2.pointOutsidePrefSize(...)を参考にしてセルの表示に使用するコンポーネント(JLabel)の推奨サイズの範囲内にカーソルがあるかどうかを比較
  • JTableに追加したMouseListenerでこれを使用してURLの文字列をHover状態に変更するか、またはクリックされたかなどを判断する

参考リンク

コメント