Multiple JButtons in a JTable cell: handling events

Hello!
I'm trying to develop a Swing application which makes use of tables in several panels.
Each row of each table should present the user two buttons, one for editing the row, one for viewing details of that row. Both editing and viewing are done in another panel.
I thought I could add the buttons as the last column of each row, so I made a panel which holds the two buttons and the id of the row, so that I know what I have to edit or view.
I managed to insert the panel as the last column, but I can't have the buttons click.
I studied cell renderers and editors from several tutorials and examples, but evidently I can't understand either of them: whatever I try doesn't change the outcome... :(
Below is the code I use, except for imports and packages:
ActionPanel.java - The panel which holds the buttons and the row id
public class ActionPanel extends JPanel{
  private static final long serialVersionUID = 1L;
  public static String ACTION_VIEW="view";
  public static String ACTION_EDIT="edit";
  private String id;
  private JButton editButton;
  private JButton viewButton;
  public String getId() {
    return id;
  public void setId(String id) {
    this.id = id;
  public JButton getEditButton() {
    return editButton;
  public void setEditButton(JButton editButton) {
    this.editButton = editButton;
  public JButton getViewButton() {
    return viewButton;
  public void setViewButton(JButton viewButton) {
    this.viewButton = viewButton;
  public ActionPanel() {
    super();
    init();
  public ActionPanel(String id) {
    super();
    this.id = id;
    init();
  private void init(){
    setLayout(new FlowLayout(FlowLayout.CENTER, 10, 0))
    editButton=new JButton(new ImageIcon("./images/icons/editButtonIcon.png"));
    editButton.setBorderPainted(false);
    editButton.setOpaque(false);
    editButton.setAlignmentX(TOP_ALIGNMENT);
    editButton.setMargin(new Insets(0,0,0,0));
    editButton.setSize(new Dimension(16,16));
    editButton.setMaximumSize(new Dimension(16, 16));
    editButton.setActionCommand(ACTION_EDIT);
    editButton.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e) {
        JOptionPane.showMessageDialog(null, id, "Editing", JOptionPane.INFORMATION_MESSAGE);
    viewButton=new JButton(new ImageIcon("./images/icons/viewButtonIcon.png"));
    viewButton.setMaximumSize(new Dimension(16, 16));
    viewButton.setActionCommand(ACTION_VIEW);
    viewButton.setBorderPainted(false);
    viewButton.setOpaque(false);
    viewButton.setMargin(new Insets(0,0,0,0));
    viewButton.setSize(new Dimension(16,16));
    viewButton.setMaximumSize(new Dimension(16, 16));
    viewButton.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e) {
        JOptionPane.showMessageDialog(null, id, "Viewing", JOptionPane.INFORMATION_MESSAGE);
    add(viewButton);
    add(editButton);
ActionPanelRenerer.java - the renderer for the above panel
public class ActionPanelRenderer implements TableCellRenderer{
  public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    Component ret=(Component)value;
    if (isSelected) {
      ret.setForeground(table.getSelectionForeground());
      ret.setBackground(table.getSelectionBackground());
    } else {
      ret.setForeground(table.getForeground());
      ret.setBackground(UIManager.getColor("Button.background"));
    return ret;
ActionPanelEditor.java - this is the editor, I can't figure out how to implement it!!!!
public class ActionPanelEditor extends AbstractCellEditor implements TableCellEditor{
  public Component getTableCellEditorComponent(JTable table,Object value,boolean isSelected,int row,int column) {
    return (ActionPanel)value;
  public Object getCellEditorValue() {
    return null;
ServicesModel.java - The way I fill the table is through a model:
public class ServicesModel extends AbstractTableModel  {
  private Object[][] data;
  private String[] headers;
  public ServicesModel(Object[][] services, String[] headers) {
    this.data=services;
    this.headers=headers;
  public int getColumnCount() {
    return headers.length;
  public int getRowCount() {
    return data.length;
  public Object getValueAt(int row, int col) {
    if(col==data.length-1)
      return new ActionPanel(""+col);
    else
      return data[row][col];
  public boolean isCellEditable(int row, int col) {
    return false;
  public Class getColumnClass(int column) {
    return getValueAt(0, column).getClass();
ServicesList.java - The panel which holds the table (BasePanel is a custom class, not related to the table)
public class ServicesList extends BasePanel {
  private JLabel label;
  private JTable grid;
  public ServicesList(SessionManager sessionManager){
    super(sessionManager);
    grid=new JTable() ;
    add(new JScrollPane(grid), BorderLayout.CENTER);
    layoutComponents();
  public void layoutComponents(){
    ConfigAccessor dao=new ConfigAccessor(connectionUrl, connectionUser, connectionPass);
    String[] headers=I18N.get(dao.getServiceLabels());
    grid.setModel(new ServicesModel(dao.getServices(), headers));
    grid.setRowHeight(20);
    grid.getColumnModel().getColumn(headers.length-1).setCellRenderer(new ActionPanelRenderer());
    grid.setDefaultEditor(ActionPanel.class, new ActionPanelEditor());
    grid.removeColumn(grid.getColumnModel().getColumn(0));
    dao.close();
}Please can anyone at least address me to what I'm doing wrong? Code would be better, but examples or hints will do... ;)
Thank you very much in advance!!!

Hello!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class MultipleButtonsInCellTest {
  public JComponent makeUI() {
    String[] columnNames = {"String", "Button"};
    Object[][] data = {{"AAA", null}, {"BBB", null}};
    DefaultTableModel model = new DefaultTableModel(data, columnNames) {
      @Override public Class<?> getColumnClass(int column) {
        return getValueAt(0, column).getClass();
    JTable table = new JTable(model);
    table.setRowHeight(36);
    ActionPanelEditorRenderer er = new ActionPanelEditorRenderer();
    TableColumn column = table.getColumnModel().getColumn(1);
    column.setCellRenderer(er);
    column.setCellEditor(er);
    JPanel p = new JPanel(new BorderLayout());
    p.add(new JScrollPane(table));
    p.setPreferredSize(new Dimension(320, 200));
    return p;
  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
      @Override public void run() { createAndShowGUI(); }
  public static void createAndShowGUI() {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    f.getContentPane().add(new MultipleButtonsInCellTest().makeUI());
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);
class ActionPanelEditorRenderer extends AbstractCellEditor
                   implements TableCellRenderer, TableCellEditor {
  JPanel panel1 = new JPanel();
  JPanel panel2 = new JPanel();
  public ActionPanelEditorRenderer() {
    super();
    JButton viewButton2 = new JButton(new AbstractAction("view2") {;
      public void actionPerformed(ActionEvent e) {
        JOptionPane.showMessageDialog(null, "Viewing");
    JButton editButton2 = new JButton(new AbstractAction("edit2") {;
      public void actionPerformed(ActionEvent e) {
        JOptionPane.showMessageDialog(null, "Editing");
    panel1.setOpaque(true);
    panel1.add(new JButton("view1"));
    panel1.add(new JButton("edit1"));
    panel2.setOpaque(true);
    panel2.add(viewButton2);
    panel2.add(editButton2);
  @Override
  public Component getTableCellRendererComponent(JTable table, Object value,
               boolean isSelected, boolean hasFocus, int row, int column) {
    panel1.setBackground(isSelected?table.getSelectionBackground()
                                   :table.getBackground());
    return panel1;
  @Override
  public Component getTableCellEditorComponent(JTable table, Object value,
                                boolean isSelected, int row, int column) {
    panel2.setBackground(table.getSelectionBackground());
    return panel2;
  @Override
  public Object getCellEditorValue() {
    return null;
}

Similar Messages

  • Multiple selection in a JTable cell

    Dear friends,
    I have to provide a way to user select multiple names in a unique cell of a JTable....
    i.e., the user click on te cell, and some pane or list appears on the screen.. te user then select some field and then close the pane.
    next time te user click on the same cell, the list comes with the updated fields...
    how to ?
    JList? JComboBox ? JOptionPane ?

    If you use a JButton as the cell editor, you could invoke a JList from button's event listener.

  • Multiple Lines in a Jtable Cell

    I am trying to place multiple lines in a single cell of Jtable
    The text Of the cell comes from the database.I am trying to do it using a JLabel .If anyone can help me please do so
    thanks
    kishore
    [email protected]

    It can be done but it is quite a lot of work. Basically you have to produce your own cell renderer and use that instead. A good book on swing will tell you how to do it.

  • Multiple JRadioButtons in a JTable cell

    I have this code that works, but I want to make it so only a single click is require to change the radio buttons in the cell. Right now it takes a double click.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    * @version 1.2 08/13/99
    public class JRadioButtonTableExample2 extends JFrame {
      public JRadioButtonTableExample2(){
        super( "JRadioButtonTable Example" );
            String[] columnHeader = {"Questions","Answer"};
             Object[][] o = new Object[50][2];
             DefaultTableModel dm = new DefaultTableModel();
             dm.setDataVector(o,columnHeader);
        JTable table = new JTable(dm);
        String[] answer = {"A","B","C"};
        table.getColumn("Answer").setCellRenderer(
          new RadioButtonRenderer(answer)
        table.getColumn("Answer").setCellEditor(
          new RadioButtonEditor(new JCheckBox(),
                                new RadioButtonPanel(answer))
        JScrollPane scroll = new JScrollPane(table);
        getContentPane().add( scroll );
      // Cell base
      class RadioButtonPanel extends JPanel {
        JRadioButton[] buttons;
        RadioButtonPanel(String[] str) {
          setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
          buttons = new JRadioButton[str.length];
          for (int i=0; i<buttons.length; i++) {
            buttons[i] = new JRadioButton(str);
    buttons[i].setFocusPainted(false);
    add(buttons[i]);
    public void setSelectedIndex(int index) {
    for (int i=0;i<buttons.length;i++) {
    buttons[i].setSelected(i == index);
    public int getSelectedIndex() {
    for (int i=0; i<buttons.length; i++) {
    if (buttons[i].isSelected()) {
    return i;
    return -1;
    public JRadioButton[] getButtons() {
    return buttons;
    class RadioButtonRenderer extends RadioButtonPanel
    implements TableCellRenderer {   
    RadioButtonRenderer(String[] strs) {
    super(strs);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    if (value instanceof Integer) {
    setSelectedIndex(((Integer)value).intValue());
    return this;
    class RadioButtonEditor extends DefaultCellEditor
    implements ItemListener {
    RadioButtonPanel panel;
    public RadioButtonEditor(JCheckBox checkBox,RadioButtonPanel panel) {
    super(checkBox);
    this.panel = panel;
    ButtonGroup buttonGroup = new ButtonGroup();
    JRadioButton[] buttons = panel.getButtons();
    for (int i=0; i<buttons.length; i++) {
    buttonGroup.add(buttons[i]);
    buttons[i].addItemListener(this);
    public Component getTableCellEditorComponent(JTable table, Object value,
    boolean isSelected, int row, int column) {
    if (value instanceof Integer) {
    panel.setSelectedIndex(((Integer)value).intValue());
    return panel;
    public Object getCellEditorValue() {
    return new Integer(panel.getSelectedIndex());
    public void itemStateChanged(ItemEvent e) {
    super.fireEditingStopped();
    public static void main(String[] args) {
    JRadioButtonTableExample2 frame = new JRadioButtonTableExample2();
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.setSize( 230, 140 );
    frame.setVisible(true);

    It looks to me like the problem is that the renderer is interfering with the editor. When the editor is invoked, something in jtable is rerendering the other items. This is causing a flood of change events to be fired. I'm not sure how you would fix this. The first thing that occurred to me was to make a separate set of buttons for the renderer vs the editor. I don't have time to try it right now.

  • My JButton inside a JTable cell does not respond to clicks

    I have a Jtable which extends AbstractTableModel and uses an arraylist to fill the data in the model. The first column of this table is my button column. I have a class for my button coumn which is:
    class MyButtonCol extends AbstractCellEditor
            implements TableCellRenderer, TableCellEditor, ActionListenerMy button column class has getTableCellRendererComponent and getTableCellEditorComponent. My problem is that the button shows on the table but it does not respond to clicks. Any help will be appreciated.

    That does not seem to be the problem. I have the method in my class but it still does not respond to clicks. This is my AbstractTableModel class:
    class WorklisttableModel extends AbstractTableModel{
         protected static List<Worklist> transaction;
         protected String[] columnNames = new String[]{" ", "Modality", "Status","Patient name",
                "Patient ID","Date of birth","Study date","Referring physician","Description"};
         public WorklisttableModel(){
             transaction = new ArrayList<Worklist>();
             fillmodel();
          @Override
          public boolean isCellEditable(int row, int column) {
                return false;
          @Override
          public int getColumnCount() {
                return 9;
          @Override
          public int getRowCount() {
                return (transaction!=null) ? transaction.size() : 0;
          @Override
          public Object getValueAt(int rowIndex, int columnIndex) {
              if(rowIndex < 0 || rowIndex>=getRowCount())
                  return" ";
                  Worklist row = (Worklist)transaction.get(rowIndex);
                  switch(columnIndex){
                      //case 0:return "";
                      case 1:return " "+row.getModality();
                      case 2: return row.getStatus();
                      case 3:return row.getName();
                      case 4:return row.getID();
                      case 5:return row.getDOB();
                      case 6:return row.getStudyDate();
                      case 7:return row.getReferringP();
                      case 8:return row.getDescription();
               return " ";
          public Class getColumnClass(int col){
              return getValueAt(0,col).getClass();
          @Override
          public String getColumnName(int columnIndex) {
                return columnNames[ columnIndex ];
          protected void fillmodel(){
              transaction.add(new Worklist("","US","active","Simpson","1232222",new java.util.Date(73,8,12),new Date(18,8,13),"Dr. Francis","Brain"));
              transaction.add(new Worklist("","US","inactive","Dodggy","3498222",new java.util.Date(83,8,12),new Date(16,8,17),"Dr. Francis","Heart"));
              transaction.add(new Worklist("","CT","active","Williams","7892222",new java.util.Date(98,9,5),new Date(19,2,13),"Dr. Evans","Dental"));
              transaction.add(new Worklist("","MR","inactive","Brian","89765412",new java.util.Date(65,5,23),new Date(19,1,18),"Dr. Evans","Brain"));
              Collections.sort( transaction, new Comparator<Worklist>(){
              public int compare( Worklist a, Worklist b) {
                  return a.getName().compareTo( b.getName() );
    }

  • How to include a jButton in the jTable CellEditor?

    sir,
    how can include a jButton in the jTable cell Editor as we include checkbox & Combo inthe Cell Editor?
    thks.

    There is c:import tag in the JSTL that will include the HTML from a file on another server.

  • How to make a cell in a JTable to be uneditable and handle events

    I tried many things but failed,How do you make a cell in a JTable to be uneditable and also be able to handle events>Anyone who knows this please help.Thanx

    Hello Klaas2001
    You can add KeyListener ,MouseListener
    Suppose you have set the value of cell using setValueAt()
    table.addKeyListener(this);
    public void keyTyped(KeyEvent src)
    String val="";
    int r= table.getEditingRow();
    int c= table.getEditingColumn();
    val=table.getValueAt(r,c).toString();
    if (r!=-1 && c!=-1)
    TableCellEditor tableCellEditor = table.getCellEditor(r, c);
    tableCellEditor.stopCellEditing();
    table.clearSelection();
    table.setValueAt(val,r,c);
    public void keyReleased(KeyEvent src)
    public void keyPressed(KeyEvent src)
    table.addMouseListener(this);
    public void mouseClicked(MouseEvent e)
    public void mouseEntered(MouseEvent e)
    public void mouseExited(MouseEvent e)
    public void mousePressed(MouseEvent e)
    public void mouseReleased(MouseEvent e)
    if(e.getClickCount()>=2)//Double Click
    table.clearSelection();
    int r= table.getEditingRow();
    int c= table.getEditingColumn();
    if (r!=-1 && c!=-1)
    TableCellEditor tableCellEditor = table.getCellEditor (
    r,c);
    tableCellEditor.stopCellEditing();
    table.clearSelection();
    table.setValueAt("",r,c);
    }//Mouse Released
    You can remove keyListener and Mouse Listener whenever You want to edit
    then add it later.
    Regarding handling events implement javax.swing.event.TableModelListener
    table.getModel().addTableModelListener(this);
    public void tableChanged(javax.swing.event.TableModelEvent source)
    TableModel tabMod = (TableModel)source.getSource();
         switch (source.getType())
    case TableModelEvent.UPDATE:
         break;
         }//Table Changed Method
    //This method gets fired after table cell value is changed.

  • Problem in event handling of combo box in JTable cell

    Hi,
    I have a combo box as an editor for a column cells in JTable. I have a event listener for this combo box. When ever I click on the JTable cell whose editor is combo box,
    I get the following exception,
    Exception occurred during event dispatching:
    java.lang.NullPointerException
         at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.setDispatchComponent(Unknown Source)
         at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.mousePressed(Unknown Source)
         at java.awt.AWTEventMulticaster.mousePressed(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Can any one tell me how to over come this problem.
    Thanks,
    Raghu

    Here's an example of the model I used in my JTable. I've placed 2 comboBoxes with no problems.
    Hope this helps.
    public class FileModel5 extends AbstractTableModel
    public boolean isEditable = false;
    protected static int NUM_COLUMNS = 3;
    // initialize number of rows to start out with ...
    protected static int START_NUM_ROWS = 0;
    protected int nextEmptyRow = 0;
    protected int numRows = 0;
    static final public String file = "File";
    static final public String mailName = "Mail Id";
    static final public String postName = "Post Office Id";
    static final public String columnNames[] = {"File", "Mail Id", "Post Office Id"};
    // List of data
    protected Vector data = null;
    public FileModel5()
    data = new Vector();
    public boolean isCellEditable(int rowIndex, int columnIndex)
    // The 2nd & 3rd column or Value field is editable
    if(isEditable)
    if(columnIndex > 0)
    return true;
    return false;
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c)
    return getValueAt(0, c).getClass();
    * Retrieves number of columns
    public synchronized int getColumnCount()
    return NUM_COLUMNS;
    * Get a column name
    public String getColumnName(int col)
    return columnNames[col];
    * Retrieves number of records
    public synchronized int getRowCount()
    if (numRows < START_NUM_ROWS)
    return START_NUM_ROWS;
    else
    return numRows;
    * Returns cell information of a record at location row,column
    public synchronized Object getValueAt(int row, int column)
    try
    FileRecord5 p = (FileRecord5)data.elementAt(row);
    switch (column)
    case 0:
    return (String)p.file;
    case 1:
    return (String)p.mailName;
    case 2:
    return (String)p.postName;
    catch (Exception e)
    return "";
    public void setValueAt(Object aValue, int row, int column)
    FileRecord5 arow = (FileRecord5)data.elementAt(row);
    arow.setElementAt((String)aValue, column);
    fireTableCellUpdated(row, column);
    * Returns information of an entire record at location row
    public synchronized FileRecord5 getRecordAt(int row) throws Exception
    try
    return (FileRecord5)data.elementAt(row);
    catch (Exception e)
    throw new Exception("Record not found");
    * Used to add or update a record
    * @param tableRecord
    public synchronized void updateRecord(FileRecord5 tableRecord)
    String file = tableRecord.file;
    FileRecord5 p = null;
    int index = -1;
    boolean found = false;
    boolean addedRow = false;
    int i = 0;
    while (!found && (i < nextEmptyRow))
    p = (FileRecord5)data.elementAt(i);
    if (p.file.equals(file))
    found = true;
    index = i;
    } else
    i++;
    if (found)
    { //update
    data.setElementAt(tableRecord, index);
    else
    if (numRows <= nextEmptyRow)
    //add a row
    numRows++;
    addedRow = true;
    index = nextEmptyRow;
    data.addElement(tableRecord);
    //Notify listeners that the data changed.
    if (addedRow)
    nextEmptyRow++;
    fireTableRowsInserted(index, index);
    else
    fireTableRowsUpdated(index, index);
    * Used to delete a record
    public synchronized void deleteRecord(String file)
    FileRecord5 p = null;
    int index = -1;
    boolean found = false;
    int i = 0;
    while (!found && (i < nextEmptyRow))
    p = (FileRecord5)data.elementAt(i);
    if (p.file.equals(file))
    found = true;
    index = i;
    } else
    i++;
    if (found)
    data.removeElementAt(i);
    nextEmptyRow--;
    numRows--;
    fireTableRowsDeleted(START_NUM_ROWS, numRows);
    * Clears all records
    public synchronized void clear()
    int oldNumRows = numRows;
    numRows = START_NUM_ROWS;
    data.removeAllElements();
    nextEmptyRow = 0;
    if (oldNumRows > START_NUM_ROWS)
    fireTableRowsDeleted(START_NUM_ROWS, oldNumRows - 1);
    fireTableRowsUpdated(0, START_NUM_ROWS - 1);
    * Loads the values into the combo box within the table for mail id
    public void setUpMailColumn(JTable mapTable, ArrayList mailList)
    TableColumn col = mapTable.getColumnModel().getColumn(1);
    javax.swing.JComboBox comboMail = new javax.swing.JComboBox();
    int s = mailList.size();
    for(int i=0; i<s; i++)
    comboMail.addItem(mailList.get(i));
    col.setCellEditor(new DefaultCellEditor(comboMail));
    //Set up tool tips.
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for mail Id list");
    col.setCellRenderer(renderer);
    //Set up tool tip for the mailName column header.
    TableCellRenderer headerRenderer = col.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer)
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the Mail Id to see a list of choices");
    * Loads the values into the combo box within the table for post office id
    public void setUpPostColumn(JTable mapTable, ArrayList postList)
    TableColumn col = mapTable.getColumnModel().getColumn(2);
    javax.swing.JComboBox combo = new javax.swing.JComboBox();
    int s = postList.size();
    for(int i=0; i<s; i++)
    combo.addItem(postList.get(i));
    col.setCellEditor(new DefaultCellEditor(combo));
    //Set up tool tips.
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for post office Id list");
    col.setCellRenderer(renderer);
    //Set up tool tip for the mailName column header.
    TableCellRenderer headerRenderer = col.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer)
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the Post Office Id to see a list of choices");
    }

  • Multiple JButtons inside JTable cell - Dispatch mouse clicks

    Hi.
    I know this subject has already some discussions on the forum, but I can't seem to find anything that solves my problem.
    In my application, every JTable cell is a JPanel, that using a GridLayout, places vertically several JPanel's witch using an Overlay layout contains a JLabel and a JButton.
    As you can see, its a fairly complex cell...
    Unfortunately, because I use several JButtons in several locations inside a JTable cell, sometimes I can't get the mouse clicks to make through.
    This is my Table custom renderer:
    public class TimeTableRenderer implements TableCellRenderer {
         Border unselectedBorder = null;
         Border selectedBorder = null;
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                   boolean hasFocus, int row, int column) {
              if (value instanceof BlocoGrid) {
                   if (isSelected) {
                        if (selectedBorder == null)
                             selectedBorder = BorderFactory.createMatteBorder(2,2,2,2, table.getSelectionBackground());
                        ((BlocoGrid) value).setBorder(selectedBorder);
                   } else {
                        if (unselectedBorder == null)
                             unselectedBorder = BorderFactory.createMatteBorder(2,2,2,2, table.getBackground());
                        ((BlocoGrid) value).setBorder(unselectedBorder);
              return (Component) value;
    }and this is my custom editor (so clicks can get passed on):
    public class TimeTableEditor extends AbstractCellEditor implements TableCellEditor {
         private TimeTableRenderer render = null;
         public TimeTableEditor() {
              render = new TimeTableRenderer();
        public Component getTableCellEditorComponent(JTable table, Object value,
                boolean isSelected, int row, int column) {
             if (value instanceof BlocoGrid) {
                  if (((BlocoGrid) value).barras.size() > 0) {
                       return render.getTableCellRendererComponent(table, value, isSelected, true, row, column);
             return null;
        public Object getCellEditorValue() {
            return null;
    }As you can see, both the renderer and editor return the same component that cames from the JTable model (all table values (components) only get instantiated once, so the same component is passed on to the renderer and editor).
    Is this the most correct way to get clicks to the cell component?
    Please check the screenshot below to see how the JButtons get placed inside the cell:
    http://img141.imageshack.us/my.php?image=calendarxo9.jpg
    If you need more info, please say so.
    Thanks.

    My mistake... It worked fine. The cell span code was malfunctioning. Thanks anyway.

  • Another JTable/buttons in cells query - event forwarding

    Hi Everyone.
    Apologies in advance for yet another thread on this subject. I realise this has been discussed a number of times but I can't find what seems like a definitive solution.
    I understand what the fundamental issue is with putting JComponents in table cells - i.e. that the cells are rendered essentially as static visual entities, that they're not "components" as such and will not receive events.
    I'd like to implement JButtons in table cells so that they behave as "normally" as possible - i.e. handle their own roll-over appearance, handle their own pressed appearance, and fire action events when pressed, with as little manual intervention in these mechanisms (e.g. in mouse listener code) as possible. I'm trying to do this by forwarding mouse events from the table to the button, but this doesn't seem to work as I'd hoped and I have various questions...
    (Background: I have implemented JButton objects in the data model, and the getTableCellRendererComponent() method returns *(JButton)value*.)
    My first question concerns the interception of mouse events. The usual technique would be to add a mouse listener and/or mouse motion listener to the table, and implement mouseClicked(), mousePressed() etc. However, can I override the table's processMouseEvent() and processMouseMotionEvent() methods instead, and from here forward events to buttons where appropriate, or process normally with super.processMouseEvent()? My motivation for doing this would be specifically not to invoke the super methods where events were forwarded to buttons - effectively consuming the event. Is this correct technique?
    My second question concerns attempts to reproduce button roll-over appearances. The JTable is of course considered a single entity as far as mouse events are concerned, and MOUSE_ENTERED and MOUSE_EXITED events aren't generated as the pointer moves from cell to cell. Merely forwarding mouse events to buttons - which will mostly be MOUSE_MOVED events - seems to be insufficient and presumably the roll-over appearance change relies upon ENTERED and EXITED events occurring at the proper times.
    I mimicked this behaviour in my override of processMouseMotionEvent() by calculating the value (i.e. JButton reference) of the cell under the mouse pointer, and if it wasn't the same as for the previous event, manually creating a MOUSE_ENTERED event and forwarding it to the new button. This seemed to work - the rollovers were happening (provided a table repaint() was performed), but it seemed to work without needing to explicitly sending a MOUSE_EXITED to the previous button before sending MOUSE_ENTERED to the new. I'm unclear why this is so - I was half-expecting both buttons to acquire the roll-over state, and they didn't.
    Also, I had assumed that having taken care of this, I should forward MOUSE_MOVED events occurring within the confines of a cell's area to the button verbatim, but this seems to instantly cancel out any roll-over (visually the button would briefly flash a roll-over appearance as the pointer moved into its cell bounds). Why might this be so?
    My last question is about the actual pressing of the button. I had hoped that forwarding MOUSE_CLICKED, MOUSE_PRESSED and MOUSE_RELEASED would cause the button to (a) acquire the button-pressed state, and (b) fire an action event to its action listeners. Neither of these things occur, and I don't understand why not.
    In summary, is interception and forwarding of events like this a viable technique for implementing table cell buttons? The various solutions that a Google trawl throws up all reproduce button-pressing mechanics in varying degrees, some just detecting a click and calling some user function, others manually manipulating the button model in the mouse handler etc. If possible I'd like to avoid this, and leave as much processing as possible to the button's native code.
    Thanks in advance for any suggestions received.
    Regards,
    A.

    try to look on this
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#editrender

  • Adding JButton into JTable cells

    Hi there!!
    I want to add a JButton into JTable cells.In fact I have got two classes.Class2 has been extended from the AbstractTableModel class and Class1 which is using Class2's model,,,here's the code,,
    Class1
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    public class Class1 extends javax.swing.JFrame {
       //////GUI specifications
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new TestTableButton().setVisible(true);
            Class2 model=new Class2();
            jTable1=new JTable(model);
            jScrollPane1.setViewportView(jTable1);
        // Variables declaration - do not modify                    
        private javax.swing.JScrollPane jScrollPane1;
        // End of variables declaration                  
        private javax.swing.JTable jTable1;
    }Class2
    import javax.swing.table.*;
    public class Class2 extends AbstractTableModel{
        private String[] columnNames = {"A","B","C"};
        private Object[][] data = {
        public int getColumnCount() {
            return columnNames.length;
        public int getRowCount() {
            return data.length;
        public String getColumnName(int col) {
            return columnNames[col];
        public Object getValueAt(int row, int col) {
            return data[row][col];
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
         * Don't need to implement this method unless your table's
         * editable.
        public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
                return false;
         * Don't need to implement this method unless your table's
         * data can change.
        public void setValueAt(Object value, int row, int col) {
            data[row][col] = value;
            fireTableCellUpdated(row, col);
    }what modifications shud I be making to the Class2 calss to add buttons to it?
    Can anybody help plz,,,,,??
    Thanks in advance..

    Hi rebol!
    I did search out a lot for this but I found my problem was a bit different,,in fact I want to use another class's model into a class being extended by JFrame,,so was a bit confused,,,hope you can give me some ideas about how to handle that scenario,,I know this topic has been discussed before here many a times and also have visited this link,,
    http://forum.java.sun.com/thread.jspa?threadID=465286&messageID=2147913
    but am not able to map it to my need,,,hope you can help me a bit...
    Thanks .....

  • JButton "sticking" in a JTable Cell

    So I've modified the renderer and what not and slapped a button into a JTable Cell. The assignment requires it to turn red/green altrenativly when pressed. It works perfectly aside from the fact that the buttons appear to not "bounce back" when they switch colors. (i.e. They appear depressed when red and pressed when green). The code is below. any ideas?
    import java.awt.Color;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.JButton;
    public class ButtonTableModel extends AbstractTableModel {
         private static final long serialVersionUID = 1;
         private Object[][] rows = new Object[2][1];
         private String[] columns = new String[1];
         public ButtonTableModel() {
              for(int k = 0; k < rows.length; k++) {
                   JButton button3 = new JButton("222");
                   button3.setSize(200, 200);
                   button3.setBackground(Color.red);
                   button3.addMouseListener(new ColorChanger(button3));
                   rows[k][0] = button3;
              /*button = new JButton("Test Button");
              button.setBackground(Color.red);
              button.addMouseListener(new ColorChanger(button));
              button2 = new JButton("asdf");
              button2.setBackground(Color.red);
              button2.addMouseListener(new ColorChanger(button2));
              rows[0][0] = button;
              rows[1][0] = button2;*/
         private class ColorChanger implements MouseListener {
              private JButton callingButton; //Stores the button that added the Listener
              public ColorChanger(JButton pCallingButton) {  //Constructs a ColorChanger that stores a given JButton
                   callingButton = pCallingButton;
              public void mouseClicked(MouseEvent e) { //When callingButton is clicked, its color changes alternativly to green/red
                   if(isGreen(callingButton) == false)
                        callingButton.setBackground(Color.green);
                   else
                        callingButton.setBackground(Color.red);
              //The 4 methods below are unused leftovers specified by the MouseListener Interface
              public void mouseEntered(MouseEvent arg0) {
              public void mouseExited(MouseEvent arg0) {
              public void mousePressed(MouseEvent arg0) {
              public void mouseReleased(MouseEvent arg0) {
         private boolean isGreen(JButton pButton) { //Returns true if a button's background is green, false otherwise
              if(pButton.getBackground() == Color.green)
                   return true;
              return false;
         public int getColumnCount() { //Returns the number of Columns in a table
              return columns.length;
         public int getRowCount() { //Returns the number of rows in the table
              return rows.length;
         public String getColumnName(int pCollumnIndex) { //Returns the name of the collumn
              return columns[pCollumnIndex];
         public Object getValueAt(int pRow, int pColumn) { //Returns the value at given table coordinates
              return rows[pRow][pColumn];
         public boolean isCellEditable(int pRow, int pColumn) { //Returns true if a cell at given coordinates is editable, false otherwise
                  return false;
         public Class getColumnClass(int pColumnIndex) { //Retrieves the class of the objects in a column
              return getValueAt(0, pColumnIndex).getClass();
    import java.awt.Color;
    import java.awt.Point;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.JTable;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import javax.swing.table.TableCellRenderer;
    public class JButtonJTableTest extends JFrame {
         private static final long serialVersionUID = 1;
         private JTable table;
         private TableCellRenderer tableCellRenderer;
         private MouseEvent e2;
         private Class columnClass;
         private JButton button;
         private Point mousePos;
         private int mouseRow, mouseColumn;
         public JButtonJTableTest() {
              super("JButton Table Test");
              table = new JTable(); //Setup the table, assigning the new renderer and model
              tableCellRenderer = table.getDefaultRenderer(JButton.class);
              table.setDefaultRenderer(JButton.class, new JButtonRenderer(tableCellRenderer));
              table.setModel(new ButtonTableModel());
              table.setGridColor(Color.blue);
              table.addMouseListener(new MouseForwarder());
              table.setShowGrid(true);
              add(table); //Add the table to the content pane
         private class MouseForwarder implements MouseListener {
              public void mouseClicked(MouseEvent e) {
                   mousePos = new Point(e.getX(), e.getY()); //Assing mouse coordinates to a point data structure
                   mouseRow = table.rowAtPoint(mousePos);  //Ascertain the mouse's row & column
                   mouseColumn = table.columnAtPoint(mousePos);
                   if(mouseRow == -1 || mouseColumn == -1)  //Ensure that the column is within the table
                        return;
                   columnClass = table.getColumnClass(mouseColumn); //Ascertain the column's class
                   if(columnClass != JButton.class) //If the class is not JButton, exit MouseForwarder
                        return;
                   button = (JButton)table.getValueAt(mouseRow, mouseColumn); //Access the button where the mouse clicked
                   e2 = (MouseEvent)SwingUtilities.convertMouseEvent(table, e, button); //Forward click to button
                   button.dispatchEvent(e2); //Have button take action
                   table.repaint(); //Repaint the table to ensure proper button animation
              //The 4 methods below are unused methods from the MouseListener Interface
              public void mouseEntered(MouseEvent arg0) {
              public void mouseExited(MouseEvent arg0) {
              public void mousePressed(MouseEvent arg0) {
              public void mouseReleased(MouseEvent arg0) {
         public static void main(String[] args) { //Setup and run the window
              JButtonJTableTest test = new JButtonJTableTest();
              test.setSize(300, 300);
              test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              test.setVisible(true);
    import java.awt.Component;
    import javax.swing.JTable;
    import javax.swing.table.TableCellRenderer;
    public class JButtonRenderer implements TableCellRenderer {
         private TableCellRenderer defaultRenderer;
         private Component jTableButton;
         public JButtonRenderer(TableCellRenderer pRenderer) {
              defaultRenderer = pRenderer;
         public Component getTableCellRendererComponent(JTable pTable, Object pButton, boolean isSelected,
                                                                     boolean hasFocus, int pRow, int pCollumn) {
              try {
                   jTableButton = (Component)pButton;
                   return (Component)pButton;
              catch(ClassCastException exception) {
                   return defaultRenderer.getTableCellRendererComponent(pTable, pButton, isSelected,
                        hasFocus, pRow, pCollumn);
    }

    This question was crossposted into the Swing forum and should be answered there as that is the correct location for it http://forum.java.sun.com/thread.jspa?threadID=753812

  • Jtable on cell changed event

    How can i treat an Jtable on cell changed event, not on value changed

    Do you mean cell selection changed? One way is to add a ListSelectionListener to both the table's and the table's ColumnModel's ListSelectionModels. Something likeListSelectionListener lsl = new ListSelectionListener() {
       public void valueChanged(ListSelectionEvent e) {
          System.out.println(e.getSource());
          ListSelectionModel lsm = (ListSelectionModel) e.getSource();
          if (!lsm.getValueIsAdjusting()) {
             System.out.println("Selection changed");
    table.getSelectionModel().addListSelectionListener(lsl);
    table.getColumnModel().getSelectionModel().addListSelectionListener(lsl);Note that simultaneous change of both row and column will generate two valueChanged events.
    If that's not what you wanted to know, ask a better question.
    [http://catb.org/~esr/faqs/smart-questions.html]
    db

  • Jtable cell listening to mouse event source

    Hi, I have a JTable with single cell selections enabled.
    I can also get the mouseClicked event working, but the cure is worse than the illness, because every cell I click on will cause a jframe to pop-up.
    Ideally only column 0 or 1 listens to the mouseClicked event.
    Can someone please tell mehow to work that into the JTable cell (sorry for the tediously long code, its only a small part)
    import javax.swing.JComponent;
    ...lots of import...
    public class CCYTable extends JPanel
      JTable newtable;
      JLabel tableHeader;
      public CCYFrame NewFrame;
      private boolean DEBUG = false;
      private int showInfoTimer = 10000; // info tip box will pop up for this period of time...
      // if both column and row selection are enabled, then individual cell selection
      // is also enabled.
      private boolean ALLOW_COLUMN_SELECTION = true;
      private boolean ALLOW_ROW_SELECTION = true;
      private boolean clickForDetail = true; // click on cell to launch frame with detail
      protected String[] colHeaderInfo =
        {"Name of Instrument, move mouse to instrument for general detail of service.",
          ...lots of text...
      // get values from database, use an "invisible column" for unique key
      // description, conditions etc from Oracle...
      String LoC = "Letter of Credit";
       ...more variable...
      public void init()
        //setSize(300,300);
        tableHeader = new JLabel("uy or Sell", JLabel.CENTER);
        setLayout(new BorderLayout());
        newtable = new JTable(new TableDefinition())
          //Put cell info here, from Oracle CellInfo varchar2
          public String getToolTipText (MouseEvent mevt)
            String info = null;
            java.awt.Point p = mevt.getPoint();
            int rowIndex = rowAtPoint(p);
            int colIndex = columnAtPoint(p);
            int realColIndex = convertColumnIndexToModel(colIndex);
            Object currentValue = getValueAt(rowIndex, colIndex);
            if (realColIndex == 0)
            { if (currentValue.equals(LoC))
              { info = "Click to read general description of our \"" + LoC + "\" service." ;
              ... ideally I would like to work the mouseClicked listener in here but... 
            return info;
          } // end of JComponent's method getToolTipText
          //Put table header info
          protected JTableHeader createDefaultTableHeader()
            return new JTableHeader(columnModel)
              public String getToolTipText(MouseEvent mevt)
                String tip = null;
                java.awt.Point p = mevt.getPoint();
                int index = columnModel.getColumnIndexAtX(p.x);
                int realIndex = columnModel.getColumn(index).getModelIndex();
                return colHeaderInfo[realIndex];
        if (clickForDetail)
          newtable.addMouseListener(new MouseAdapter()
            public void mouseClicked(MouseEvent mevt)
              { // ...but JTable wants it like this...
                // launch a new pop-up to replace the tool tip box
                NewFrame = new CCYFrame("blabla");
        ToolTipManager.sharedInstance().setDismissDelay(showInfoTimer);
        newtable.setPreferredScrollableViewportSize(new Dimension(770, 350));
        JScrollPane scrollpane = new JScrollPane(newtable);
        initColumnSizes(newtable);
        enableCellSelection(newtable);
        add("North", tableHeader);
        add("Center", scrollpane);
       * For sizing columns. If all column heads are wider than the column-cells'
       * contents, then just use column.sizeWidthToFit().
      private void initColumnSizes(JTable newtable)
        TableDefinition tblmodel = (TableDefinition)newtable.getModel();
        TableColumn column = null;
        Component comp = null;
        int headerWidth=0, cellWidth=0;
        Object[] longValues = tblmodel.longValues;
        TableCellRenderer headerRenderer = newtable.getTableHeader().getDefaultRenderer();
        TableCellRenderer rightRenderer = new RightRenderer();
        for (int i = 0; i < 7; i++)
          column = newtable.getColumnModel().getColumn(i);
          comp = headerRenderer.getTableCellRendererComponent(
                                 null, column.getHeaderValue(),
                                 false, false, 0, 0);
          headerWidth = comp.getPreferredSize().width;
          comp = newtable.getDefaultRenderer(tblmodel.getColumnClass(i)).
                          getTableCellRendererComponent(
                                 newtable, longValues,
    true, true, 0, i);
    cellWidth = comp.getPreferredSize().width;
    column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    TableColumn col2 = newtable.getColumnModel().getColumn(2);
    col2.setCellRenderer( rightRenderer );
    TableColumn col2Width = newtable.getColumnModel().getColumn(2);
    col2Width.setPreferredWidth(2);
    TableColumn col6 = newtable.getColumnModel().getColumn(6);
    col6.setCellRenderer( rightRenderer );
    TableColumn col6Width = newtable.getColumnModel().getColumn(6);
    col6Width.setPreferredWidth(2);
    }// end of method initColumnSizes
    private void enableCellSelection(JTable newtable)
    if (ALLOW_COLUMN_SELECTION)
    if (ALLOW_ROW_SELECTION) {newtable.setCellSelectionEnabled(true);}
    newtable.setColumnSelectionAllowed(true);
    ListSelectionModel colSM = newtable.getColumnModel().getSelectionModel();
    colSM.addListSelectionListener(new ListSelectionListener()
    public void valueChanged(ListSelectionEvent lsevt)
    if (lsevt.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)lsevt.getSource();
    if (lsm.isSelectionEmpty()) {}
    else
    //int selectedCol = lsm.getMinSelectionIndex();
    //NewFrame = new CCYFrame("more blabla!");
    }//end of method enableCellSelection
    ...a lot of code follows...
    TIA :-)

    Hi, thanks for the tip, but I get following compile-time error:
    <identifier> expected
    newtable.addMouseListener(new MouseAdapter()
    .............................................^
    package newtable does not exist
    newtable.addMouseListener(new MouseAdapter()
    ...............^
    2 errors
    And here is how I've modified the code :
    public class CCYTable extends JPanel
      JTable newtable;
      ...lots of variables...
      private boolean ALLOW_COLUMN_SELECTION = true;
      private boolean ALLOW_ROW_SELECTION = true;
      private boolean clickForDetail = true; // click on cell to launch frame with detail
      protected String[] colHeaderInfo =
        {"Name of Instrument, move mouse to instrument for general detail of service.",
          ...lots of text for tooltipbox...
      // get values from database, use an "invisible column" for unique key
      // description, conditions etc from Oracle...
       ...lots more String variables...
      public void init()
        //setSize(300,300);
        tableHeader = new JLabel("Bids and Offers", JLabel.CENTER);
        setLayout(new BorderLayout());
        newtable = new JTable(new TableDefinition())
          //Put cell info here, from Oracle CellInfo varchar2
          public String getToolTipText (MouseEvent mevt)
            String info = null;
            java.awt.Point p = mevt.getPoint();
            int rowIndex = rowAtPoint(p);
            int colIndex = columnAtPoint(p);
            int realColIndex = convertColumnIndexToModel(colIndex);
            Object currentValue = getValueAt(rowIndex, colIndex);
            if (realColIndex == 0)
            { if (currentValue.equals(LoC))
              { info = "Click to read general description of our \"" + LoC + "\" service." ;
            return info;
          } // end of JComponent's method getToolTipText
          newtable.addMouseListener(new MouseAdapter()  //  HELP: compiler throws error here !!!!!!!!
            public void mouseClicked(MouseEvent e)
              java.awt.Point p = mevt.getPoint();
              int rowIndex = rowAtPoint(p);
              int colIndex = columnAtPoint(p);
              int realColIndex = convertColumnIndexToModel(colIndex);
              Object currentValue = getValueAt(rowIndex, colIndex);
              if ((rowIndex == 0) and (colIndex == 0))
                // do stuff for this particular JTable cell ...
          //Put table header info
          protected JTableHeader createDefaultTableHeader()
            return new JTableHeader(columnModel)
              public String getToolTipText(MouseEvent mevt)
                String tip = null;
                java.awt.Point p = mevt.getPoint();
                int index = columnModel.getColumnIndexAtX(p.x);
                int realIndex = columnModel.getColumn(index).getModelIndex();
                return colHeaderInfo[realIndex];
        ToolTipManager.sharedInstance().setDismissDelay(showInfoTimer);
        newtable.setPreferredScrollableViewportSize(new Dimension(770, 350));
        JScrollPane scrollpane = new JScrollPane(newtable);
        initColumnSizes(newtable);
        enableCellSelection(newtable);
        add("North", tableHeader);
        add("Center", scrollpane);
      }On the other hand, this code works after a fashion but it is not what is needed because it listens to every JTable cell :
    public class CCYTable extends JPanel
      JTable newtable;
      ...unbelievably more variable definitions, etc...
      public void init()
        //setSize(300,300);
        tableHeader = new JLabel("Bids and Offers", JLabel.CENTER);
        setLayout(new BorderLayout());
        newtable = new JTable(new TableDefinition())
          //Put cell info here, from Oracle CellInfo varchar2
          public String getToolTipText (MouseEvent mevt)
            String info = null;
            java.awt.Point p = mevt.getPoint();
            int rowIndex = rowAtPoint(p);
            int colIndex = columnAtPoint(p);
            int realColIndex = convertColumnIndexToModel(colIndex);
            Object currentValue = getValueAt(rowIndex, colIndex);
            if (realColIndex == 0)
            { if (currentValue.equals(LoC))
              { info = "Click to read general description of our \"" + LoC + "\" service." ;
                if (rowIndex == 0)  // HELP:  compiles okay but won't specifically select rowIndex == 0 and colIndex == 0
                {this.addMouseListener(new clickListener(newtable, rowIndex, colIndex));
            return info;
          } // end of JComponent's method getToolTipText
         ... lots more code...
      // ==============================
      class clickListener extends MouseAdapter
        private JTable newtable;
        private int rowIndex;
        private int colIndex;
        public clickListener(JTable newtable, int rowIndex, int colIndex)
          this.newtable = newtable;
          this.rowIndex = rowIndex;
          this.colIndex = colIndex;
        public void mouseClicked(MouseEvent mevt)
          NewFrame = new CCYFrame("blablabla");
      }// end of method clickListenerIdeally I should be able to use a selection criteria like this :
    java.awt.Point p = mevt.getPoint();
    rowIndex = rowAtPoint(p);
    colIndex=colAtPoint(p);
    if ((rowIndex == 0) && (colIndex == 0)) {//do something}but this is going to be a bad Chrissy for me?

  • Rendering multiple objects in JTable cells

    Hi,
    I wish to render in a single JTable cell (actually all cells in a Column) an ImageIcon and it's associated description string. The description string should be rendered below the ImageIcon, as it's caption. How can this be done? I assume a custom cell renderer, but the details are muddy at this point.
    thanks!
    JPL

    Thanks.
    I have looked atthe tutorial, but it focuses on a single object type per cell - I've got two different types (an ImageIcon and a String) that will occupuy a single cell.
    Taking a conceptual leap here, is it possible to create a new TableCellRenderer that houses a JPanel and GridLayout, and then place an ImageIcon and JLabel into that panel? I guess as long as things are JComponents, should I be OK with this approach?
    thanks,
    jpl

Maybe you are looking for

  • To create folder in Application server

    hi, How to create folder in application server from presentation server?? how is the program it?? reply me soon... thx, s.suresh.

  • How can I store received email in a folder on my iPad *

    How can I store received email in a folder on my iPad * I am trying to save certain messages on my iPad but don't know how to make a folder with email!

  • How to run Windows on top of Linux

    Just an idea for those of you who are using Linux but still need to run Windows XP or Vista for one reason or another. When I bought my machine, I immediately reformatted the HD getting rid of Vista and all of that other prebundeled junk that made my

  • What's wrong with my feed - episode 2 !

    Hi, I thought it was fixed but it still persists ... I don't understand what's wrong with my feed : http://www.dailyfrenchpod.com/wordpress/feed With iTunes 7 : - my page on iTunes shows all my episodes (and you can download each episode, one by one)

  • Hyperlink set to open new window & jump to anchor tag, doesn't jump

    I am generating Flash Help output in RH7. We have content hyperlinks that are set to open in a new window (target="_blank") and jump to an anchor tag in the destination topic (a href="newwindowtopic.htm#anchor") This works fine if I compile the file