Question

Is there anyway i can get Jtable from the tabbed panel selected.

I creat tables dynamically for every tab selected using this code:

     JScrollPane panel2 = new JScrollPane();
                panel2.setName(tabidis);


               chattable = new JTable();
               chattable.setModel(new javax.swing.table.DefaultTableModel(new Object [][] {},new String [] {"Messages"}));
               panel2.setViewportView(chattable);
               chattable.setShowGrid(false);

               jTabbedPane1.add(username4, panel2);



//I am using GUI environment in netbeans. 

I think the hierarchy as follows:

JTabbedPanel1 >> JscrollPAnel1 >> Jtable1

By using the following code:

((JTable)jTabbedPane1.getSelectedComponent().getComponentAt(1,1).getComponentAt(0,0)).getName();

I get the error that "javax.swing.table.JTableHeader cannot be cast to javax.swing.JTable"

That means that i am getting jTable Header as the component. But what i need is to get JTable as the component outcome so to get the model from it.

Or more simply "Is there anyway to get the model of a JTable present in the selected tab"

Was it helpful?

Solution

This seems to work:

@Test
public void test() {

    // original components
    JTable jTable = new JTable();
    JScrollPane scrollPane = new JScrollPane(jTable);

    // add them to tab
    JTabbedPane jTabbedPane = new JTabbedPane();
    jTabbedPane.addTab("tab1", scrollPane);
    jTabbedPane.setSelectedComponent(scrollPane);

    // get them out of selected tab
    JScrollPane scrollRef = (JScrollPane) jTabbedPane.getSelectedComponent();
    JTable tableRef = (JTable) scrollRef.getViewport().getComponents()[0];

    assertTrue(tableRef == jTable);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top