Editing JTables

When exactly does the isEditing() method of a JTable return FALSE, following a user edit?
I have a table with four columns, the first three of which have JComboBoxes as DefaultCellEditors, while the last column has a custom editor allocated dependent on the combo box item selected in the second column. (It's a Query Builder!) The custom editors are/will be modelled upon the ColorEditor example in Sun's How To Use Tables guide.
I want to disable some JButtons whenever a cell in the table is being edited, and re-enable them whenever the edit stops.
I attempted that by testing isEditing() in the valueChanged method of a TableModelListener. However, it's always TRUE.
I over-rode the editingStopped() method of my extended JTable class, and I can see that isEditing() does eventually become FALSE.
I guess that answers my question, but... I can't see how I can implement the behaviour that I need. Any suggestions folks?

I'm sure you don't want to be a personal mentor... but could I ask you to assist me further with my JTable QueryBuilder? I guess it can't hurt to ask.
The Builder seems to be fully functional, loading other custom editors (including JTextFields, JComboBoxes, and JTrees) into the "value" column, as appropriate to the selection in the "field" column.
There seems to be one last problem though... well, that I've found. I'll try to describe it.
Clicking for a second time in the 'hot' (display) area of the JComboBox editor for the "field" column after bringing up the list causes the the list to disappear, and the 'hot' area to be in editable mode. Fine. But then attempting to click in any of the other table cells causes the following exception:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.plaf.basic.BasicTableUI$Handler.setDispatchComponent(BasicTableUI.java:852)
at javax.swing.plaf.basic.BasicTableUI$Handler.adjustFocusAndSelection(BasicTableUI.java:923)
at javax.swing.plaf.basic.BasicTableUI$Handler.mousePressed(BasicTableUI.java:889)
at java.awt.AWTEventMulticaster.mousePressed(AWTEventMulticaster.java:222)
at java.awt.Component.processMouseEvent(Component.java:5485)
I'm sure my code is causing it, and I suspect that somehow it's related to the way I'm re-setting the editor in the "value" column for that row. I don't know if it's a good idea, but I'm doing that in the setValueAt() method of my TableModel class. Whenever I detect a change in value in the "field" cell, I reset the editor in the "value" cell, and ascribe a new default value to that cell.
The exception is only thrown when attempting to move from the "field" column to any another column. It cannot be reproduced performing the same behaviour in the other columns.
I'd be happy to provide code if you are willing to help. Cheers.

Similar Messages

  • FocusTraversalPolicy in an editable JTable

    Hello,
    does anyone have an example how to use a FocusTraversalPolicy in an editable JTable, that uses user defined cell editors?
    Any hint or example is appreciated.
    Thank you,
    Fritz

    Ok - using the editor you will know when editing has stopped, (enter used). so it would seem logical to have it trigger the event.
    However.... your tablemodel will now also have to determinine which is the next logical cell to move to by stepping through the model:
    isCellEditable() or some such to stop at that cell... ?

  • How to edit jtable programmatically?

    id like to know how to edit jtable cell programmatically.
    thanks!

    override
    getTableCellEditorComponent in customized
    TableCellEditor.Hi,
    hmm ... if that's that, what he want to know? - I guess, he wants to know how to change values of the JTable by program.
    Every JTable has an underlying TableDataModel that holds the values of the tablecells. You can retrieve this model by the getModel()-method of the JTable.
    To get a value from the model use method getValueAt(row,column) of the model.
    To set a value in the model use method setValueAt(object,row,column) of the model.
    See the TableModel-interface-Documentation for other methods.
    greetings Marsian

  • Editable jtable inside a jtree

    I want to create an editable jtable inside a jtree. can anyone show me how to do it? thank you.

    I want to create an editable jtable inside a jtree. can anyone show me how to do it? thank you.

  • Problem with Starting Edit JTable after Enter Pressed

    Hi.
    Who knows what to do in such case:
    I have JTable. When I press ENTER on Cell - the editing process must begin, like it happens when I make Double Click on Cell.

    The KeyStroke to invoke editing on a cell is the "F2" key. So you want to map the Enter Action to be the same as the F2 Action.
    This posting shows how to remap the Action for the Enter key:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=505866

  • Dynamically Rendering and editing JTable cell

    Hi all,
    I wonder if some body can help me.
    As in my application each cell in Jtable returns java Object. and what i am trying to do is based on each object returned in cell my renderer is going to change dynamically. for example if the object returned is primitive data types the renderer is defualt, if the returned object is Map, Set or List, then the Cell Renderer should show clickable button with icon on right hand side and TextField on left hand side and so on for other objects. i am able get renderer for Map, set or list, which is button on right hand side of cell and text field on left hand side displaying toString of Object. then what i want is when i click button it should show those values in popup window and if i double click it should edit the cell which i am able to do it. so how can i handle events or what i have to do to make button clickable. if any body come accross these situations or got idea. please let me know how to move further.
    Thanks,
    Kotesh.

    Hi,
    Thanks for your advise and as i said i am able to get render for Map as (TextField in left hand side+Button with icon in right hand side side) of Cell. but what i need is when i click button which is on right hand, then i should be able to show popup wvindow with map values and if i double click on TextField which is on right hand side, then i should be able to edit Cell which is happening. but i am not able to get popup window when i click button on right hand side of cell. basically i am not sure how to handle events on cell and the button on right hand side?
    if some one can guide me that will be great as i am in big trouble.
    Thanks
    Kotesh.

  • Non-editable JTable cells?

    Is there any way to make all the cells in a JTable non-editable? In the API I see the isEditable method, but no setEditable method. Any suggestions?

    You have to set it in the TableModel.
    TableModel model = new AbstractTableModel()
    public int getRowCount()
    return 10;
    public int getColumnCount()
    return 5;
    public Object getValueAt(int row, int column)
    return "( "+row+","+column+" )";
    public boolean isCellEditable(int row,int column)
    return false;
    The one given above is a sample to show you how to set a cell non-editable on the cell. You have to customize it for your table model.
    Thanks,
    Kalyan

  • Edit JTable Date Cell, press Enter, the Time Cell changes to GMT time!

    Has anyone seen this strange behavior? I try to edit a Date Cell in JTable (orig. value 10/02/2000) and change it to (10/03/2000), I press Enter. But, the value of my Time Cell in the next column, same row which I never edited (orig. value 00:05:00) changes to approximately my system time in GMT (16:28:48).
    This is an excerpt from my TableModel which get called from setValueAt():1734 javax.swing.JTable, JTable.java. In the code below, the debug statement prints out:
    row, col = 0,0
    Value in SubTableModel = 10-02-2000 16:28:48
    Value should be "10-02-2000" since I did not edit the time cell at all. And why is row and col both zero?
    public void setValueAt(Object value, int row, int col) {
    try {
    ((ITableCellAdapter)adapters.get(col)).setData(getRow(row),col);
    System.out.println("row, col = " + row + col);
    System.out.println("Value in SubTableModel = " + value.toString());
    ((ITableCellAdapter)adapters.get(col)).setValue(value);
    catch (PropertyVetoException badSet) {
    System.out.println("could not set value");
    fireTableCellUpdated(row,col);
    How can I force it to set the date cell's new value only and leave the time cell alone?
    I've also seen that sometimes my date entry gets lost, the old value still showing, what am I doing wrong? I've seen a bunch of bug parade listings about terminating edits within a JTable being buggy, is this related?
    Any help on this is most appreciated!

    Did you find the solution to yuor problem?
    Has anyone seen this strange behavior? I try to edit
    a Date Cell in JTable (orig. value 10/02/2000) and
    change it to (10/03/2000), I press Enter. But, the
    value of my Time Cell in the next column, same row
    which I never edited (orig. value 00:05:00) changes to
    approximately my system time in GMT (16:28:48).
    This is an excerpt from my TableModel which get called
    from setValueAt():1734 javax.swing.JTable,
    JTable.java. In the code below, the debug statement
    prints out:
    row, col = 0,0
    Value in SubTableModel = 10-02-2000 16:28:48
    Value should be "10-02-2000" since I did not edit the
    time cell at all. And why is row and col both zero?
    public void setValueAt(Object value, int row, int
    nt col) {
    try {
    ((ITableCellAdapter)adapters.get(col)).setData(getRow(
    ow),col);
    System.out.println("row, col = " + row +
    + row + col);
    System.out.println("Value in SubTableModel = "
    del = " + value.toString());
    ((ITableCellAdapter)adapters.get(col)).setValue(value)
    catch (PropertyVetoException badSet) {
    System.out.println("could not set value");
    fireTableCellUpdated(row,col);
    How can I force it to set the date cell's new value
    only and leave the time cell alone?
    I've also seen that sometimes my date entry gets lost,
    the old value still showing, what am I doing wrong?
    I've seen a bunch of bug parade listings about
    terminating edits within a JTable being buggy, is
    this related?
    Any help on this is most appreciated!

  • Updating resultsets using vectors in editable JTables

    Ok i am currently retrieveing my result from a vector of vectors from a query:
    public void presentResultSet (ResultSet rs)throws SQLException {
    Vector dataVector=new Vector();
    try
    {if (!rs.next())
        JOptionPane.showMessageDialog(null, " No records for student" );
      else {
        do{
         Vector rowVector=new Vector();
         rowVector.addElement(rs.getString("studentID"));
         rowVector.addElement(rs.getString("moduleID"));
         rowVector.addElement(rs.getString("examMark"));
         dataVector.addElement (rowVector);
        }while(rs.next());
    } tab.setData(dataVector);
    dataTableScrollPane.setViewportView(dataTable);}
    catch (Exception f){ System.out.println (f.getMessage());
    This method is fine actually as it displays the results onto my GUI. But problem is, i want to add another feature of the system where users can click on any cells in the JTable, edit it and JTable will be able to help me update it onto my tables in mysql.
    I have set the public boolean iseditable into true.
    but can anyone tell me how to write the public void setValueAt method ? how to retrieve that information that the user type into the particular cell and update it onto the database ? Please help !

    Ok I assume because your using a JTable that you are using your own TableModel because the DefaultTableModel usually won't do everything you want. So if your not extending DefaultTableModel you need to start there.
    In your Table model you need a method called setValueAt which will overide the DefaultTableMode.setValueAt().
    Your TableModel's setValueAt() will get called by the table Cell Renderer when ever a cell is edited.
    So to break down setValueAt(Object aValue,int aRow,int aColumn)
    Object aValue = is whatever the user has entered in the Cell. Now its an Object and not a String because you can have all sort of things in a JTable Cell such as checkboxes,buttons, etc.
    The int Row and int Column are pretty self explanitory.
    I don't know what your table looks like but lets say you have have 3 columns
    StudentID,ModuleID,ExamMark you could do something like this
    public void setValueAt(Object aValue,int aRow,int aColumn)
            // In your table model there should be some Vector that contains your other 
            // Vectors. In this example "rows" is that Vector
           // this assigns rowVector the Vector of Columns at the row
           // that was edited by the user in the JTable. It should contain the 3 columns
           Vector rowVector = (Vector)rows.elementAt(aRow);
            // this will overwrite the current value at that column
            rowVector.setElementAt(aValue,aColumn );
            // you may need to cast aValue into whatever Object you plan on storing probably a string
            // ie. rowVector.setElementAt((String)aValue,aColumn );
    } Your Table Model should now contain the new value in its rows Vector all you have do is add someway to save that new Vector back into the Database.
    Hope this helps I didn't compile it but I think it will work or at least give you a better understanding....
    Or maybe I confused you more.
    Good Luck
    Justin

  • Start or stop edit jtable cell editing

    Hello,
    I got a problem with the jtable DefaultModel isCellEditable.
    If I set the IsCellEditable to false, I would not be able to enable the cell selection as and when I want it.
    What I have in mind is the add a mouselister so that if the user select a row using fast left mouse click like the procedure shown below
    private class MouseClickHandler extends MouseAdapter {
    public void mouseClicked(MouseEvent event) {
    int no_mouseclick = 0;
    no_mouseclick = event.getClickCount();
    if (no_mouseclick >= 2) {
    int cur_row = 0;
    cur_row = table.getSelectedRow();
    // table.setColumnSelectionAllowed(true);
    // table.setRowSelectionAllowed(true);
    for (int i=0;i<table.getColumnCount();i++){
    table.editCellAt(cur_row,i);
    System.out.println("mouse row--->" + cur_row);
    I could overwrite the IsCellEditable to true to enable that particular or cell contains in that row to be able to accept input and overwrite any data which in my case obtained from the Sql database a sort of like input module using tabulation . I am also thinking of using text component or combobox to display the value for user selection , but I do not know how to enable a particular cell for editing if the Jtable created is using a non-editable DefaultModel. If I set the IsCellEditable to true, every single cell would be enable for editing , and this defeat the purpose of enable user input only upon double mouseclicks.
    By the way , I am interested to know how to track the data changes in the cell within the jtable so that only those have been modified are notify from the Table model and updated into the Sql table
    Could anyone of you out there provide some hints please
    Thanks

    Hello,
    Tablemodellistener could detect the changes in the data, how about the backend database updating and transactional activity that must be associated with the data changes?
    What is on my mind is that , the moment there is changes in the data detected by the TableModellistener, whatever records associated with or brougt up by Jtable would be all deleted from the database and then follow by the new set of new records to be inserted into the database. The disadvantage of this method is that everytime the backend database connection and activity need to be executed the moment there is a change in the data in the jtable cell. For example the user may be just amendment to only one cell , but all the records associated need to be deleted and then inserted again.
    Perhaps there are better solution to deal with Jtable and JDBC backend connection where in this case, I am using JDO to undertake the database activity like the observable modelling .
    Could someone provide the hint please
    Thank

  • Un-Editable JTable

    Hey,
    I have been looking at the API and other forms and I can not figure out a way to do the following. I have a table that I have that displays data that I retrieve from a database. However I want the user to be able to click inside the table and select the rows/cells, however I do not want them to be able to edit the individual cells. Is there any way to make this table 'clickable' (or 'selectable') however not editable? I can not seem to find anything other than isCellEditable(int row, int col) for JTable.
    Any help would be appreciated.
    Thanks

    You're almost there. Override isCellEditable() to return false.
    db
    edit For exampleJTable table = new JTable(10, 5) {
        @Override
        public void isCellEditable(int row, int column) {
            return false;
    }Edited by: Darryl.Burke

  • Edit JTable Cell

    Hi,ALL
    I have create normal JTable.and set all cell Editable.
    When I double clike a cell, I can modify the value on the cell.
    However, When I use getValueAt(row, col)
    it still give me the orginal value, not the modified value!
    Do I lost something? Or do I need to implement something else?
    any idea would be greated appreciated

    It may also depend on when you're calling getValueAt. If you're doing it before the edit has committed to the table model (ie, before setValueAt has been called) then the underlying data won't yet have been updated.
    It would be useful if you could supply some example code for what you're trying to do (post it in [ code ] tags please!).
    Hope this helps.

  • Set a focus in an editable jtable

    Please i have a jframe which contains a jtable editable. J programmed it in such way that when I click on TAB the following cell will be selected.
    Although that this cell will be selected whereas the focus does not viewed;
    When I type some characters by the keyboard they will be taken into account by the cell,
    I would like to see the focus as if i click by the mouse on the cell.
    Thanks you for your help

    Swing related questions should be posted in the Swing forum.
    Maybe my reply here is what you are looking for:
    http://forum.java.sun.com/thread.jspa?threadID=509229&tstart=0

  • Problem in editing JTable fields.....

    Hi there!!
    I have got 2 classes in my package,one contains a public static JTable while the other has got some variables whose values I want the JTable's fields to populate with.Now the problem I have is that I can't populate the JTable's fields after making it's class's object and accessing the JTable using that object...Can anybody help plz?
    Thanks...

    Hi Cantry!!
    I'm embedding my code in this post,,had to simplify the code as my application's code may not have been understandable,,,
    Here's the code
    //THIS IS THE CLASS CONTAINING JTable
    import java.sql.*;
    import java.util.StringTokenizer;
    import javax.swing.JOptionPane;
    import javax.swing.JTextField;
    import javax.swing.*;
    public class Test_GUI extends javax.swing.JFrame {
        /** Creates new form Test_GUI */
        public Test_GUI() {
            initComponents();
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                     
        private void initComponents() {
            jScrollPane1 = new javax.swing.JScrollPane();
            jTable1 = new javax.swing.JTable();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("New Allocations");
            jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4"
            jScrollPane1.setViewportView(jTable1);
            org.jdesktop.layout.GroupLayout layout = new
    org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(57, 57, 57)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 344,
    org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(106, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(55, 55, 55)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 143,
    org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(247, Short.MAX_VALUE))
            pack();
        }// </editor-fold>                       
         * @param args the command line arguments
        public static void main(String args[]) {
            Test_GUI tg2=new Test_GUI();
            tg2.SetTableValues();
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Test_GUI().setVisible(true);
            try
    javax.swing.UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    catch(Exception e)
                        e.printStackTrace();
            Test_GUI tg=new Test_GUI();
            tg.setVisible(true);
        // Variables declaration - do not modify                    
        private javax.swing.JScrollPane jScrollPane1;
        public static javax.swing.JTable jTable1;
        // End of variables declaration                  
        private javax.swing.JTextField jTextField6;
        public static void SetTableValues()
            System.out.println("here");
            Data_Class dc=new Data_Class();
            jTable1.setValueAt(dc.Test_data,0,0);
    and code from the other calss,,,
    //CLASS FROM WHERE I'M FETCHING THE DATA
    public class Data_Class {
        static String Test_data="testdata";
        /** Creates a new instance of Data_Class */
        public Data_Class() {
    }thanks in advance...

  • Edit JTable and Send Info To DB!!!!!  Duke$$$$

    hi,
    I have an Applet that contains JTable.
    I am retriveing person information from DB to jTable...
    Once i click on the JTable i want to change the value in the JTable cell and click the Update button to update that info in db...
    Can someone please guide me on how this can be done...
    If possible if someone can post a simple code or post where i can get an example like this...
    Again Thanks for any help..
    Sam

    take a look at this code.
    import javax.swing.JTable;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class SimpleTableDemo extends JFrame implements TableModelListener {
    private boolean DEBUG = true;
    javax.swing.table.TableModel modela;
    public SimpleTableDemo() {
    super("SimpleTableDemo");
    Object[][] data = {
    {"Mary", "Campione",
    "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", "Huml",
    "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", "Walrath",
    "Chasing toddlers", new Integer(2), new Boolean(false)},
    {"Mark", "Andrews",
    "Speed reading", new Integer(20), new Boolean(true)},
    {"Angela", "Lih",
    "Teaching high school", new Integer(4), new Boolean(false)}
    String[] columnNames = {"First Name",
    "Last Name",
    "Sport",
    "# of Years",
    "Vegetarian"};
    final JTable table = new JTable(data, columnNames);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    modela = table.getModel();
    modela.addTableModelListener(this);
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this window.
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    public void tableChanged(TableModelEvent e){
    int row = e.getFirstRow();
    int column = e.getColumn();
    Object firstname = modela.getValueAt(row, 0);
    Object lastname = modela.getValueAt(row, 1);
    Object sport = modela.getValueAt(row, 2);
    Object years = modela.getValueAt(row, 3);
    Object veg = modela.getValueAt(row, 4);
    System.out.println();
    System.out.println(firstname);
    System.out.println(lastname);
    System.out.println(sport);
    System.out.println(years);
    System.out.println(veg);
    System.out.println();
    public static void main(String[] args) {
    SimpleTableDemo frame = new SimpleTableDemo();
    frame.pack();
    frame.setVisible(true);
    hope this helps

Maybe you are looking for