• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JTableのセル内でリンクだけHover可能にする
#navi(../)
RIGHT:Posted by [[aterai]] at 2011-08-29
*JTableのセル内でリンクだけHover可能にする [#e6636e70]
JTableのセル内ではなく、内部のリンク上にカーソルがきた場合だけHoverするように設定します。

-&jnlp;
-&jar;
-&zip;

//#screenshot
#ref(https://lh3.googleusercontent.com/-OQfktkzVBD4/Tlsepf4ePZI/AAAAAAAABBQ/bikhWupFHEk/s800/PointInsidePrefSize.png)

**サンプルコード [#g63a443d]
#code{{
//@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();
  Rectangle cellBounds = table.getCellRect(row, col, false);
  cellBounds.width = itemSize.width;
  return cellBounds.contains(p);
}
@Override public void mouseMoved(MouseEvent e) {
  JTable table = (JTable)e.getSource();
  Point pt = e.getPoint();
  if(pointInsidePrefSize(table, pt)) {
    row = table.rowAtPoint(pt);
    col = table.columnAtPoint(pt);
  }else{
    row = -1;
    col = -1;
  }
  table.repaint();
}
@Override public void mouseExited(MouseEvent e)  {
  JTable table = (JTable)e.getSource();
  row = -1;
  col = -1;
  table.repaint();
}
@Override public void mouseClicked(MouseEvent e) {
  JTable table = (JTable)e.getSource();
  Point pt = e.getPoint();
  if(pointInsidePrefSize(table, pt)) {
    int crow = table.rowAtPoint(pt);
    int ccol = table.columnAtPoint(pt);
    if(table.getColumnClass(ccol).equals(URL.class)) {
      URL url = (URL)table.getValueAt(crow, ccol);
      System.out.println(url);
      //try{
      //  Desktop.getDesktop().browse(url.toURI());
      //}catch(Exception ex) {
      //  ex.printStackTrace();
      //}
    }
  }
}
}}

**解説 [#c629ee2d]
SwingUtilities2.pointOutsidePrefSize(...)を参考にして、セルの表示に使用するコンポーネント(JLabel)の標準サイズ(幅)内にカーソルがあるかどうかを比較するメソッドを作成しています。JTableに追加したMouseListenerでこれを使用し、URLの文字列をHoverするか、それがクリックされたかを判断しています。

**参考リンク [#h06368d9]
-[[JTableのセルにHyperlinkを表示>Swing/HyperlinkInTableCell]]
-[[Htmlで修飾した文字列のクリップ>Swing/ClippedHtmlLabel]]
-[[JTableで文字列をクリックした場合だけセルを選択状態にする>Swing/TableFileList]]

**コメント [#r6f7ffe9]
#comment