0

I've created a JTable whose columns contain a variety of different components. The last five columns either contain nothing (a DefaultTableCellRenderer with no value) or a JRadioButton using a custom renderer and editor. The renderer creates and returns a new radioButton in the cells I need one, and I want to access these radio buttons from my panel class to add them to a ButtonGroup. I am using the following piece of code that I wrote:

protected void setButtonGroups() {
    buttonGroups = new ArrayList<ButtonGroup>();
    for (int i = 0; i < tableModel.getRowCount(); i++) {
        ButtonGroup currentGroup = new ButtonGroup();
        for (int j = 0; j < tableModel.getColumnCount(); j++) {
            if (table.getComponentAt(i, j) != null) {
                    currentGroup.add((JRadioButton)table.getComponentAt(i, j));
                }
            }
        }
        buttonGroups.add(currentGroup);
    }
}

getComponentAt() keeps returning null regardless of what is contained in the cell, whether it be a JCheckBox, JRadioButton, JComboBox... everything is returned as null.

Is there an alternative way to get the cell's component? Or is there a way for me to get this to work? Thank you!

Duffluc
  • 27
  • 2
  • 6
  • 1
    The `getComponentAt` method refers to "pixel coordinates", not to the cells of the table. Usually, the cells of the table are rendered with a renderer, but such a renderer (usually) uses the *same* component for *all* cells of one column (it's used like a "stamp", only for painting the cell contents - the components are not really "there"). You mentioned that you are creating new buttons in the renderer. This may cause problems, because the buttons may be re-created each time they are painted. You should add the code of your button-based renderer/editor (preferably, a compilable example) – Marco13 May 16 '14 at 22:59
  • @Marco13 Yes you are right. – Braj May 16 '14 at 23:03
  • Use a combination of JTabel#getCellRenderer and TableCellRenderer#getTableCellRendererCoomponent. This will return the physical component used by the JTable, if that render then contains sub components, you will need to further inspect the renderer component – MadProgrammer May 16 '14 at 23:39
  • Several alternatives are cited [here](http://stackoverflow.com/q/11154378/230513). – trashgod May 17 '14 at 04:20

1 Answers1

0

If you have a tableModel from table.getModel(). Then you can call model.getValueAt(row,col)

I am not sure why you are putting Swing Components inside a JTable. Are you using it for formatting? If so look into LayoutManagers. If you want to edit values in a table, you might want to look into extending TableCellEditor. If you really want to put components in your table. Consider extending the DefaultTableCellRenderer to return your component. You will want to override getTableCellRendererComponent().

HowYaDoing
  • 820
  • 2
  • 7
  • 15