Getting the TableModel of a JTable

Hi there!
I've got a JTable that was created via a class JCatalogTable that extends a so called JAbstractTable (this class extends JTable). In JCatalogTable the AbstractTableModel is set via super(TableModel) to the JAbstractTable. The AbstractTableModel is not the "normal" AbstractTableModel but a class called CatalogTableModel extending the AbstractTableModel.
This classes are all extending the normal Model because they display a special type of data. However, there is Method in the CatalogTableModel I have to call. My problem now is to get the Model to call the method.
What I have is an instance of JAbstractTable (a JTable). But I can only get the standard AbstractTableModel, if I try to cast to the CatalogTableModel I get a ClassCastException. Maybe anyone understands what I want and can give me a hin how to solve.
At last, here is my relevant code:
// jt_c is the JTable I'm working on
         JAbstractTable jat_c = (JAbstractTable) jt_c;
         AbstractTableModel atm_jat_c = (AbstractTableModel) jat_c.getModel(); // this works
         CatalogTableModel ctm_jat_c = (CatalogTableModel) atm_jat_c; // this gives a class cast exception

Well, it prints
class data.swing.CatalogTableModelBut I now wrote a get-Method in the JAbstractTable getATM()
    public AbstractTableModel getATM() {
         return atm; // atm is declared in the whole class
    }and then with
CatalogTableModel cm = (CatalogTableModel) jat_c.getATM();I have the CatalogTableModel.
Thanks for your contributions!

Similar Messages

  • Swing: when trying to get the values from a JTable inside an event handler

    Hi,
    I am trying to write a graphical interface to compute the Gauss Elimination procedure for solving linear systems. The class for computing the output of a linear system already works fine on console mode, but I am fighting a little bit to make it work with Swing.
    I put two buttons (plus labels) and a JTextField . The buttons have the following role:
    One of them gets the value from the JTextField and it will be used to the system dimension. The other should compute the solution. I also added a JTable so that the user can type the values in the screen.
    So whenever the user hits the button Dimensiona the program should retrieve the values from the table cells and pass them to a 2D Array. However, the program throws a NullPointerException when I try to
    do it. I have put the code for copying this Matrix inside a method and I call it from the inner class event handler.
    I would thank you very much for the help.
    Daniel V. Gomes
    here goes the code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import AdvanceMath.*;
    public class MathF2 extends JFrame {
    private JTextField ArrayOfFields[];
    private JTextField DimOfSis;
    private JButton Calcular;
    private JButton Ativar;
    private JLabel label1;
    private JLabel label2;
    private Container container;
    private int value;
    private JTable DataTable;
    private double[][] A;
    private double[] B;
    private boolean dimensionado = false;
    private boolean podecalc = false;
    public MathF2 (){
    super("Math Calcs");
    Container container = getContentPane();
    container.setLayout( new FlowLayout(FlowLayout.CENTER) );
    Calcular = new JButton("Resolver");
    Calcular.setEnabled(false);
    Ativar = new JButton("Dimensionar");
    label1 = new JLabel("Clique no bot�o para resolver o sistema.");
    label2 = new JLabel("Qual a ordem do sistema?");
    DimOfSis = new JTextField(4);
    DimOfSis.setText("0");
    JTable DataTable = new JTable(10,10);
    container.add(label2);
    container.add(DimOfSis);
    container.add(Ativar);
    container.add(label1);
    container.add(Calcular);
    container.add(DataTable);
    for ( int i = 0; i < 10 ; i ++ ){
    for ( int j = 0 ; j < 10 ; j++) {
    DataTable.setValueAt("0",i,j);
    myHandler handler = new myHandler();
    Calcular.addActionListener(handler);
    Ativar.addActionListener(handler);
    setSize( 500 , 500 );
    setVisible( true );
    public static void main ( String args[] ){
    MathF2 application = new MathF2();
    application.addWindowListener(
    new WindowAdapter(){
    public void windowClosing (WindowEvent event)
    System.exit( 0 );
    private class myHandler implements ActionListener {
    public void actionPerformed ( ActionEvent event ){
    if ( event.getSource()== Calcular ) {
    if ( event.getSource()== Ativar ) {
    //dimensiona a Matriz A
    if (dimensionado == false) {
    if (DimOfSis.getText()=="0") {
    value = 2;
    } else {
    value = Integer.parseInt(DimOfSis.getText());
    dimensionado = true;
    Ativar.setEnabled(false);
    System.out.println(value);
    } else {
    Ativar.setEnabled(false);
    Calcular.setEnabled(true);
    podecalc = true;
    try {
    InitValores( DataTable, value );
    } catch (Exception e) {
    System.out.println("Erro ao criar matriz" + e );
    private class myHandler2 implements ItemListener {
    public void itemStateChanged( ItemEvent event ){
    private void InitValores( JTable table, int n ) {
    A = new double[n][n];
    B = new double[n];
    javax.swing.table.TableModel model = table.getModel();
    for ( int i = 0 ; i < n ; i++ ){
    for (int j = 0 ; j < n ; j++ ){
    Object temp1 = model.getValueAt(i,j);
    String temp2 = String.valueOf(temp1);
    A[i][j] = Double.parseDouble(temp2);

    What I did is set up a :
    // This code will setup a listener for the table to handle a selection
    players.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    ListSelectionModel rowSM = players.getSelectionModel();
    rowSM.addListSelectionListener(new Delete_Player_row_Selection(this));
    //Class will take the event and call a method inside the Delete_Player object.
    class Delete_Player_row_Selection
    implements javax.swing.event.ListSelectionListener
    Delete_Player adaptee;
    Delete_Player_row_Selection (Delete_Player temp)
    adaptee = temp;
    public void valueChanged (ListSelectionEvent listSelectionEvent)
    adaptee.row_Selection(listSelectionEvent);
    in the row_Selection function
    if(ex.getValueIsAdjusting()) //To remove double selection
    return;
    ListSelectionModel lsm = (ListSelectionModel) ex.getSource();
    if(lsm.isSelectionEmpty())
    System.out.println("EMtpy");
    else
    int selected_row = lsm.getMinSelectionIndex();
    ResultSetTableModel model = (ResultSetTableModel) players.getModel();
    String name = (String) model.getValueAt(selected_row, 1);
    Integer id = (Integer) model.getValueAt(selected_row, 3);
    This is how I got info out of a table when the user selected it

  • How can I get the JCheckBox value in JTable?

    I have a JTable with JCheckBox inside. How can I get the value when the user turn on or off the check? I need to do this when the user change the value.
    Thanks for any help.
    Renato

    Hi again,
    no - the datamodel is a class that implements the TableModel-interface - if you do not use your own model in JTable, an instance of DefaultTableModel is used - you can subclass DefaultTableModel and overwrite its setValueAt(...)-method. When you instantiate your JTable do it by passing your DefaultTableModel subclass to the constructor or in the way you do it right now and replace the default model with your model using the setModel(...)-method of JTable.
    greetings Marsian

  • How to get the data from a jtable with random order??

    hi everyone,
    i have a jtable i filled with Strring and Float data, i put this data to a MySQL database, and i use vectors and iterators to filled the database. the problem is there are some cells that are empty, and the Floats' columns throws me nullpointerexceptions.
    please if anyone know how to avoid that exception i'd would be great.
    thanks for your time.

    HI Siggi,
    Thank you for your reply..
    I am also planning to do FM to get the data. But it is saying that the Cluster table ZES does not exist (ZES is the the standard table, in SE11 also).
    How can I use the Fields from the that table.?
    What can I do now, can you please explain me about this point.
    Waiting for your reply.
    Thanks and Regards
    Rajesh
    Message was edited by:
            rajesh

  • Cant get the last row in jtable

    Hello all.
    I am trying to get the last row from the table but get "" from it.
    my table has 6 rows and i can get all rows right but the last line I have a problem.
            //creating the table
        for (i=0;i<this.rows;i++)
         model.insertRow(i,new Object[]{"input Y1:",""});
                for ( i=i;i<this.Amount+this.rows;i++)
         model.insertRow(i,new Object[]{"input Amount:",""});
    //end of creatingthis code creats the table that i need and its works right.
    for(i=0;i<rows;i++){
                  fObj.fullData[i] = Double.valueOf(GetData(table, 1, i).toString()).doubleValue();
            int j=0;
            String s=GetData(table, 1, 4).toString();
            //the problem line
            String s1=GetData(table, 1, 5).toString();
        public Object GetData(JTable table, int col_index, int row_index){
        return table.getModel().getValueAt(row_index, col_index);
      }this line i get ""
    String s1=GetData(table, 1, 5).toString();
    Edited by: vitaly87 on 00:41 08/04/2011

    vitaly87 wrote:
    Hello all.
    I am trying to get the last row from the table but get "" from it.
    my table has 6 rows and i can get all rows right but the last line I have a problem.
    this line i get ""
    String s1=GetData(table, 1, 5).toString();Looks right to me, given that your insert ismodel.insertRow(i,new Object[]{"input Amount:",""});(Hint: indexes start at *0* ).
    If it hadn't found the row, I expect you would have got an Exception
    Winston

  • Getting the Difference in JTables my algo is messed

    Im trying to get the difference of two JTables...in other words if Table B has the rowdata of Table A, then Table C should not have it...Table C should have all the data in Table A - the data in Table B
    heres my code:
    //in a subclass of JTable
    public Object[][] getDifferenceData(JTable table){
        DefaultTableModel thisModel = (DefaultTableModel)this.getModel();
        DefaultTableModel userModel = (DefaultTableModel)table.getModel();
        int differenceRows = thisModel.getRowCount() - userModel.getRowCount();
        Object[][] newData = new Object[differenceRows][2];
        Object symbol = new Object();
        Object description = new Object();
         for (int i=0; i<differenceRows; i++){
            for (int j=0; j<userModel.getRowCount()-1; j++){
                if ((symbol = thisModel.getValueAt(i,0)) != userModel.getValueAt(j,0)){
                    //symbol in portfolio model != symbol in user portfolio
                    //so new difference table model should have it
                    description = thisModel.getValueAt(i,1);
                    newData[0] = symbol;
    newData[i][1] = description;
    return newData;
    heres what im trying to do
    1) new Data[][] is set to size bigger table row count - smaller tables
    for all new row size
    2)compare table A data in the current row and first column to all the rows/first column of table B
    3) if the data is NOT the same, the copy that row data from Table A into a new 2D data vector to the appropriate row
    4) return the new data[][] for new jtable creation
    but what happens is that the difference table (C) contains the corrent number of rows...but it still contains the data found in table B, and the new table C is just table C with the right number of rows cut off
    my algo is severly messed :)
    any help would be appreciated..thanks

    hey klepto,
    your not using .equals() on the symbol Object, this means that all it is doing is seeing if they refer to the same instance of the object, not if the to instances have the same value.
    The other problem is that you presume that the difference of the two collections is based on their respective size. What if they contain totaly different values? Then the total size would be the sum of both collections.
    Lets presume that the symbol is a String. Then I would do the following:
    //in a subclass of JTable
    public Object[][] getDifferenceData(JTable table, DefaultTableModel thisModel, DefaultTableModel userModel){
        Object[][] newData = null;
        String symbolA = null;
        String symbolB = null;
        String description = null;
        SymbolData symbolData = null;
        Vector newList = new Vector();
        int nbrRowsA = thisModel.getRowCount();
        int nbrRowsB = userModel.getRowCount();
        for(int i = 0; i < nbrRowsA; i++) {
            symbolA = (String)thisModel.getValue(i, 0);
            for(int j = 0; j < userModel.getRowCount() - 1; j++) {
                symbolB = (string)userModel.getValue(i, 0);
                if(!symbolA.equals(symbolB)){
                    description = (String)thisModel.getValueAt(i,1);
                    newList.add(new SymbolData(symbol, description));
        if(newList.size() > 0) {
            int size = newList.size();
            newData = new String[size][2];
            for(int i = 0; i < size; i++) {
                symbolData  = (SymbolData)newList.get(i);
                newData[0] = symbolData.getSymbol();
    newData[i][1] = symbolData.getDescription();
    return newData;
    class SymbolData {
    String symbol;
    String description;
    MyDataClass(String symbol, String description) {
    this.symbol = symbol;
    this.description = description;
    String getSymbol() {
    return symbol;
    String getDescription() {
    return description;
    String[] getData() {
    String[] data = new String[2];
    data[0] = symbol;
    data[1] = description;
    return data;
    Hmm, that should do the job. Not the fastest code, I'm sure there
    could be some improvements with the array handling. But it should
    get you started.
    Also I have not attempted to compile the above so I suspect you
    will find problems (only on a good day do I get zero compile errors
    when I first write something, good days are rare :-) ).
    James.

  • How can I get the edited value from the editor in JTable

    I have a JTextField added as an editor to a cell in JTable.
    I value gets changed when I press enter.
    but in actionPerformed of the JTextField when I say
    String txtEditorValue = txtEditor.getText();
    I am getting the old value. How can I get the edited value? Thanks.

    Hi,
    I guess, your understanding of how JTable works together with its models is not good enough - for example the method getTableCellEditorComponent(...) of the TableCellEditor interface is used to get the component, that should be used as editing component - its second parameter is a value that should be used to setup the editing component - it is normally not the editing component itself.
    JTable uses an underlying TableModel to store the cell values - if you have edited a cell, JTable gets the value of the editing component by itself and stores it in the TableModel using its setValueAt(...) method. To retrieve this data you only need to query the TableModel using row and column of this cell as parameters
    say jt is your JTable, and row and column are the row and column of the cell - so to get the value, simply use
    Object obj = jt.getModel().getValueAt(row,column);
    if you know, that there is a String in this cell use
    String str = (String) jt.getModel().getValueAt(row,column);
    The editor component is used for the view of the JTable - you only want the data, which is stored in the model - you don't have to deal with the GUI components in this case.
    greetings Marsian

  • (JTable) How can i get the first columns cell in a selected row?

    Hello. I am trying to figure out how i can get the first columns cell within a selected row no matter what cell is selected in that row. I have a class that extends AbstractTableModel which represents the table. Now i have another class that extends DefaultSelectionModel. Each model is added to the JTable via setModel(TableModel dataModel), setSelectionModel(ListSelectionModel newModel). Now i don't understand what i have to return from getMaxSelectionIndex(). Any ides? Thanks.
      class xTableModel extends AbstractTableModel{
         private static String[] cols;
         private Object[][] data;
            public void setTableModel(Object data[][], String[] cols){
             this.cols = cols;
             this.data = data;
            public String getColumnName(int col){
             return cols[col];
            public int getRowCount() {
             return data.length;
            public Object getValueAt(int row, int col) {
             return data[row][col];           
            public void setValueAt(Object value,int row,int col){
             data[row][col]=value;
            public int getColumnCount(){
             return cols.length;
    class ColumnListenerModel extends DefaultListSelectionModel{
         public int getMaxSelectionIndex(){}

    int row = table.getSelectedRow();
    Object data = table.getValueAt(row, 0);

  • How can i get the component value which is in jtable

    hi all,
    i have a JTable and i added JSpinner component in 1st column.
    i want to get the value of the component.
    i tried to get the value using the following code
    for(int i=0;i<5;i++)
    ((JSpinner)tableDisbursals.getEditorComponent().getComponentAt(i,1)).getValue()it throwing NullPointerException
    is that correct? what i did
    thanks in advance
    daya

    hi all,
    thanks for replay
    the following code is demo
    import hivosCommonMain.function.ComProperties;
    import hivosCommonMain.function.FillCompFN;
    import java.awt.Component;
    import java.util.Date;
    import java.util.Vector;
    import javax.swing.AbstractCellEditor;
    import javax.swing.JFrame;
    import javax.swing.JSpinner;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellEditor;
    public class SpinnerDemo extends JFrame{
         DefaultTableModel tableModel;
         JTable table;
         private String[] columnNames = {"First Name",
                "Last Name",
                "Sport",
                "# of Years",
                "Vegetarian"};
         private Object[][] data = {
                   {"Mary", "12/Aug/2005",
                   "Snowboarding", new Integer(5), new Boolean(false)},
                   {"Alison", "12/Aug/2005",
                   "Rowing", new Integer(3), new Boolean(true)},
                   {"Kathy", "12/Aug/2005",
                   "Knitting", new Integer(2), new Boolean(false)},
                   {"Sharon", "12/Aug/2005",
                   "Speed reading", new Integer(20), new Boolean(true)},
                   {"Philip", "12/Aug/2005",
                   "Pool", new Integer(10), new Boolean(false)}
         public SpinnerDemo(){          
            tableModel     = new DefaultTableModel(data, columnNames);
            table   = new JTable(tableModel) {
                 public boolean isCellEditable(int row, int col) {
                      return true;
            table.getColumnModel().getColumn(1).setCellEditor(new MyCellEditor());
            Component c = table.getEditorComponent();
            Component c2 = c.getComponentAt(1, 0);
            JSpinner spinner = (JSpinner)c2;       
            System.out.println(spinner.getValue());
            getContentPane().add(table);
            setVisible(true);
            pack();
         public static void main(String args[]){
              new SpinnerDemo();
         class MyCellEditor extends AbstractCellEditor implements TableCellEditor {
              JSpinner sDate;
              Object value;
              public MyCellEditor() {
                   sDate = new JSpinner(FillCompFN.getJSpinnerModel());
                   sDate.setEditor(new JSpinner.DateEditor(sDate, ComProperties.DATE_FORMAT));
                   ((JSpinner.DefaultEditor)sDate.getEditor())
                                       .getTextField().setHorizontalAlignment(JTextField.RIGHT);
                   sDate.setOpaque(true);
              public Object getCellEditorValue() {
                   return ((JSpinner.DefaultEditor)sDate.getEditor())
                        .getTextField().getText();
              public Component getTableCellEditorComponent(JTable table,
                   Object value,
                   boolean isSelected,
                   int row,
                   int column) {
                   this.value = value;
                   try{
                        if(value.toString().length() > 0)
                             ((JSpinner.DefaultEditor)sDate.getEditor())
                             .getTextField().setText(value.toString());
                        else
                             sDate.setValue(new Date());
                   }catch(Exception e){
                        e.printStackTrace();
                        sDate.setValue(new Date());
                   return sDate;
    }

  • Getting the user input from a JTables Columns

    Hello
    I am having real trouble with this could someone please help?
    I have to columns on my JTable (first name , lastname).
    How can I loop though each column like this?
    the first column (first names), and get each row and add it to a String array?
    for example if the user puts in 10 firstnames I want to add all 10 to a string array.
    and for the second column, I want to add all the rows (last names ), to a arraylist. so if the user puts in 10 lastnames, I want to add them to the arraylist.
    How can I do this?
    thanks
    bobby

    JTable table = new JTable();
    TableModel model = table.getModel();
    int row = 0;
    int col = 0;
    //You can loop using the line below to get the values for each cell
    //I'm casting it as a String, if you don't have a String, you can leave
    // it as an Object
    String s = (String) model.getValueAt(row, col);

  • How to get the value from a cell in jTable without click "enter" or "tab"

    Hi guys,
    I have a simple question. I have a jTable in my screen and when editing a value, but without click "enter" or "tab" I want to get the new value. I have a button update and after editing the value I click the button "update" and I want the new value to be store in my table. If try to get the selected value it is giving the old value. How can I implement this? Any idea? I hope I was clear.
    Thanks

    [Table Stop Editing|http://www.camick.com/java/blog.html?name=table-stop-editing]

  • How to get the last value edited by users from JTable?

    Hi.
    I have a JDialog that includes an editable JTable. This table is used to set up field caption and font for a report program. I found only when cursor is moved to another cell, the value in current cell being edited will be transferred to Table Model. So if the user don�t move cursor to another cell after editing the value of a cell but click OK button directly, Table Model cannot get the last value edited by the user, I wonder if there is a way to fire JTable to transfer the value being edited to Table model.
    By the way, I found if the TableCellEditor is using JCheckBox or JComboBox instead of JTextField, there is no this problem.
    Thank you for any reply.

    I guess you can make use of the following methods on your table model to inform it make it getValueAt bcos table data has changed.
    fireTableCellUpdated
    Notifies all listeners that the value of the cell at [row, column] has been updated.
    fireTableChanged
    Forwards the given notification event to all TableModelListeners that registered themselves as listeners for this table model.
    fireTableDataChanged
    Notifies all listeners that all cell values in the table's rows may have changed. The number of rows may also have changed and the JTable should redraw the table from scratch. The structure of the table (as in the order of the columns) is assumed to be the same.
    But when to call these methods??
    -- When OK button is pressed, do this as the first thing!!
    OR
    -- Call this on every key event!!
    regds,
    CA

  • How to get the coordinate of a cell in the jtable?

    How to get the coordinate of a cell in the jtable?
    How to get the point of a cell in the jtable?
    Thanks for help!

    getCellRect(...);

  • How to get the default selection color from JTable

    Hi, there,
    I have a question for how to get the default selection color from JTable. I am currently implementing the customized table cell renderer, but I do want to set the selection color in the table exactly the same of default table cell renderer. The JTable.getSelectionBackgroup() did not works for me, it returned dark blue which made the text in the table unreadable. Anyone know how to get the window's default selection color?
    Thanks,
    -Jenny

    The windows default selection color is dark blue. Try selecting any text on this page. The difference is that the text gets changed to a white font so you can actually see the text.
    If you don't like the default colors that Java uses then use the UIManager to change the defaults. The following program shows all the properties controlled by the UIManager:
    http://www.discoverteenergy.com/files/ShowUIDefaults.java
    Any of the properties can be changed for the entire application by using:
    UIManager.put( "propertyName", value );

  • JTable problem : how to get the last value entered by user + event lost

    Hi all,
    I have 2 problems with Jtable class.
    1 => To get the last value entered by user in a cell,
    it seems that we must change the selected cell.
    That is to say we can only have the previous cell's value.
    Is there a simple way to get the current value of any cell ?
    2 => To resolve the problem i store the values of each cell in a vector and i intercept keyboard event (!)
    BUT, when i do a double click with the mouse on the Jtable, i loose keyboard events. Then, i can't intercept them.
    Is it a bug of swing or am i following a wrong way ?
    Thanks by anticipation for your help.

    You have to fire the "TableCellUpdatedEvent"
    and override the getCellEditorValue in TableCellEditor to return the current value

Maybe you are looking for

  • Plugging XSLT / XML processors into Business Connector 4.7

    Hi, I need to use Xalan 2.6.0 and the associated XML parsers in the Business Connector. Does anyone know whether any built-in services or SAP Adapter services would be negatively impacted by this change? I have found nothing in the documentation. (Am

  • Error in Creating Excise Invoice for Factory Sale

    Dear Friends: Using T.code J1IIN ( Create Excise invoice for Factory Sale), I entered data for billing doc,posting date,sub transaction type & pressed enter and tried to save it.I got the error 'Error in allocating internal document number interval n

  • Problem with recognition

    I have a 1st gen nano. It sometimes doesn't get recognized fora while but now it hasn't been recognized by the computer or any other device I try to connect it to for longer than 12 hours, which has never been the case before. I am starting to worry

  • Problem burning a DVD

    I just recently got a MacBook, and am loving it so far. However, I have encountered my first problem. I was burning a DVD using iDVD, and after about a minute, it got very, very noisy, and made unusual noises as well, not what I was used to hearing w

  • Black line appearing when using Magic Bullet

    I have installed the latest Magic Bullet suite and it all works fine within Premiere, except when I apply a Look. In the Looks Builder the image looks fine. However, when I go back to Premiere a black line appears on the left hand side of the image.