TITLE:JTableのセルにHyperlinkを表示

JTableのセルにHyperlinkを表示

Posted by terai at 2008-12-29

概要

JTableのセルの中に、Hyperlinkを表示します。

  • &jnlp;
  • &jar;
  • &zip;

#screenshot

サンプルコード

class URLRenderer extends DefaultTableCellRenderer
        implements MouseListener, MouseMotionListener {
  private final JTable table;
  private int row = -1;
  private int col = -1;
  public URLRenderer(JTable table) {
    super();
    this.table = table;
    table.addMouseListener(this);
    table.addMouseMotionListener(this);
  }
  public Component getTableCellRendererComponent(JTable table, Object value,
                           boolean isSelected, boolean hasFocus,
                           int row, int column) {
    super.getTableCellRendererComponent(table, value, isSelected, false, row, column);
    if(!table.isEditing() && this.row==row && this.col==column) {
      setText("<html><u><font color='blue'>"+value.toString());
    }else if(hasFocus) {
      setText("<html><font color='blue'>"+value.toString());
    }else{
      setText(value.toString());
    }
    return this;
  }
  public void mouseMoved(MouseEvent e) {
    Point pt = e.getPoint();
    row = table.rowAtPoint(pt);
    col = table.columnAtPoint(pt);
    if(row<0 || col<0) {
      row = -1;
      col = -1;
    }
    table.repaint();
  }
  public void mouseExited(MouseEvent e)  {
    row = -1;
    col = -1;
    table.repaint();
  }
  public void mouseClicked(MouseEvent e) {
    Point pt = e.getPoint();
    int crow = table.rowAtPoint(pt);
    int ccol = table.columnAtPoint(pt);
    if(table.getColumnClass(ccol).equals(URL.class))
      System.out.println(table.getValueAt(crow, ccol));
  }
  public void mouseDragged(MouseEvent e) {}
  public void mouseEntered(MouseEvent e) {}
  public void mousePressed(MouseEvent e) {}
  public void mouseReleased(MouseEvent e) {}
}

解説

htmlタグを使って文字列を修飾するセルレンダラーを作成して使用しています。

TableColumn col = table.getColumnModel().getColumn(2);
col.setCellRenderer(new URLRenderer(table));

参考リンク

コメント