JTableのセルにHyperlinkを表示
Total: 11891
, Today: 2
, Yesterday: 3
Posted by aterai at
Last-modified:
概要
JTable
のセルの中に、Hyperlink
を表示します。
Screenshot
Advertisement
サンプルコード
class URLRenderer extends DefaultTableCellRenderer implements MouseInputListener {
private int row = -1;
private int col = -1;
@Override 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;
}
@Override public void mouseMoved(MouseEvent e) {
JTable table = (JTable) e.getSource();
Point pt = e.getPoint();
row = table.rowAtPoint(pt);
col = table.columnAtPoint(pt);
if (row < 0 || col < 0) {
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();
int crow = table.rowAtPoint(pt);
int ccol = table.columnAtPoint(pt);
// if (table.convertColumnIndexToModel(ccol) == 2)
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();
}
}
}
@Override public void mouseDragged(MouseEvent e) {
/* not needed */
}
@Override public void mouseEntered(MouseEvent e) {
/* not needed */
}
@Override public void mousePressed(MouseEvent e) {
/* not needed */
}
@Override public void mouseReleased(MouseEvent e) {
/* not needed */
}
}
View in GitHub: Java, Kotlin解説
上記のサンプルでは、JTable
のセル内にリンクを表現するためにhtml
タグを使って文字列を修飾するセルレンダラーを作成して使用しています。
URLRenderer renderer = new URLRenderer();
table.setDefaultRenderer(URL.class, renderer);
table.addMouseListener(renderer);
table.addMouseMotionListener(renderer);