Java JTable set table cell tooltip text

Description

Java JTable set table cell tooltip text


import java.awt.Component;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

public class Main {
  public static void main(String[] args) {
    JFrame f = new JFrame("JTable example");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    /* w  ww .  jav a 2s .co m*/
    String[] columnNames = { "Ordinal" };
    String[][] tableData = {{ "One" }, //
                            { "Two" },//
                            { "Three" } };
    
    JTable table = new JTable(tableData, columnNames);
    
    table.setDefaultRenderer(Object.class, new TimesTableRenderer());
    
    f.add(new JScrollPane(table));
    f.pack();
    
    f.setVisible(true);

  }
}
class TimesTableRenderer extends DefaultTableCellRenderer {
   @Override
   public Component getTableCellRendererComponent(JTable table, Object value,
       boolean isSelected, boolean hasFocus, int row, int column) {

     Component c = super.getTableCellRendererComponent(table, value, isSelected,
         hasFocus, row, column);
     JComponent jc = (JComponent) c;
     jc.setToolTipText((row + 1) + "x" + (column + 1) + "=" + ((row + 1) * (column + 1)));
     return jc;
   }
 }



PreviousNext

Related