JTABLE - FocusEvent on CelEditor!

Hi, I�m have a little problem: when im editing a cell in jtable and then i click in a button, the cellEditor do not do the event to update my TableModel, resuming: its like i did not have typed anything in table!
I really need help... i guess that its missing some focusEvent, like lostFOcusEvent in CellEditor, then when exit the celleditor (do not passing by the jTable, going right away to the Button) the celleditor fire the fireEditingStopped() event.
I just have no ideia how to do it....
Ice

Are you calling stopCellEditing()?
On the action of the button try doing this.
row = table.getEditingRow();
col = table.getEditingColumn();
if (row != -1 && col != -1)
table.getCellEditor(row,col).stopCellEditing();
Hope this helps...

Similar Messages

  • Java.awt.IllegalComponentStateException in JTable

    Hi folks,
    I am trying to write a JTable cell validation. Input data in a cell, if failure, prompt message and set focus & editing back to the cell. I've tried InputVerifier() but it doesn't work since I can easily use the mouse click to shift to other cells in the same table.
    What I am trying to do now is to define my DefaultCellEditor. I record the row & index position when getting focus. In the lost focus event, do the validation and set the focus & editing back if failure. Seems it works fine. However, when I randomly click different cells in the table quickly. It prompts:
    "java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location"
    Here is my stack dump:
         at java.awt.Component.getLocationOnScreen_NoTreeLock(Component.java:1487)
         at java.awt.Component.getLocationOnScreen(Component.java:1461)
         at javax.swing.Autoscroller.mouseDragged(Autoscroller.java:79)
         at javax.swing.JComponent.processMouseMotionEvent(JComponent.java:2759)
         at java.awt.Component.processEvent(Component.java:4822)
         at java.awt.Container.processEvent(Container.java:1525)
         at java.awt.Component.dispatchEventImpl(Component.java:3526)
         at java.awt.Container.dispatchEventImpl(Container.java:1582)
         at java.awt.Component.dispatchEvent(Component.java:3367)
         at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.repostEvent(BasicTableUI.java:475)
         at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.mouseDragged(BasicTableUI.java:554)
         at java.awt.AWTEventMulticaster.mouseDragged(AWTEventMulticaster.java:258)
         at java.awt.AWTEventMulticaster.mouseDragged(AWTEventMulticaster.java:257)
         at java.awt.AWTEventMulticaster.mouseDragged(AWTEventMulticaster.java:257)
         at java.awt.Component.processMouseMotionEvent(Component.java:5069)
         at javax.swing.JComponent.processMouseMotionEvent(JComponent.java:2763)
         at java.awt.Component.processEvent(Component.java:4822)
         at java.awt.Container.processEvent(Container.java:1525)
         at java.awt.Component.dispatchEventImpl(Component.java:3526)
         at java.awt.Container.dispatchEventImpl(Container.java:1582)
         at java.awt.Component.dispatchEvent(Component.java:3367)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3359)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3091)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3004)
         at java.awt.Container.dispatchEventImpl(Container.java:1568)
         at java.awt.Window.dispatchEventImpl(Window.java:1581)
         at java.awt.Component.dispatchEvent(Component.java:3367)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:445)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:191)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:144)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:130)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:98)
    Also, enclosed is my modified DefaultCellEditor class. Your input will be greatly appreicated. Thanks.
    class NewDefaultCellEditor extends DefaultCellEditor {
    public NewDefaultCellEditor(JTextField jTextField) {
    super(jTextField);
    this.setClickCountToStart(1);
    jTextField.addFocusListener(new FocusAdapter() {
    JTable tbl;
    int row;
    int column;
    public void focusGained(FocusEvent e) {
    tbl = (JTable)((JTextField)e.getSource()).getParent();
    row = tbl.getEditingRow();
    column = tbl.getEditingColumn();
    public void focusLost(FocusEvent e) {
    /*** Put validation here, execute the following if failed ***/
    tbl.editCellAt(row, column);
    ((JTextField)e.getSource()).requestFocus();

    Your use in a JTable isn't too clear to me, but I feel you're overthinking the basic requirement:
    I have an extended JComboBox which is meant to display its information only. Thus it
    - does not allow any selection
    - shows the first item of the list in the TextField only and not once more in the listI don't see the need for duplicating the model and using a popup menu listener.
    import java.awt.Component;
    import javax.swing.*;
    public class DisplayOnlyComboBoxDemo {
      public static void main(String[] args) throws Exception {
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            new DisplayOnlyComboBoxDemo().makeUI();
      public void makeUI() {
        JFrame frame = new JFrame();
        frame.add(new DisplayOnlyComboBox("One", new String[]{"Two", "Three", "Four", "Five"}));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    class DisplayOnlyComboBox extends JComboBox {
      private String firstItem;
      public DisplayOnlyComboBox(String firstItem, String[] items) {
        super(items);
        this.firstItem = firstItem;
        setRenderer(new DefaultListCellRenderer() {
          @Override
          public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            if (index == -1) {
              setText(DisplayOnlyComboBox.this.firstItem);
            return this;
    }db

  • Tab and back-tab out of a JTable

    Hi There,
    I have been working for some time on improving the default behaviour of the tab key within editable JTables. It largely works as required now, but I'm stuck on getting back-tab to leave the table if on row 0, col 0. I register tab and back-tab action in the table's ActionMap that looks like this:     
         class TabAction extends AbstractAction {
              public void actionPerformed(ActionEvent e) {
                   if (getRowCount() > 0) {
                        int row = getSelectedRow();
                        int column = getSelectedColumn();
                        if (row < 0 || column < 0) {
                             row = 0;
                             column = 0;
                        do {
                             if (++column >= getColumnCount()) {
                                  row++;
                                  column = 0;
                        } while (row < getRowCount() && ! isCellTabbable(row, column));
                        if (row < getRowCount()) {
                             changeSelection(row, column, false, false);
                        } else {
                             clearSelection();
                             transferFocus();
                   } else {
                        transferFocus();
         class BackTabAction extends AbstractAction {
              public void actionPerformed(ActionEvent e) {
                   if (getRowCount() > 0) {
                        int row = getSelectedRow();
                        int column = getSelectedColumn();
                        if (row < 0 || column < 0) {
                             row = getRowCount() - 1;
                             column = getColumnCount() - 1;
                        do {
                             if (--column < 0) {
                                  row--;
                                  column = getColumnCount() - 1;
                        } while (row >= 0 && ! isCellTabbable(row, column));
                        if (row >= 0) {
                             changeSelection(row, column, false, false);
                        } else {
                             clearSelection();
                             transferFocusBackward();
                             KeyboardFocusManager fm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
                                // fm.upFocusCycle(BTTTable_Editable.this);                         
                             // fm.focusPreviousComponent(BTTTable_Editable.this);
                   } else {     
                        // transferFocusBackward();
                        // KeyboardFocusManager fm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
                           // fm.upFocusCycle(BTTTable_Editable.this);                         
                        // fm.focusPreviousComponent(BTTTable_Editable.this);
         }transferFocus() to go to the next screen component works fine - as long as I callsetFocusTraversalPolicyProvider(true); when I create the JTable.
    But the backward traversal just doesn't work - instead it does nothing the first time you press back-tab on row 0 col 0, then if you press it again, focus goes onto the last row/col of the table.
    As an alternative, I thought maybe I could call the Ctrl-back-tab action, but I can't find that registered in the action map - can anyone tell me how ctrl-back-tab is called and whether I can call that code directly?
    Any ideas?
    Thanks,
    Tim

    Where's the rest of your code? What good does posting
    the Actions do if we can't execute your code and see
    how you've installed the Actions on the table? Who
    knows where the mistake is. It may be in the posted
    code or it may be in some other code.Well I assume the Action is registered okay because back-tab within the table works fine, and in fact using a debugger I can see that the focus request code (transferFocusBackward) is being called at the right time. I followed it into that code and it appears that it is picking up the tableCellEditor as the "previous" component which is "why" it isn't working right - not that that helps me to fix it.
    Anyway, just to confirm, here is a complete standalone testcase:import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.KeyboardFocusManager;
    import java.awt.event.ActionEvent;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import java.awt.event.InputEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.AbstractAction;
    import javax.swing.ActionMap;
    import javax.swing.InputMap;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.KeyStroke;
    * <br>
    * <br>
    * Created on 14/11/2005 by Tim Ryan
    public class TabTable extends JTable implements FocusListener {
         protected KeyStroke TAB = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
         protected KeyStroke BACK_TAB = KeyStroke.getKeyStroke(KeyEvent.VK_TAB,
                   InputEvent.SHIFT_DOWN_MASK);
         protected KeyStroke LEFT_ARROW = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0);
         protected KeyStroke RIGHT_ARROW = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0);
         public TabTable(Object[][] rowData, Object[] columnNames) {
              super(rowData, columnNames);
              initialise();
         public TabTable() {
              super();
              initialise();
         private void initialise() {
              addFocusListener(this);
              InputMap inMap = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
              ActionMap actionMap = getActionMap();
              inMap.put(LEFT_ARROW, "None");
              inMap.put(RIGHT_ARROW, "None");
              actionMap.put(inMap.get(TAB), new TabAction());
              actionMap.put(inMap.get(BACK_TAB), new BackTabAction());
              setCellSelectionEnabled(true);
              putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
              setFocusTraversalPolicyProvider(true);
         public void focusGained(FocusEvent e) {
              if (getRowCount() > 0 && getSelectedRow() < 0) {
                   editCellAt(0, 0);
                   getEditorComponent().requestFocusInWindow();
         public void focusLost(FocusEvent e) {
         public void changeSelection(int row, int column, boolean toggle, boolean extend) {
              super.changeSelection(row, column, toggle, false);
              if (editCellAt(row, column)) {
                   getEditorComponent().requestFocusInWindow();
          * This class handles the back-tab operation on the table.
          * It repeatedly steps the selection backwards until the focus
          * ends up on a cell that is allowable (see <code>isCellTabbable()</code>).
          * If already at the end of the table then focus is transferred out
          * to the previous component on the screen.
         class BackTabAction extends AbstractAction {
              public void actionPerformed(ActionEvent e) {
                   if (getRowCount() > 0) {
                        int row = getSelectedRow();
                        int column = getSelectedColumn();
                        if (row < 0 || column < 0) {
                             row = getRowCount() - 1;
                             column = getColumnCount() - 1;
                        do {
                             if (--column < 0) {
                                  row--;
                                  column = getColumnCount() - 1;
                        } while (row >= 0 && ! isCellTabbable(row, column));
                        if (row >= 0) {
                             changeSelection(row, column, false, false);
                        } else {
                             clearSelection();
                             // transferFocusBackward();
                             KeyboardFocusManager.getCurrentKeyboardFocusManager().focusPreviousComponent();
                   } else {
                        // transferFocusBackward();
                        KeyboardFocusManager.getCurrentKeyboardFocusManager().focusPreviousComponent();
          * This class handles the tab operation on the table.
          * It repeatedly steps the selection forwards until the focus ends
          * up on a cell that is allowable (see <code>isCellTabbable()</code>).
          * If already at the end of the table then focus is transferred out
          * to the next component on the screen.
         class TabAction extends AbstractAction {
              public void actionPerformed(ActionEvent e) {
                   if (getRowCount() > 0) {
                        int row = getSelectedRow();
                        int column = getSelectedColumn();
                        if (row < 0 || column < 0) {
                             row = 0;
                             column = 0;
                        do {
                             if (++column >= getColumnCount()) {
                                  row++;
                                  column = 0;
                        } while (row < getRowCount() && ! isCellTabbable(row, column));
                        if (row < getRowCount()) {
                             changeSelection(row, column, false, false);
                        } else {
                             clearSelection();
                             transferFocus();
                   } else {
                        transferFocus();
          * Some cells can be tabbed to, but are not actually editable.
          * @param row
          * @param column
          * @return
         private boolean isCellTabbable(int row, int column) {
              return (column % 2 == 0);
         public boolean isCellEditable(int row, int column) {
              return (column == 1 || column == 3);
          * @param args
         public static void main(String[] args) {
              JFrame frame = new JFrame("Tables test");
              frame.setName("TablesTest");
              frame.setSize(600, 400);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JPanel panelMain = new JPanel(new GridBagLayout());
              frame.add(panelMain);
              Object[][] tableData = new Object[2][6];
              Object[] columnHeadings = new Object[] {"H0", "H1", "H2", "H3", "H4", "H5"};
              GridBagConstraints gbc = new GridBagConstraints();
              gbc.anchor = GridBagConstraints.NORTH;
              gbc.insets = new Insets(10, 10, 10, 10);
              JTextField field1 = new JTextField("left", 8);
              field1.setName("left");
              panelMain.add(field1, gbc);
              Dimension tableSize = new Dimension(300, 300);
              BTTTable table3 = new BTTTable_Editable(tableData, columnHeadings);
              table3.setName("Editable");
              JScrollPane scroll3 = new JScrollPane(table3);
              scroll3.setPreferredSize(tableSize);
              panelMain.add(scroll3, gbc);
              JTextField field2 = new JTextField("right", 8);
              field2.setName("right");
              gbc.gridwidth = GridBagConstraints.REMAINDER;
              panelMain.add(field2, gbc);
              frame.setVisible(true);
    }I thought it might be the focusGained() code, but commenting that out makes no difference.
    And here is the code I would use to go to the
    previous component:
    KeyboardFocusManager.getCurrentKeyboardFocusManager().
    focusPreviousComponent();I tried that too, as you can see from my original post. It gives the same answer.
    So the big question is why does the FocusManager think that the "previous" field to the table is an editor component within the table?
    Regards,
    Tim

  • How do I get Integer in JTable cell to be selected when edit using keyboard

    I have some cells in a JTable, when I double-click on the cell to edit it the current value (if any) is selected and is replaced by any value I enter, which is the behaviour I want. But when I use the keyboard to navigate to the cell and start editing, new values are added to the end of the current value which is not what I want.
    I have created my own IntegerCellEditor (see below) and added a focus event or the textfield used when editing to select all the current text but it has no effect, any ideas please ?
    public class IntegerCellEditor extends DefaultCellEditor
        public IntegerCellEditor( JTextField textfield )
            super( textfield );    
            //Ensure old value is always selected, when start editing
            ((JTextField)getComponent()).addFocusListener(new FocusAdapter()
                    public void focusGained(FocusEvent fe){
                        ((JTextField)getComponent()).selectAll();
            ((JTextField)getComponent()).setHorizontalAlignment(JTextField.RIGHT);
         * Return as Integer (because delegate converts values to Strings).
        public Object getCellEditorValue()
            return Integer.valueOf((String)delegate.getCellEditorValue());
    }

    But when I use the keyboard to navigate to the cell and start editing,
    new values are added to the end of the current value which is not what I want.How does the use know that typing will replace the text and not append? Usually if text is to be deleted, it is highlighted to give the user a visual cue.
    Here is a renderer that does this, in case your interested:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=752727

  • About JCheckBox in a JTable.

    Hi,
    In my JTable, one of the column uses checkbox as cell editor.
    I like to know how to get the row index of the row where the clicked checkbox is in.
    Thanks
    Stephen

    Hi,
    TableColumnModel tcm = jTable1.getColumnModel();
    JUTableLOVEditor jTableLOVEditor = (JUTableLOVEditor) tcm.getColumn(0).getCellEditor();
    JComboBox component = (JComboBox) jTableLOVEditor.getComponent();
    component.addFocusListener(new FocusListener(){
    public void focusGained(FocusEvent e) {
    DCIteratorBinding dciter = (DCIteratorBinding)panelBinding.get("EmployeesView1Iterator");
    System.out.println(dciter.getCurrentRowIndexInRange());
    public void focusLost(FocusEvent e) {
    Frank

  • Password column in a JTable

    I want the values entered in a column to have "***********" i.e as password, instead of actually displaying the text . How can I do this? Thanks.

    Thanks for you response. I got it working now. but I have another question.
    I see the JPasswordField added when the table gets displayed. I want it to be added only when I click on it. what can I modify to get this.
    tblConnections =
    new JTable(tm) {
    public String getToolTipText(MouseEvent e) {
    Point pt = e.getPoint();
    int column = columnAtPoint(pt);
    int row = rowAtPoint(pt);
    if (column > -1 && row > -1) {
    String tooltipString = "";
    Project project = ProjectSet.getProject();
    IconData iconData = (IconData) tblConnections.getValueAt(0, 0);
    String connectionName = (String)iconData.getData();
    List connectionList = project.getDefaultConnections();
    for (java.util.Iterator itr = connectionList.iterator(); itr.hasNext(); ) {
    Connection connection = (Connection) itr.next();
    if ((connection.getName()).equals(connectionName)) {
    tooltipString = "Connector" + " = " + connection.getName() + "\n"
    + "Type" + " = " + connection.getDataType() + "\n"
    + "Server" + " = " + connection.getDataServerName();
    tooltipString = "<html><pre>" + tooltipString + "</pre></html>";
    return tooltipString;
    } else {
    return (null);
    public TableCellRenderer getCellRenderer(int row, int column) {
    TableColumn tableColumn = getColumnModel().getColumn(column);
    TableCellRenderer renderer = tableColumn.getCellRenderer();
    if (renderer == null) {
    Class c = getColumnClass(column);
    if (c.equals(Object.class)) {
    Object o = getValueAt(row, column);
    if (o != null) {
    c = getValueAt(row, column).getClass();
    renderer = getDefaultRenderer(c);
    if(column == (tblConnections.getColumnModel().getColumnIndex("Password"))) {
    MyRenderer myRenderer = new MyRenderer();
    return myRenderer;
    if(column == (tblConnections.getColumnModel().getColumnIndex("Connection Name"))) {
    TextWithIconCellRenderer renderer1 = new TextWithIconCellRenderer();
    return renderer1;
    return renderer;
    public TableCellEditor getCellEditor(final int row, final int column) {
    DefaultCellEditor defaultEditor;
    if (column == (tblConnections.getColumnModel().getColumnIndex("Password"))) {
    MyCellEditor editor = new MyCellEditor();
    editor.addCellEditorListener(this);
    editor.getPasswordField().addFocusListener(
    new FocusListener() {
    public void focusGained(FocusEvent e) { }
    public void focusLost(FocusEvent e) {
    tblConnections.setValueAt(((JPasswordField) (e.getSource())).getPassword(), row, column);
    tblConnections.getCellEditor().stopCellEditing();
    return editor;
    } else if (column == (tblConnections.getColumnModel().getColumnIndex("Userid"))) {
    JTextField txtField = new JTextField();
    defaultEditor = new DefaultCellEditor(txtField);
    defaultEditor.addCellEditorListener(this);
    txtField.addFocusListener(
    new FocusListener() {
    public void focusGained(FocusEvent e) { }
    public void focusLost(FocusEvent e) {
    tblConnections.setValueAt(((JTextField) (e.getSource())).getText(), row, column);
    tblConnections.getCellEditor().stopCellEditing();
    return defaultEditor;
    return null;
    Thanks.

  • How to get name of a Component retuned by FocusEvent.getOppositeComponent()

    Hi,
    I have three instances of JTable named table1, table2, table3 and one button. For the button I have FocusListener which listens to focusGained event. The FocusEvent enables me to get the Component which has lost the focus by e.getOppositeComponent(). Now my question: how can I understand which instance is that component table1, table2, or table3? getName(), getAccessibleContext().getAccessibleName() return nulls. I SIMPLY WANT TO KNOW WHICH TABLE LOST FOCUS WHEN BUTTON WAS PRESSED.
    Thanks

    if you have the object use if (component instanceof table1) .....
    Noah

  • JTable JCombox popup on click in table cell

    What is the recommended way of making a JComboBox that is in a JTable cell popup when the user clicks once anywhere in the cell?
    The popup is actually a calendar that works fine if the user clicks on the spot where the button shows up in the cell but sets the focus in the text box of the JComboBox is the click is anywhere else in the cell and the popup doesn't sho in that case. To get to the popup requires a click on the button.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test extends JFrame {
      public Test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        String[] head = {"One","Two","Three"};
        String[][] data = {{"R1-C1","R1-C2","R1-C3"},
                           {"R2-C1","R2-C2","R2-C3"},
                           {"R3-C1","R3-C2","R3-C3"}};
        JTable jt = new JTable(data, head);
        content.add(new JScrollPane(jt), BorderLayout.CENTER);
        JComboBox jcb = new JComboBox(head);
        jcb.addFocusListener(new FocusAdapter() {
          public void focusGained(FocusEvent fe) {
            ((JComboBox)fe.getSource()).showPopup();
        jt.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(jcb));
        setSize(200, 200);
        setVisible(true);
      public static void main(String[] args) { new Test(); }
    }

  • JTable custom cell editor losing focus

    This is a followup to Re: Tutorial on AWT/Swing control flow wherein I ask for pointers to help me understand the source of focus-loss behaviour in my JTable's custom cell editor.
    I have done some more investigations and it turns out that the focus loss is a more general problem with custom cell editors which call other windows. Even the color-picker demo in the JTable tutorial at http://download.oracle.com/javase/tutorial/uiswing/examples/components/index.html#TableDialogEditDemo has this problem, IF you add a text field or two to the layout BEFORE the table. The only reason the table in the demo doesn't lose the focus when the color-picker comes out is because the table is the only thing in the window!
    Here is the demo code, augmented with two text fields, which are admittedly ugly here but which serve the desired purpose:
    * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
    * Redistribution and use in source and binary forms, with or without
    * modification, are permitted provided that the following conditions
    * are met:
    *   - Redistributions of source code must retain the above copyright
    *     notice, this list of conditions and the following disclaimer.
    *   - Redistributions in binary form must reproduce the above copyright
    *     notice, this list of conditions and the following disclaimer in the
    *     documentation and/or other materials provided with the distribution.
    *   - Neither the name of Oracle or the names of its
    *     contributors may be used to endorse or promote products derived
    *     from this software without specific prior written permission.
    * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
    * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
    * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
    * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    import javax.swing.*;
    import javax.swing.border.Border;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class TableDialogEditDemo extends JPanel {
        public class ColorEditor extends AbstractCellEditor
                implements TableCellEditor,
                ActionListener {
            Color currentColor;
            JButton button;
            JColorChooser colorChooser;
            JDialog dialog;
            protected static final String EDIT = "edit";
            public ColorEditor() {
                //Set up the editor (from the table's point of view), which is a button.
                //This button brings up the color chooser dialog, which is the editor from the user's point of view.
                button = new JButton();
                button.setActionCommand(EDIT);
                button.addActionListener(this);
                button.setBorderPainted(false);
                //Set up the dialog that the button brings up.
                colorChooser = new JColorChooser();
                dialog = JColorChooser.createDialog(button, "Pick a Color", true,  //modal
                        colorChooser, this,  //OK button handler
                        null); //no CANCEL button handler
             * Handles events from the editor button and from the dialog's OK button.
            public void actionPerformed(ActionEvent e) {
                if (EDIT.equals(e.getActionCommand())) {
                    //The user has clicked the cell, so bring up the dialog.
                    button.setBackground(currentColor);
                    colorChooser.setColor(currentColor);
                    dialog.setVisible(true);
                    //Make the renderer reappear.
                    fireEditingStopped();
                } else { //User pressed dialog's "OK" button
                    currentColor = colorChooser.getColor();
            public Object getCellEditorValue() {
                return currentColor;
            public Component getTableCellEditorComponent(JTable table,
                                                         Object value,
                                                         boolean isSelected,
                                                         int row,
                                                         int column) {
                currentColor = (Color) value;
                return button;
        public class ColorRenderer extends JLabel
                implements TableCellRenderer {
            Border unselectedBorder = null;
            Border selectedBorder = null;
            boolean isBordered = true;
            public ColorRenderer(boolean isBordered) {
                this.isBordered = isBordered;
                setOpaque(true);
            public Component getTableCellRendererComponent(
                    JTable table, Object color,
                    boolean isSelected, boolean hasFocus,
                    int row, int column) {
                Color newColor = (Color) color;
                setBackground(newColor);
                if (isBordered) {
                    if (isSelected) {
                        if (selectedBorder == null) {
                            selectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5,
                                    table.getSelectionBackground());
                        setBorder(selectedBorder);
                    } else {
                        if (unselectedBorder == null) {
                            unselectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5,
                                    table.getBackground());
                        setBorder(unselectedBorder);
                return this;
        public TableDialogEditDemo() {
            super(new GridLayout());
            JTextField tf1 = new JTextField("tf1");
            add(tf1);
            JTextField tf2 = new JTextField("tf2");
            add(tf2);
            JTable table = new JTable(new MyTableModel());
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            table.setFillsViewportHeight(true);
            JScrollPane scrollPane = new JScrollPane(table);
            table.setDefaultRenderer(Color.class,
                    new ColorRenderer(true));
            table.setDefaultEditor(Color.class,
                    new ColorEditor());
            add(scrollPane);
        class MyTableModel extends AbstractTableModel {
            private String[] columnNames = {"First Name",
                    "Favorite Color",
                    "Sport",
                    "# of Years",
                    "Vegetarian"};
            private Object[][] data = {
                    {"Mary", new Color(153, 0, 153),
                            "Snowboarding", new Integer(5), new Boolean(false)},
                    {"Alison", new Color(51, 51, 153),
                            "Rowing", new Integer(3), new Boolean(true)},
                    {"Kathy", new Color(51, 102, 51),
                            "Knitting", new Integer(2), new Boolean(false)},
                    {"Sharon", Color.red,
                            "Speed reading", new Integer(20), new Boolean(true)},
                    {"Philip", Color.pink,
                            "Pool", new Integer(10), new Boolean(false)}
            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();
            public boolean isCellEditable(int row, int col) {
                if (col < 1) {
                    return false;
                } else {
                    return true;
            public void setValueAt(Object value, int row, int col) {
                data[row][col] = value;
                fireTableCellUpdated(row, col);
        private static void createAndShowGUI() {
            JFrame frame = new JFrame("TableDialogEditDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JComponent newContentPane = new TableDialogEditDemo();
            newContentPane.setOpaque(true);
            frame.setContentPane(newContentPane);
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }When you come back from choosing a color, tf1 is given the focus, instead of the table. This is because bringing the color picker window to the front causes a focus lost event for the cell editor component; it's temporary, as it should be, so why on earth is the system losing track of who has focus in the window??
    I see the following in Window#getMostRecentFocusOwner():
      public Component getMostRecentFocusOwner()
        if (isFocused())
          return getFocusOwner();
        else
          Component mostRecent =
            KeyboardFocusManager.getMostRecentFocusOwner(this);
          if (mostRecent != null)
            return mostRecent;
          else
            return (isFocusableWindow())
                   ? getFocusTraversalPolicy().getInitialComponent(this)
                   : null;
      }My app has a custom focus traversal policy, so I'm able to see who is being called, and indeed, getInitialComponent() is being called. Clearly, the KeyboardFocusManager is actually losing track of the fact that the table was focussed at the point where control was transferred to the color picker! This strikes me as completely unreasonable, especially since, as noted, this is a temporary focus loss event, not a permanent one.
    I'd be grateful for any wisdom in solving this, since similar behaviour to this little demo -- without focus loss, naturally -- is an essential part of my application.

    Looks like it is because the 'restore-focus-to-previous-after-modal-dialog-close' is in a later event than when the control returns to the action performed (which I guess makes sense: it continues the action event handler and the focus events are handled later, but I needed two chained invoke laters so it might also be that the OS events comes later).
    The following works for me (in the actionPerformed edited):
               // create the dialog here so it is correctly parented
               // (otherwise sometimes OK button not correctly the default button)
               dialog = JColorChooser.createDialog(button, "Pick a Color", true,  //modal
                            colorChooser, this,  //OK button handler
                            null); //no CANCEL button handler
                    //The user has clicked the cell, so bring up the dialog.
                    button.setBackground(currentColor);
                    colorChooser.setColor(currentColor);
                    button.addFocusListener(new FocusListener() {
                        @Override
                        public void focusLost(FocusEvent e) {}
                        @Override
                        public void focusGained(FocusEvent e) {
                            // dialog closed and focus restored
                            button.removeFocusListener(this);
                            fireEditingStopped();
                    dialog.setVisible(true);but a simpler request might be better (althoug I still need an invoke later):
    // rest as before except the FocusListener
                    dialog.setVisible(true);
                    button.requestFocusInWindow();
                    EventQueue.invokeLater(new Runnable() {
                        public void run() {
                            fireEditingStopped();
                    });And a quick fix to the renderer so you can actualy see the focus on it:
                    if(hasFocus) {
                        Border border = DefaultLookup.getBorder(this, ui, "Table.focusCellHighlightBorder");
                        setBorder(BorderFactory.createCompoundBorder(
                                border, BorderFactory.createMatteBorder(1, 4, 1, 4,
                                        ((MatteBorder) getBorder()).getMatteColor())));
                    }

  • Selection color in jtable

    I've noticed one annoying thing about JTable when running under Windows L&F. Namely, a table without focus renders its selection in the same color as a table with a focus. This can get really annoying especially with windows where containing more than one jtable.
    Is there an good way of telling JTable to use a different color for selection when it doesn't have the focus?

    thanks, that worked. here's what i ended up donig:
             addFocusListener(new FocusListener() {
                private Color selectionBackground = getSelectionBackground();
                private Color selectionForeground = getSelectionForeground();
                public void focusGained(FocusEvent e) {
                    setSelectionForeground(selectionForeground);
                    setSelectionBackground(selectionBackground);
                public void focusLost(FocusEvent e) {
                    if( !e.isTemporary()) {
                        setSelectionForeground(UIManager.getColor("inactiveCaptionText"));
                        setSelectionBackground(UIManager.getColor("inactiveCaption"));
            });not too sure if inactiveCaption* is the best key to use, but I couldn't find anything better. Any ideas?
    Thanks
    Dmitry

  • Preventing JTree updates from uncompleted JTable edits

    Hello there!!
    I have an applet that displays an xml file in a JTree. Each node of the table represents specific elements of the xml file (some are not displayed by design). Also on the applet is a JTable that updates the displayed information depending on what node of the tree is clicked. The information displayed in the table includes names and values of attributes and names and values of xml elements not displayed in the JTree.
    I can edit values in the table and update that tree effectively, so that is not a problem.
    The problem I have is that if the user enters a value in the table, does not press enter and then clicks on another tree node, the entered value is copied into the new tree node. I would like to ignore all values if the user does not specifically press enter.
    I have seen some code examples in previous posts that partially work, but can't get the entered values to be totally ignored.
    I'm currently using the following code to handle the 'didn't press enter' bug.
            table.getEditorComponent().addFocusListener(
                    new java.awt.event.FocusListener(){
                public void focusGained(java.awt.event.FocusEvent e) {}
                public void focusLost(java.awt.event.FocusEvent e){
                    if ( table.getEditingRow() > -1 &&
                            table.getEditingColumn() > -1 ){
                        ((javax.swing.DefaultCellEditor)table.getCellEditor()).stopCellEditing();
            });So my question is: How do I prevent the value entered in the table cell from being copied to the newly clicked on tree node? Any assistance would be great.
    Thanks (even just for reading!)
    Simon
    PS. When are we going to see the back of the stupid censorship in this forum?

    Not too sure if this will help but here goes...
    Normally in a JTable, editing is automatically stopped when the enter key is pressed so there is no need to do anything special there. If you don't want editing to stop when the mouse is clicked elsewhere in the table, what you should do is call cancelEditing() instead of stopEditing() in your focusLost method.
    ;o)
    V.V.

  • Tab Traversal problem in JTable

    Hi all,
    I am having a requirement in my current project to traverse across the cells of a JTable. Some of the cells were set CustomCelleditor(mainly textfield).
    I have gone through the threads in this forum and tried a code snippet which is now highlighting the text on tab traversal. But there are 2 problems with which I am facing with :-
    1. I need to press tab twice to move to the next cell(one is stopping cell editing and the other is to traverse to the next cell).
    2. When I moved from cell 1 to cell2 using tab and then click on cell1, the text is not getting highlighted.
    Please help me in resolving these issues ?
    The code I tried includes :-
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import javax.swing.text.*;
    public class TableSelectAll extends JFrame{
         JTable table;
         public TableSelectAll() {     
              Object[][] data = { {"1", "A"}, {"2", "B"}, {"3", "C"}, {"4", "D"} };
              String[] columnNames = {"Number","Letter"};
              DefaultTableModel model = new DefaultTableModel(data, columnNames);
              table = new JTable(model) {   
              public void changeSelection(int row, int column, boolean toggle,
    boolean extend) {
              super.changeSelection(row, column, toggle, extend);
                   SwingUtilities.invokeLater( new Runnable(){                 
                   public void run() {    
                        table.dispatchEvent(new KeyEvent( table,                               KeyEvent.KEY_PRESSED,
                             0,
                             0,
                             KeyEvent.VK_F2,
                             KeyEvent.CHAR_UNDEFINED) );
                   JScrollPane scrollPane = new JScrollPane( table );
                   getContentPane().add( scrollPane );
                   MyCellEditor dce = new MyCellEditor( new SelectAllEditor() );
                   dce.setClickCountToStart( 1 );
                   table.setDefaultEditor(Object.class, dce );
         class SelectAllEditor extends JTextField implements FocusListener { 
              public SelectAllEditor() {           
              setBorder( new LineBorder(Color.black) );
              addFocusListener( this );
    public void setText(String text) {
         super.setText(text);
         System.out.println("text");
         selectAll();
    public void focusGained(FocusEvent e) { 
         System.out.println("gained");
         if (getSelectionStart() == getSelectionEnd())
         selectAll();
         public void focusLost(FocusEvent e) {}
    class MyCellEditor extends DefaultCellEditor {
    public MyCellEditor(JTextField t) {
    super(t);
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int
    row, int column) {
    final Component c = super.getTableCellEditorComponent(table, value, isSelected, row, column);
    if (c != null && c instanceof JTextField) {
    try {
    c.requestFocus();
    } catch (Exception e) {
    //handleException(e);
    return c;
    public static void main(String[] args) {   
         TableSelectAll frame = new TableSelectAll();
         frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
    frame.pack(); frame.setVisible(true);
    Regards
    Nagalakshmi

    Additional info:[http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=2&t=017300]

  • JTable - getValueAt Problem

    I am new to Java and am having a problem with a JTable. I want the user to enter 12 months of rain that will go into an array list. The input sreen is O.K., but I cant retrieve the data or clear the cells. Any suggestings would be appreciated. Here is the code. Thanks Ronnie
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.BorderFactory.*;
    import javax.swing.table.*;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import javax.swing.JMenuBar;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class GridBagWindow extends JFrame implements ActionListener,
    FocusListener {
    public GridBagWindow() {
    setTitle("User Rainfall Data");
    JComboBox userCboRainCounty, userCboRainYr;
    DefaultTableModel dtmUserRain = new DefaultTableModel();
    JMenuBar userRainJMB = new JMenuBar();
    JMenu userRainfileMenu = new JMenu("File");
    JMenu userRainprintMenu = new JMenu("Print");
    JMenu userRainclearMenu = new JMenu("Clear");
    JMenu userRaintotalsMenu = new JMenu("Totals");
    // Need to add additional menu option because evnet can not be added
    // directly to JMenu
    JMenuItem userRainOpen = new JMenuItem("Open");
    JMenuItem userRainSave = new JMenuItem("Save");
    JMenuItem userRainPrint = new JMenuItem("Print");
    JMenuItem userRainClear = new JMenuItem("Clear");
    JMenuItem userRainTotals = new JMenuItem("Totals");
    userRainJMB.add(userRainfileMenu);
    userRainfileMenu.add(userRainOpen);
    userRainfileMenu.add(userRainSave);
    userRainJMB.add(userRainprintMenu);
    userRainprintMenu.add(userRainPrint);
    userRainJMB.add(userRainclearMenu);
    userRainclearMenu.add(userRainClear);
    userRainJMB.add(userRaintotalsMenu);
    userRaintotalsMenu.add(userRainTotals);
    userRainOpen.addActionListener(this);
    userRainSave.addActionListener(this);
    userRainPrint.addActionListener(this);
    userRainClear.addActionListener(this);
    userRainTotals.addActionListener(this);
    setJMenuBar(userRainJMB);
    Container contentPane = getContentPane();
    setFont(new Font("Arial", Font.BOLD, 16));
    GridBagLayout gridbag = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();
    contentPane.setLayout(gridbag);
    int width = 800;
    int height = 500;
    Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (screen.width - width) / 2;
    int y = (screen.height - height) / 2;
    setBounds(x, y, 600, 600);
    setJMenuBar(userRainJMB);
    JLabel userRainLblCounty = new JLabel(
    " County");
    userRainLblCounty.setFont(new Font("Arial", Font.BOLD, 16));
    buidConstraints(c, 2, 0, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.EAST;
    c.insets = new Insets(1, 25, 1, 1);
    gridbag.setConstraints(userRainLblCounty, c);
    contentPane.add(userRainLblCounty);
    userCboRainCounty = new JComboBox();
    userCboRainCounty.setFont(new Font("Arial", Font.BOLD, 16));
    userCboRainCounty.setBackground(Color.white);
    buidConstraints(c, 3, 0, 1, 1, 0, 0);
    c.insets = new Insets(1, 1, 1, 1);
    c.anchor = GridBagConstraints.EAST;
    gridbag.setConstraints(userCboRainCounty, c);
    userCboRainCounty.addFocusListener(this);
    contentPane.add(userCboRainCounty);
    String[] header = { "Jan", "Feb", "Mar", "Apr", "May", "June",
    "July", "Aug", "Sep", "Oct", "Nov", "Dec", "Total" };
    DefaultTableModel dftModel = new DefaultTableModel(header, 1);
    JTable userRainTable = new JTable(dftModel);
    userRainTable.setEnabled(true);
    JScrollPane scrollPane = new JScrollPane(userRainTable);
    buidConstraints(c, 1, 1, 3, 1, 0, 0);
    c.anchor = GridBagConstraints.WEST;
    c.insets = new Insets(10, 10, 1, 1);
    gridbag.setConstraints(scrollPane, c);
    contentPane.add(scrollPane);
    JLabel userRainLblRain = new JLabel("Rain (in)");
    userRainLblCounty.setFont(new Font("Arial", Font.BOLD, 16));
    buidConstraints(c, 0, 1, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.EAST;
    gridbag.setConstraints(userRainLblRain, c);
    contentPane.add(userRainLblRain);
    userRainTable
    .setPreferredScrollableViewportSize(new Dimension(600, 20));
    JLabel userRainLblRainYr = new JLabel("Rainfall Years");
    userRainLblRainYr.setFont(new Font("Arial", Font.BOLD, 16));
    buidConstraints(c, 0, 2, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.SOUTH;
    c.insets = new Insets(0, 1, 1, 1);
    gridbag.setConstraints(userRainLblRainYr, c);
    contentPane.add(userRainLblRainYr);
    userCboRainYr = new JComboBox();
    userCboRainYr.setFont(new Font("Arial", Font.BOLD, 16));
    userCboRainYr.setBackground(Color.white);
    buidConstraints(c, 1, 2, 1, 1, 0, 0);
    c.insets = new Insets(1, 1, 1, 1);
    c.anchor = GridBagConstraints.EAST;
    gridbag.setConstraints(userCboRainYr, c);
    // userCboRainCounty.addFocusListener(this);
    contentPane.add(userCboRainYr);
    JLabel userRainLblTitle = new JLabel("Title");
    userRainLblTitle.setFont(new Font("Arial", Font.BOLD, 16));
    buidConstraints(c, 2, 2, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.EAST;
    // c.insets = new Insets(1, 14,1,1);
    gridbag.setConstraints(userRainLblTitle, c);
    contentPane.add(userRainLblTitle);
    JTextField userRainTxtTitle = new JTextField(18);
    userRainTxtTitle.setFont(new Font("Arial", Font.BOLD, 16));
    buidConstraints(c, 3, 2, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.EAST;
    c.insets = new Insets(1, 1, 1, 1);
    gridbag.setConstraints(userRainTxtTitle, c);
    contentPane.add(userRainTxtTitle);
    JLabel userLblRainBlank = new JLabel(" ");
    buidConstraints(c, 0, 3, 4, 4, 0, 0);
    c.insets = new Insets(15, 15, 1, 1);
    gridbag.setConstraints(userLblRainBlank, c);
    contentPane.add(userLblRainBlank);
    JButton userBtnRainDefault = new JButton(" Default ");
    userBtnRainDefault.setFont(new Font("Arial", Font.BOLD, 16));
    userBtnRainDefault.setBorder(BorderFactory.createRaisedBevelBorder());
    buidConstraints(c, 1, 4, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.EAST;
    gridbag.setConstraints(userBtnRainDefault, c);
    contentPane.add(userBtnRainDefault);
    JButton userBtnRainCancel = new JButton(" Cancel ");
    userBtnRainCancel.setFont(new Font("Arial", Font.BOLD, 16));
    userBtnRainCancel.setBorder(BorderFactory.createRaisedBevelBorder());
    buidConstraints(c, 2, 4, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.CENTER;
    c.insets = new Insets(15, 0, 0, 0);
    gridbag.setConstraints(userBtnRainCancel, c);
    contentPane.add(userBtnRainCancel);
    JButton userBtnRainOK = new JButton(" O.K ");
    userBtnRainOK.setFont(new Font("Arial", Font.BOLD, 16));
    userBtnRainOK.setBorder(BorderFactory.createRaisedBevelBorder());
    buidConstraints(c, 3, 4, 1, 1, 20, 20);
    c.insets = new Insets(15, 0, 0, 150);
    c.anchor = GridBagConstraints.EAST;
    gridbag.setConstraints(userBtnRainOK, c);
    userBtnRainOK.addActionListener(this);
    contentPane.add(userBtnRainOK);
    // //User Definded Cold Protection
    // Input Combo Box for County Selection, two counties per line
    userCboRainCounty.addItem("CHARLOTTE");
    userCboRainCounty.addItem("CITRUS");
    userCboRainCounty.setSelectedIndex(5);
    userCboRainYr.addItem(String.valueOf(1));
    userCboRainYr.addItem(String.valueOf(5));
    userCboRainYr.addItem(String.valueOf(10));
    userCboRainYr.setSelectedIndex(-1);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    pack();
    setVisible(true);
    void buidConstraints(GridBagConstraints c, int gx, int gy, int gw, int gh,
    int wx, int wy) {
    c.gridx = gx;
    c.gridy = gy;
    c.gridwidth = gw;
    c.gridheight = gh;
    c.weightx = wx;
    c.weighty = wy;
    public void focusGained(FocusEvent af) {
    // if(af.getSource() == userRainTable){
    // userRainTable.setBackground(Color.yellow);
    public static void main(String args[]) {
    GridBagWindow window = new GridBagWindow();
    public void actionPerformed(ActionEvent evt) {
    String actionName = evt.getActionCommand();
    System.out.println("Button \"" + actionName + "\" was pressed.");
    // userRainTable.getValueAt(1,1);
    if (actionName == "Clear") {
    for (int i = 0; i > 14; i++) {
    // userRainfallTable.setValueAt(0, 1 , 1);
    System.out.println("Yes Continue");
    if (actionName == "Totals") {
    System.out.println("Yes Continue");
    }

    Hello Ronnie,
    this is a nice little piece of code. ;-)
    No chance of reducing it a little bit just to show the problem?
    And what about making it at least to compile error free? (Just tried on 1.5_06)
    Also place tags around to make it more readable.
    Regards
    J�rg                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • JTable's setValueAt() function -URGENT please help!!!

    I am using a subclass of the DefaultTableModel for my JTable. The data is in the form of a Vector of vectors. I am catching user input (editing) by implementing the setValueAt() function. The table consists of 1 row, and 4 columns (thats a required limitation). When I edit(change) only one cell of the table, and dont tab out of the cell, I see that the setValueAt() function is not being called, and the model is not being updated. But when I change the cell value and tab out of the cell to the next cell, the setValueAt() function is being called.
    How can I force the setValueAt() function to be called without tabbing out of the edited cell. I need to implement this feature as a user can change a single cell and click the "save" button.
    here is the setValueAt() function implementation.. Could it be that I might have implemented this in error or need to implement some other methods? Any help/pointers will be greatly appreaciated.
    public void setValueAt(Object value, int row, int col)
    String cellValue = "";
         if (value instanceof String)
              cellValue = (String)value;
         Vector tmp = (Vector)dataVector.elementAt(row);
         tmp.setElementAt(cellValue,col);
         fireTableCellUpdated(row,col);
    Thank You in advance

    Seems to me that the problem is to do with when setValueAt() gets called.
    Sounds like you want it to be called when the Cell's editor loses focus.
    One solution would be something like the following to ensure editing stops when focus is lost.
    There may be other less complicated solutions, but this one should work !
    class  MyEditor extends AbstractCellEditor implements TableCellEditor {
        public MyEditor() {
            this.text = new JTextField();
            this.text.addFocusListener(new FocusListener() {
                public void focusGained(FocusEvent e) {
                public void focusLost(FocusEvent e) {
                    stopCellEditing();
        public Component getTableCellEditorComponent(JTable table, Object value,
                                                                               boolean isselected, int row, int col) {
            this.text.setText((String)value);
            return this.text;
        public Object getCellEditorValue() {
            return this.text.getText();
        private JTextField text;
    table.setDefaultEditor(String.class, new MyEditor());

  • JTable row deletion deleting valuable information  --need HELP

    Hi Experts and Java Programmers,
    I am posting the code that works 99% of the time. It basically creates a JTable and has row insertion and row deletion methods. The row insertion works fine. However, when a row N is deleted it causes the loss of data in the row N+1's cell in whichever cell the cursor is blinking. In other words, when cursor is in cell M of row N, row deletion sets the cell M of row N+1 to blank. So if the cursor is on the 2nd cell of 1st row and if 1st row is deleted, the data in the 2nd cell of 2nd row (now moved to 1st row) is lost.
    Thanks for your help.
    Murthy
    package trunkxref;
    *  Copyright 1999-2002 Matthew Robinson and Pavel Vorobiev.
    *  All Rights Reserved.
    *  ===================================================
    *  This program contains code from the book "Swing"
    *  2nd Edition by Matthew Robinson and Pavel Vorobiev
    *  http://www.spindoczine.com/sbe
    *  ===================================================
    *  The above paragraph must be included in full, unmodified
    *  and completely intact in the beginning of any source code
    *  file that references, copies or uses (in any way, shape
    *  or form) code contained in this file.
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    import java.text.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.net.*;
    public class trnk
    //extends JFrame
      public JTable m_table;
      public TrunkReportData m_data;
      public JLabel m_title;
      public JLabel m_title2;
      public InputStream is;
      Image imginsert, imgdel, imgup, imgdown, imgsav;
      URL jspURL;
      JApplet applet;
      public trnk ( JApplet applet,InputStream is, Image imginsert, Image imgdel, Image imgup, Image imgdown, Image imgsav, URL jspURL)
        //super ("Trunks Data");
        //setSize (600, 300);
        this.applet=applet;
        this.is=is;
        this.imginsert=imginsert;
        this.imgdel=imgdel;
        this.imgup=imgup;
        this.imgsav=imgsav;
        this.imgdown=imgdown;
        this.jspURL=jspURL;
        UIManager.put("Table.focusCellHighlightBorder",
                new LineBorder(Color.black, 0));
        m_data = new TrunkReportData (this,imgup, imgdown);
        m_title = new JLabel(m_data.getTitle(),
                    null, SwingConstants.LEFT);
        m_title2 = new JLabel("(Please make sure to hit TAB or ENTER after making changes to a cell)",
                    null, SwingConstants.LEFT);
        m_title.setFont(new Font("Helvetica",Font.PLAIN,24));
        m_title2.setFont(new Font("Helvetica",Font.PLAIN,12));
               Color bg=new Color(200,100,30);
               //setBackground(header.getBackground());
               m_title.setBackground(bg);
               m_title.setForeground(Color.white);
               m_title2.setBackground(bg);
               m_title2.setForeground(Color.yellow);
        //getContentPane().add(m_title, BorderLayout.NORTH);
        m_table = new JTable ();
         m_table.putClientProperty( "JTable.autoStartsEdit", new Boolean( false ) );
         //m_table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
        m_table = new JTable () {
              public boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {     
                   if (e.getKeyChar()==KeyEvent.CHAR_UNDEFINED)
                        return false;     
                   return super.processKeyBinding(ks,e,condition,pressed);             }
        m_table = new JTable () {
         protected void processKeyEvent(KeyEvent e)     {     
               if ( (e.getKeyCode() == KeyEvent.VK_ENTER ||
                   e.getKeyCode() == KeyEvent.VK_TAB) &&  
                   e.getID() == KeyEvent.KEY_PRESSED ){
                        if(m_table.isEditing()) {
                             m_table.getCellEditor().stopCellEditing();
                             int row = m_table.getEditingRow();
                             int col = m_table.getEditingColumn();
                             col++; // actually check col > number of columns
                             m_table.editCellAt(row,col);
                             //m_table.transferFocus();
                        } else {
                             int col = m_table.getSelectedColumn() + 1;
                             int row = m_table.getSelectedRow();
                             m_table.clearSelection();
                             col++; // actually check col > number of columns
                             m_table.editCellAt(row,col);
                             //m_table.transferFocus();
                                //m_table.setRowSelectionInterval(row, row);
                                //m_table.setColumnSelectionInterval(column, column);               
                             //m_table.scrollRectToVisible( m_table.getCellRect(row, column, true) );          
              }     else           {               
                   super.processKeyEvent(e);           
         //m_table.setSurrendersFocusOnKeystroke(true);
         //m_table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
         m_table.addFocusListener(new FocusListener() {
              public void focusGained(FocusEvent e){
              public void focusLost(FocusEvent e){
                        if(m_table.isEditing()) {
                             m_table.getCellEditor().stopCellEditing();
        m_table.setAutoCreateColumnsFromModel (false);
        m_table.setModel (m_data);
        m_table.setSelectionMode (ListSelectionModel.SINGLE_SELECTION);
        for (int k = 0; k < m_data.getColumnCount (); k++)
         TableCellRenderer renderer = null;
         TableCellEditor editor = null;
         renderer = new TextAreaCellRenderer ();     // NEW
         editor = new TextAreaCellEditor (m_table, m_data);
         TableColumn column = new TableColumn (k,
                                   TrunkReportData.m_columns[k].m_width,
                                   renderer, editor);
         column.setHeaderRenderer(createDefaultRenderer());
         m_table.addColumn (column);
        JTableHeader header = m_table.getTableHeader ();
        header.setUpdateTableInRealTime (false);
        header.addMouseListener(new ColumnListener());
        header.setReorderingAllowed(true);
        //JScrollPane ps = new JScrollPane ();
        //ps.getViewport ().setBackground (m_table.getBackground ());
        //ps.setSize (550, 150);
        //ps.getViewport ().add (m_table);
        //getContentPane ().add (ps, BorderLayout.CENTER);
        //JToolBar tb = createToolbar ();
        //getContentPane ().add (tb, BorderLayout.NORTH);
        //JPanel p = new JPanel (new GridLayout (1, 2, 5, 5));
        //getContentPane ().add (p, BorderLayout.SOUTH);
      } //constructor trnk
      protected TableCellRenderer createDefaultRenderer() {
        DefaultTableCellRenderer label = new DefaultTableCellRenderer()
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
           if (table != null) {
             JTableHeader header = table.getTableHeader();
             if (header != null) {
               //setForeground(header.getForeground());
               setForeground(Color.white);
               Color bg=new Color(200,100,30);
               //setBackground(header.getBackground());
               setBackground(bg);
               setFont(header.getFont());
           setText((value == null) ? "" : value.toString()) ;
           setBorder(UIManager.getBorder("TableHeader.cellBorder"));
           return this;
        label.setHorizontalAlignment(JLabel.CENTER);
        return label;
      } //table cell renderer
      public JToolBar createToolbar ()
        JToolBar tb = new JToolBar ();
        tb.setFloatable (false);
               Color bg=new Color(200,100,30);
               //setBackground(header.getBackground());
               tb.setBackground(bg);
        JButton bt = new JButton (new ImageIcon (imginsert));
        //JButton bt = new JButton ("Insert");
        bt.setToolTipText ("Insert Row");
        bt.setRequestFocusEnabled (false);
        ActionListener lst = new ActionListener (){
          public void actionPerformed (ActionEvent e) {
         int nRow = m_table.getSelectedRow() + 1;
         m_data.insert (nRow);
         m_table.tableChanged (new TableModelEvent
                         (m_data, nRow, nRow, TableModelEvent.ALL_COLUMNS,
                          TableModelEvent.INSERT));
         m_table.setRowSelectionInterval (nRow, nRow);
        bt.addActionListener ((ActionListener)lst);
        tb.add (bt);
        bt = new JButton (new ImageIcon (imgdel));
        //bt = new JButton ("Delete");
        bt.setToolTipText("Delete Row");
        bt.setRequestFocusEnabled(false);
        lst = new ActionListener ()
         public void
           actionPerformed
           (ActionEvent e)
             int nRow = m_table.getSelectedRow();
              if (nRow  < 0)
               JOptionPane.showMessageDialog( null,  "Please select a row to delete",  "Error", JOptionPane.ERROR_MESSAGE);
              else
              if (JOptionPane.showConfirmDialog(null, "Do you want to delete the selected row?", "Delete a Row", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
             if (m_data.delete (nRow))
              m_table.getCellEditor().stopCellEditing();
              m_table.tableChanged
                (new TableModelEvent
                 (m_data, nRow, nRow,
                  TableModelEvent.ALL_COLUMNS,
                  TableModelEvent.DELETE));
              //m_table.clearSelection();
        bt.addActionListener(lst);
        tb.add (bt);
        bt = new JButton (new ImageIcon (imgsav));
        //bt = new JButton ("Save");
        bt.setToolTipText("Save");
        bt.setRequestFocusEnabled(false);
        lst = new ActionListener ()
         public void
           actionPerformed
           (ActionEvent e)
             m_table.tableChanged (new TableModelEvent
                          (m_data));
             //m_data.fireTableDataChanged();
             //System.out.println("beginning to write data to" + jspURL.toString());
             //code to save data to file
              //final Component top=(trnk)this.getTopLevelAncestor();
              //final Component top=(trnk)super.;
              //final Cursor lOrigCursor =(Cursor) super.getCursor();
              //final Cursor lOrigCursor = getCrsr();
              //top.setCursor( Cursor.getPredefinedCursor( Cursor.WAIT_CURSOR ) );
              setWaitCursor();
              Thread lSavThread= new Thread() {
                   public void run()
                        savefile(m_data, jspURL);
                        //top.setCursor( lOrigCursor );
                        setNormalCursor();
              lSavThread.start();
        bt.addActionListener(lst);
        tb.add (bt);
        return tb;
      } //create tool bar
      public void setWaitCursor()
              applet.getGlassPane().setVisible(false);
              applet.getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
      public void setNormalCursor()
              applet.getGlassPane().setVisible(true);
              applet.getGlassPane().setCursor(Cursor.getDefaultCursor());
      public void savefile(TrunkReportData m_data, URL jspURL)
             String txt="";
             Enumeration enum=m_data.m_vector.elements();
             while(enum.hasMoreElements())
              TrunkData trnk = (TrunkData)enum.nextElement();
              txt += trnk.m_sysname + " , "
    + trnk.m_clli + " , "
    + trnk.m_tg + " , "
    + trnk.m_member.intValue() + " , "
    + trnk.m_trunk_type + " , "
    + trnk.m_lata + " , "
    + trnk.m_lata_name + " , "
    + trnk.m_prospect_server + " , "
    + trnk.m_tgroupid + " , "
    + trnk.m_ctg + " , "
    + trnk.m_augmen.intValue() + " , "
    + trnk.m_vendor + "\n";
             try {
               URLConnection jspCon=jspURL.openConnection();
               jspCon.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
               jspCon.setUseCaches(false);
               jspCon.setDoOutput(true);
               PrintStream out = new PrintStream(jspCon.getOutputStream());
               String postData= "Text=" + URLEncoder.encode(txt, "UTF-8");
               out.println(postData);
               out.flush();
               out.close();
               InputStreamReader in=new InputStreamReader(jspCon.getInputStream());
               int chr;
               while((chr=in.read()) != -1) {}
               in.close();
             } catch (Exception e2) {
               System.out.println (" exception in writing data out "
    + e2.toString());
             //System.out.println("done write data");
      // NEW
      class ColumnListener extends MouseAdapter {
        public void mouseClicked(MouseEvent e) {
          TableColumnModel colModel = m_table.getColumnModel();
          int columnModelIndex = colModel.getColumnIndexAtX(e.getX());
          int modelIndex = colModel.getColumn(columnModelIndex).getModelIndex();
          if (modelIndex < 0)
         return;
          if (m_data.m_sortCol == modelIndex)
         m_data.m_sortAsc = !m_data.m_sortAsc;
          else
         m_data.m_sortCol = modelIndex;
          for (int i=0; i < m_data.getColumnCount(); i++) {
         TableColumn column = colModel.getColumn(i);
         int index = column.getModelIndex();
         JLabel renderer = (JLabel)column.getHeaderRenderer();
         renderer.setIcon(m_data.getColumnIcon(index));
          m_table.getTableHeader().repaint();
          m_data.sortData();
          m_table.tableChanged(new TableModelEvent(m_data));
          m_table.repaint();
      } //column listener
    } //class trnk
    class TextAreaCellRenderer extends JTextArea implements TableCellRenderer
      protected static Border m_noFocusBorder    =    new
      EmptyBorder (1,           1,           1,           1);
      protected static    Border    m_focusBorder =
      UIManager.getBorder("Table.focusCellHighlightBorder");
      public
      TextAreaCellRenderer
        setEditable
          (false);
        setLineWrap
          (true);
        setWrapStyleWord
          (true);
        setBorder
          (m_noFocusBorder);
      public Component
      getTableCellRendererComponent
      (JTable table,
       Object value,
       boolean
       isSelected,
       boolean
       hasFocus,
       int nRow, int nCol)
        Color fg=new Color(255,0,0);
        //ColorData cvalue = new ColorData(value);
        setForeground(fg);
        if (value       instanceof       String)
          setText ((String) value);
        else if (value instanceof Integer)
          setText((String)value.toString());
         setBackground
          (isSelected && !hasFocus ?      table.getSelectionBackground() : table.getBackground ());
        //setForeground (isSelected && !hasFocus ?
        //      table.getSelectionForeground() : table.getForeground ());
        setFont (table.getFont ());
        setBorder (hasFocus ? m_focusBorder : m_noFocusBorder);
         causes looping and stops rendering the components surrounding
         the cells
        // Adjust row's
        // height
        //int width =
         // table.getColumnModel().getColumn(nCol).getWidth ();
        //setSize (width,
    //          1000);
        int rowHeight =     getPreferredSize().height;
        if (table.getRowHeight(nRow) <  rowHeight)
          table.setRowHeight (nRow,  rowHeight);
         //table.setRowHeight(nRow, 20);
        return this;}
      // To fix JDK bug
      public String getToolTipText (MouseEvent event)
        return null;
    } //class text area cell renderer
    // NEW
    class TextAreaCellEditor extends AbstractCellEditor implements
    TableCellEditor
      public static int CLICK_COUNT_TO_EDIT = 1;
      protected JTextArea m_textArea;
      protected JScrollPane m_scroll;
      public TextAreaCellEditor (JTable t_table, TrunkReportData t_tablemodel)
         final JTable table=t_table;
         final TrunkReportData tablemodel =t_tablemodel;
        m_textArea = new JTextArea () {
         protected void processKeyEvent(KeyEvent e)     {     
                   //if (e.getKeyChar()==KeyEvent.CHAR_UNDEFINED)
                   // return ;
               if ( (e.getKeyCode() == KeyEvent.VK_ENTER ||
                   e.getKeyCode() == KeyEvent.VK_TAB)&&  
                   e.getID() == KeyEvent.KEY_PRESSED ){
                   int row = table.getEditingRow();
                   int col = table.getEditingColumn();
                   col++; // actually check col > number of columns
                   if (col == tablemodel.getColumnCount())
                        row++;
                        if (row == tablemodel.getRowCount())
                        row=0;
                        col=0;
                   stopCellEditing();
                   table.editCellAt(row,col);
                   table.transferFocus();
              }     else if ( (e.getKeyCode() == KeyEvent.VK_DOWN ||
                   e.getKeyCode() == KeyEvent.VK_UP ) &&
                   e.getID() == KeyEvent.KEY_PRESSED ){
                   int row = table.getEditingRow();
                   int col = table.getEditingColumn();
                   if ( e.getKeyCode() == KeyEvent.VK_UP)
                   row--;
                   if ( e.getKeyCode() == KeyEvent.VK_DOWN)
                   row++;
                   if (col == tablemodel.getColumnCount())
                        row++;
                        if (row == tablemodel.getRowCount())
                        row=0;
                        col=0;
                   stopCellEditing();
                   table.editCellAt(row,col);
                   table.transferFocus();
              }     else
                   super.processKeyEvent(e);           
        m_textArea.setLineWrap (true);
        m_textArea.setWrapStyleWord (true);
        m_scroll = new JScrollPane (m_textArea,
                        //JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                        JScrollPane.VERTICAL_SCROLLBAR_NEVER,
                        //JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
                        JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
      public Component
      getTableCellEditorComponent
      (JTable table,
       Object value,
       boolean
       isSelected,
       int nRow, int nCol)
        //m_textArea.setBackground(table.getBackground());
        m_textArea.setBackground(Color.green);
        //m_textArea.setForeground(table.getForeground());
        m_textArea.setForeground(Color.black);
        m_textArea.setFont (table.getFont());
        m_textArea.setText (value   ==   null ?   "" :  value.toString());
        return m_scroll;
      public Object getCellEditorValue ()
        return       m_textArea.getText ();
      JTextArea getCellEditor ()
        return       m_textArea;
      public boolean isCellEditable (EventObject anEvent)
        if (anEvent   instanceof         MouseEvent)
         int click = ((MouseEvent) anEvent).getClickCount();
         return click >= CLICK_COUNT_TO_EDIT;
        return true;
    } //class text area cell editor
    class TrunkData
      public String    m_sysname;
      public String    m_clli;
      public String    m_tg;
      public Integer     m_member;
      public String    m_trunk_type;
      public String    m_lata;
      public String    m_lata_name;
      public String    m_prospect_server;
      public String    m_tgroupid;
      public String    m_ctg;
      public Integer   m_augmen;
      public String    m_vendor;
      public TrunkData ()
        m_sysname = "";
        m_clli = "";
        m_tg = "";
        m_member =     new Integer (0);
        m_trunk_type =     "";
        m_lata = "";
        m_lata_name =       "";
        m_prospect_server       = "";
        m_tgroupid = "";
        m_ctg = "";
        m_augmen = new Integer(0);
        m_vendor = "";
      public
      TrunkData
      (String sys,
       String clli,
       String tg,
       String member,
       String ttyp,
       String lata,
       String latanm,
       String pserver,
       String tgrpid,
       String ctg,
       String aug,
       String vend)
        m_sysname = sys;
        m_clli = clli;
        m_tg = tg;
        try {
          if (member.trim().equals(""))
         m_member=new Integer(0);
          else
         m_member =     new Integer(member.trim());
        } catch (Exception e) {
          System.out.println("can't parse member " + e.toString());
        m_trunk_type =     ttyp;
        m_lata = lata;
        m_lata_name =     latanm;
        m_prospect_server     = pserver;
        m_tgroupid =     tgrpid;
        m_ctg = ctg;
        if (aug.trim().equals(""))
          m_augmen=new Integer(0);
        else m_augmen=new Integer(aug.trim());
        m_vendor = vend;
    } //class trunkd data
    class ColumnData
      public String    m_tolatLbl;
      int m_width;
      int m_alignment;
      public    ColumnData    (String title,     int width,     int alignment)
        m_tolatLbl =     title;
        m_width = width;
        m_alignment =     alignment;
    } //class column data
    class  TrunkReportData  extends  AbstractTableModel
      public static ImageIcon COLUMN_UP;
      public static ImageIcon COLUMN_DOWN;
      public int               m_sortCol = 0;
      public boolean m_sortAsc = true;
      public static      final ColumnData      m_columns[] =
        new      ColumnData      ("System", 200,       JLabel.LEFT),
        new      ColumnData      ("CLLI", 200,       JLabel.LEFT),
        new      ColumnData      ("Trunk Group",       200,       JLabel.LEFT),
        new      ColumnData      ("Members", 200,       JLabel.LEFT),
        new      ColumnData      ("Trunk Type",       200,       JLabel.LEFT),
        new      ColumnData      ("LATA ", 200,       JLabel.LEFT),
        new      ColumnData      ("LATA Name",       200,       JLabel.LEFT),
        new      ColumnData      ("Prospect Server",       200,       JLabel.LEFT),
        new      ColumnData      ("Trunk Group ID",       200,       JLabel.LEFT),
        new      ColumnData      ("CTG", 200,       JLabel.LEFT),
        new      ColumnData      ("Augments", 200,       JLabel.LEFT),
        new      ColumnData      ("Vendor", 200,       JLabel.LEFT)
      protected      trnk m_parent;
      protected Vector      m_vector;
      public TrunkReportData (trnk parent , Image imgup, Image imgdown)
        this.COLUMN_UP=new ImageIcon(imgup);
        this.COLUMN_DOWN=new ImageIcon(imgdown);
        m_parent = parent;
        m_vector = new Vector ();
        setDefaultData (parent.is);
      public void setDefaultData (InputStream is)
        m_vector =  new Vector ();
        int numFields =       0;
        try
         BufferedReader
           br =new     BufferedReader(new InputStreamReader(is));
         String inline ="";
         while ((inline =  br.readLine()) != null)
             if (inline.indexOf('#') > -1)
              continue;
             StringTokenizer st = new StringTokenizer (inline, ",");
             String nsys=st.nextToken ().trim(); //sys
             String nclli=  st.nextToken().trim() ;     // clli
             String ntg= st.nextToken ().trim();     // tg
             String nmemb=  st.nextToken().trim();     // members
             String nttyp=   st.nextToken ().trim();     // trunktype
             String nlata= st.nextToken ().trim();     // lata
             String nlataname=  st.nextToken ().trim();     // lata  name
             String npros=    st.nextToken ().trim();     // prospect  server
             String ntgrpid=st.nextToken().trim();      //tgroupid
             String nctg=st.nextToken().trim();      //ctg
             String naug=st.nextToken().trim();      //augments
             String nvend=st.nextToken().trim();      //vendor
             m_vector.addElement(new TrunkData(nsys,nclli, ntg,
                                   nmemb, nttyp, nlata, nlataname, npros, ntgrpid, nctg,
                                   naug,nvend));
         br.close ();}
        catch (Exception e)
         System.out.println("Error in file reader 2 "+ e.toString ());
        sortData();
      public Icon getColumnIcon(int column) { // NEW
        if (column==m_sortCol)
          return m_sortAsc ? COLUMN_UP : COLUMN_DOWN;
        return null;
      // NEW
      public void sortData() {
        Collections.sort(m_vector, new
                   TrunkComparator(m_sortCol, m_sortAsc));
      public int getRowCount ()
        return m_vector == null ? 0 : m_vector.size ();
      public int getColumnCount ()
        return    m_columns.length;
      public String getColumnName(int nCol)
        return    m_columns[nCol]. m_tolatLbl;
      public boolean isCellEditable
      (int nRow, int nCol)
        return true;
      public Object getValueAt (int         nRow,         int nCol)
        if (nRow < 0 || nRow >=getRowCount())
          return "";
        TrunkData row = (TrunkData) m_vector.elementAt(nRow);
        switch (nCol)
          case 0:
         return row.m_sysname;
          case 1:
         return row.m_clli;
          case 2:
         return row.m_tg;
          case 3:
         return row.m_member;
          case 4:
         return row.m_trunk_type;
          case 5:
         return row.m_lata;
          case 6:
         return row.m_lata_name;
          case 7:
         return row.m_prospect_server;
          case 8:
         return row.m_tgroupid;
          case 9:
         return row.m_ctg;
          case 10:
         return row.m_augmen;
          case 11:
         return row.m_vendor;
        return "";
      public void setValueAt (Object value, int nRow, int nCol)
        if (nRow < 0
         || nRow >=
         getRowCount
         || value ==
         null)
          return;
        System.out.println("setting nrow=" + nRow + " nCol=" + nCol + " to value=" + (String) value);
        TrunkData row = (TrunkData) m_vector.elementAt (nRow);
        String svalue = value.toString ();
        switch (nCol)
          case 0:
         row.m_sysname = svalue; break;
          case 1:
         row.m_clli = svalue; break;
          case 2:
         row.m_tg = svalue; break;
          case 3:
         if (svalue.trim().equals(""))
           row.m_member=new Integer(0);
         else
             try {
               row.m_member = new Integer(svalue.trim());
             } catch (NumberFormatException e) {
               JOptionPane.showMessageDialog( null,  "Please enter integer valuesonly.",  "Error", JOptionPane.ERROR_MESSAGE);
           break;
          case 4:
         row.m_trunk_type = svalue; break;
          case 5:
         row.m_lata = svalue; break;
          case 6:
         row.m_lata_name = svalue; break;
          case 7:
         row.m_prospect_server = svalue; break;
          case 8:
         row.m_tgroupid = svalue; break;
          case 9:
         row.m_ctg = svalue; break;
          case 10:
              if (svalue.trim().equals("")) {
                   row.m_augmen = new Integer(0);
              } else {
                       try {
                        row.m_augmen = new Integer(svalue.trim());
                       } catch (NumberFormatException e) {
                              JOptionPane.showMessageDialog( null,  "Error", "Please enter only integer values.",  JOptionPane.ERROR_MESSAGE);
              break;
          case 11:
         row.m_vendor = svalue; break;}
        fireTableCellUpdated(nRow,nCol);
      public void insert (int nRow)
        if (nRow < 0)
          nRow = 0;
        if (nRow >     m_vector.size ())
          nRow  =
         m_vector. size ();
        m_vector.insertElementAt
          (new
           TrunkData (),
           nRow);
      public boolean delete (int nRow)
        if (nRow < 0
         || nRow >=
         m_vector.size
         ())return
              false;
        m_vector.remove (nRow);
        return true;
      public String getTitle() {
        return "Verizon Trunk Table";
    } //class trunk report data
    class TrunkComparator implements Comparator {
      protected int            m_sortCol;
      protected boolean m_sortAsc;
      public TrunkComparator(int sortCol, boolean sortAsc) {
        m_sortCol = sortCol;
        m_sortAsc = sortAsc;
      public int compare(Object o1, Object o2)
        if (!(o1 instanceof TrunkData) || !(o2 instanceof TrunkData))
          return 0;
        TrunkData s1=(TrunkData)o1;
        TrunkData s2=(TrunkData)o2;
        int result=0;
        String str1="", str2="";
        int i1=0, i2=0;
        switch(m_sortCol) {
        case 0: //sysname
          str1=(String)s1.m_sysname;
          str2=(String)s2.m_sysname;
          result=str1.compareTo(str2);
          break;
        case 1: // clli
          str1=(String)s1.m_clli;
          str2=(String)s2.m_clli;
          result=str1.compareTo(str2);
          break;
        case 2: //TG
          str1=(String)s1.m_tg;
          str2=(String)s2.m_tg;
          result=str1.compareTo(str2);
          break;
        case 3: //member
          i1 =s1.m_member.intValue();
          i2 =s2.m_member.intValue();
          result = i1 < i2 ? -1 : (i1 > i2 ? 1 : 0);
          break;
        case 4: //trunk type
          str1=(String)s1.m_trunk_type;
          str2=(String)s2.m_trunk_type;
          result=str1.compareTo(str2);
          break;
        case 5: //lata
          str1=(String)s1.m_lata;
          str2=(String)s2.m_lata;
          result=str1.compareTo(str2);
          break;
        case 6: //lata name
          str1=(String)s1.m_lata_name;
          str2=(String)s2.m_lata_name;
          result=str1.compareTo(str2);
          break;
        case 7: //prospect server
          str1=(String)s1.m_prospect_server;
          str2=(String)s2.m_prospect_server;
          result=str1.compareTo(str2);
          break;
        case 8: //tgroup id
          str1=(String)s1.m_tgroupid;
          str2=(String)s2.m_tgroupid;
          result=str1.compareTo(str2);
          break;
        case 9: //ctg
          str1=(String)s1.m_ctg;
          str2=(String)s2.m_ctg;
          result=str1.compareTo(str2);
          break;
        case 10: //augments
          i1 =s1.m_augmen.intValue();
          i2 =s2.m_augmen.intValue();
          result = i1 < i2 ? -1 : (i1 > i2 ? 1 : 0);
          break;
        case 11: //vendor
          str1=(String)s1.m_vendor;
          str2=(String)s2.m_vendor;
          result=str1.compareTo(str2);
          break;
        if (!m_sortAsc) result = -result;
        return result;
      public boolean equals(Object obj) {
        if (obj instanceof TrunkComparator) {
          TrunkComparator compObj=(TrunkComparator) obj;
          return (compObj.m_sortCol == m_sortCol) &&
         (compObj.m_sortAsc==m_sortAsc);
        return false;
    } //class trunk comparator

    Problem resolved by modifying the code to this:
    bt.setToolTipText("Delete Row");   
    bt.setRequestFocusEnabled(false);   
    lst = new ActionListener ()      {     
    public void       actionPerformed       (ActionEvent e)       {       
    int nRow = m_table.getSelectedRow();          
    if (nRow  < 0)           
    JOptionPane.showMessageDialog( null,  "Please select a row to delete",  "Error", JOptionPane.ERROR_MESSAGE);          
    else if (JOptionPane.showConfirmDialog(null, "Do you want to delete the selected row?", "Delete a Row", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
    m_table.getCellEditor().stopCellEditing();   
    if (m_data.delete (nRow))           {          
         m_table.tableChanged            (new TableModelEvent             (m_data, nRow, nRow,              TableModelEvent.ALL_COLUMNS,              TableModelEvent.DELETE));          //m_table.clearSelection();       
       };

Maybe you are looking for