How can I enable hyperlink for every record in the JTable
?
What I want to do is such that a user can click on the hyperlink which will then display the information they can edit/update.
Alternatively how can I enable in place editing of the table data?
Another question is i am currently using the following way to display different screen. But this is not an elegant way i understand we should use cardlayout but how exactly to go about it?
mainPanel.setVisible(false);
createBlogEntryPanel.setVisible(true);
setComponent(createBlogEntryPanel);
To address the problem with JTable
consuming the events, you can add your own MouseListener
(or a MouseAdapter
) to the JTable
and do your manipulation inside this listener. Here is an example of what you can achieve:
public class Main extends JFrame {
public Main() {
super();
DefaultTableModel dt = new DefaultTableModel(
new String[][] { { "http://google.com" }, { "http://gmail.com" } }, new String[] { "Url" });
final JTable t = new JTable(dt);
t.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int row = t.rowAtPoint(new Point(e.getX(), e.getY()));
int col = t.columnAtPoint(new Point(e.getX(), e.getY()));
System.out.println(row + " " + col);
String url = (String) t.getModel().getValueAt(row, col);
System.out.println(url + " was clicked");
// DO here what you want to do with your url
}
@Override
public void mouseEntered(MouseEvent e) {
int col = t.columnAtPoint(new Point(e.getX(), e.getY()));
if (col == 0) {
t.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
}
@Override
public void mouseExited(MouseEvent e) {
int col = t.columnAtPoint(new Point(e.getX(), e.getY()));
if (col != 0) {
t.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
}
});
add(new JScrollPane(t));
t.getColumnModel().getColumn(0).setCellRenderer(new TableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, final Object value, boolean arg2,
boolean arg3, int arg4, int arg5) {
final JLabel lab = new JLabel("<html><a href=\"" + value + "\">" + value + "</a>");
return lab;
}
});
setSize(700, 500);
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
new Main();
}
}