JTable cell focus order

Does anyone know why cells in a JTable would still respond to focus events even though they are disabled?
For example, assume this is my table:
D D E E E E E
D D E E E E E
D D E E E E E
D = Disabled
E = Enabled
When this table gets focus, the upper left cell "D" gets focus. What if I wanted the first "E" in row one to be the default cell? And what if I don't want any "D" cells to be focusable?

FocusListener only tells me where iv'e been or where I am going...it does not give me a mechanism to set focus to a particular cell. After searching the API and the Forums, it looks as if I am not the first to ask this question and certainly not the first to find that it cannot be done with the JTable. So, either I give up on the idea or find a JTable replacement...

Similar Messages

  • JTable Cell Focus Problem

    I am using the setValueAt method in the TableModel of a JTable in order to do validation of the value the user has entered into a cell of a table (the validation involves looking at the values of other components on the same JFrame).
    Everything works fine, except for the following case: The person enters a value into the cell of the editor. The person then moves the focus to another component via a mouse-click. The cell in the table still shows the new value entered by the person, but the setValueAt method is never triggered, and <table>.getValueAt(<row>,<col>) shows the value of the cell prior to the change.
    Is there a way to ensure the setValueAt method of the TableModel is triggered before the JTable loses focus? Or is there a better (i.e. correct) way to accomplish this (ensuring a cell change is 'committed' to the table before
    losing focus)?

    Bug? What Bug? Sun considers this a feature....LOL
    Here is my work-around:
       public boolean editCellAt(final int row, final int col, EventObject e) {
          if (e instanceof MouseEvent) {
             if (((MouseEvent)e).getClickCount()<2) {               // single click on a cell other than the one being edited causes editing to stop
                if (isEditing())getCellEditor(getEditingRow(),getEditingColumn()).stopCellEditing();
                return false;
          return super.editCellAt(row,col,e);                         // cell editing on a keyevent or a double mouse click
       }This is will if the mouse is clicked elsewhere on the same table. I have a lot of other tricks for JTable and things....check out my web site at:
    http://www.aokabc.com
    ;o)
    V.V.

  • JTable Cell Focus Change

    Hi all,
    Is it possible to keep track the cell focus change in JTable so that I can perform appropriate validation. For example, user use the key to move from cell (2,3) to (2,4) or use the mouse to move from (2,4) to (5,3).
    I know that it is possible to use ListSelectionEvent on SelectionModel (for row change) and & ColumnModel (for change change) to do that. However, when both row & column change simultaneously, I need to do only 1 validation (in fact, the validation must have both information). My existing code gives me two separate event instead.
    Any idea ? Thanks in advance.

    This will be a decently hard nut to crack without making a slightly (or worse) cluttered solution.
    I've been part of a framework where applications-developer has requested solutions like you currently ask for. The solution we implemented was twofold.
    1) We made an centralised TableModel that people could use as-is or extend if nessecary. To this tablemodel we added a new set of events that could be consumed, or in some cases even replaced.
    The events was for instance 'beforeCellChange' and contained enough data on the current value, the new value, location in model and space for replacing any of the above values. Many more events was added as time went by as well.
    We made the event-listener fairly generalized and the type sent in the actual event, this allowed us to expand the events without having to change any interfaces. The drawback with this was that it forces the developer to check which type of event is happening, a bit like events happened in AWT 1.0.
    With the help of this, the developers just added the nessecary listeners to the table model and they could consume, change, validate any input to a table before it was committed.
    2) No good method for row-verification could really be found.
    There was a few futile tries, but since data could be entered in any order, the validation raised the amount of code with a order of magnitude. It does work, by listening on selection events, but quite a few extra checks has to be resolved, as instance with rows not validated etc etc.
    My recomendations, verify data carefully from events either from model or the table-editor. The result will most assurdly end in that you need to have an tablemodel on your own and also TableCellRenderer to accomplish all that you want to do.
    Yours sincerely
    Peter Norell

  • JTable cell focus outline with row highlight

    With a JTable, when I click on a row, the row is highlighted and the cell clicked has a subtle outline showing which cell was clicked.
    I would like to do that programatically. I can highlight the row, but I have not been able to get the subtle outline on the cell. My purpose is to point the user to the row and cell where a search found a match. I do not have cell selection enabled, because I want the whole row highlighted.
    My basic code is:
    table.changeSelection(irow, icol, false, false);
    table.scrollRectToVisible(table.getCellRect(irow, icol, true));I keep thinking I just need to find a way to "set focus" to the cell so the subtle outline is displayed, but I cannot find something like that.
    Does anyone have some ideas on how to activate that automatic outline on the cell? I prefer not to write custom cell renderers for this if possible.

    That seems unnecessarily complicated, the outline is the focused cell highlight border so requesting focus on the table should be enough.
    import java.awt.BorderLayout;
    import java.awt.EventQueue;
    import java.awt.Rectangle;
    import java.awt.event.ActionEvent;
    import javax.swing.*;
    public class TestTableFocus {
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    final JTable table = new JTable(10, 10);
                    JFrame frame = new JFrame("Test");
                    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                    frame.getContentPane().add(new JScrollPane(table));
                    frame.getContentPane().add(new JButton(
                      new AbstractAction("Focus cell") {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            table.changeSelection(5, 5, false, false);
                            centerCell(table, 5, 5);
                            table.requestFocusInWindow();
                        private void centerCell(JTable table, int x, int y) {
                            Rectangle visible = table.getVisibleRect();
                            Rectangle cell = table.getCellRect(x, y, true);
                            cell.grow((visible.width - cell.width) / 2,
                                    (visible.height - cell.height) / 2);
                            table.scrollRectToVisible(cell);
                    }), BorderLayout.PAGE_END);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
    }

  • Grab Focus in a JTable cell

    Hi,
    I have a JTable with only one editable column. The user should write some informations always in the same column and this will be checked: if the input.length=9, the whole row will be filled with data and a new row will be added. The focus remains in the same column at the last row. If the input.length!=9 , a message appears and the input should be deleted and the focus should remain in the same cell, in order to permit the user to input the correct information. By my code goes the focus to another cell
    import java.awt.*;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.DefaultTableModel;
    public class Test implements TableModelListener{
        DefaultTableModel model;
        JTable table;
        final int LIMIT=9;
       public Test(){
             createTable();
             JPanel leftPanel = new JPanel(new BorderLayout(6, 6));
             leftPanel.add(new JScrollPane(table), BorderLayout.CENTER);
             JPanel centerPanel = new JPanel(new GridLayout(1, 2, 6, 6));
             centerPanel.add(leftPanel);
             JPanel contentPane = new JPanel(new BorderLayout(6, 6));
             contentPane.add(centerPanel, BorderLayout.CENTER);
             JFrame f = new JFrame("Test Frame");
             f.setContentPane(contentPane);
             f.pack();
             f.setLocationRelativeTo(null);
             f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
             f.setVisible(true);
        public static void main(String[] args) {
            new Test();
      private void createTable() {
            table=new JTable();
            model = new DefaultTableModel() {
                    @Override
                    public boolean isCellEditable(int row, int col) {
                       if(col==1 ){
                            return true;
                       }else{
                            return false;
             model.addColumn("A");
             model.addColumn("B");
             model.addColumn("C");
             model.addColumn("D");
             model.addColumn("E");
             model.addColumn("F");
             model.addTableModelListener(this);
             table.setModel(model);
             table.setCellSelectionEnabled(true);
             table.setColumnSelectionAllowed(true);
             table.setRowSelectionAllowed(true);
             addEmptyRow() ;
        public void tableChanged(TableModelEvent e) {
           if(e.getColumn()==1 && model.getRowCount()>0){
               String line=(String)model.getValueAt(model.getRowCount()-1,1);
               if(line.length()==LIMIT){
                        addDataToLastRow(line);
               if(!line.isEmpty() && line.length()!=LIMIT){
                    if (table.getCellEditor() != null) {
                            table.getCellEditor().cancelCellEditing();
                    JOptionPane.showMessageDialog(null, "Information has wrong format");
                    loescheLastRow();
        private void addDataToLastRow(String info)  {
           int lastRow =model.getRowCount()-1;
           model.setValueAt(info, lastRow, 2);
           model.setValueAt(info, lastRow, 3);
           model.setValueAt(info, lastRow, 4);
           model.setValueAt(info, lastRow, 5);
           addEmptyRow();
        private void loescheLastRow() {
                model.removeRow(model.getRowCount() - 1);
                addEmptyRow();
        private void addEmptyRow() {
           Vector temp=new Vector();
           temp.add(model.getRowCount()+1);
           temp.add("");
           temp.add("");
           temp.add("");
           temp.add("");
           temp.add("" );
           model.addRow(temp);
           focusEmptyRow();
        void focusEmptyRow(){
           int row = model.getRowCount()-1;
           //System.out.println("row:"+row);
           int col = 1;
            // Set the cell in edit mode
            boolean success = table.editCellAt(row, col);
            //System.out.println("success:"+success);
            if (success) {
                // Select cell
                boolean toggle = false;
                boolean extend = false;
                table.changeSelection(row, col, toggle, extend);
                table.requestFocus();
    }

    hii,
    please change value for Column from 1 to 0, because Row&Column starts with 0
                       if(col==0 ){ // because you addedd only one column (==0), edidable flags doesn't works
                            return true;
                       }else{
                            return false;
    // and
           //System.out.println("row:"+row);
            int col = 0; // again you select 2nd. Column
            // Set the cell in edit mode... kopik

  • JTable, cells lost focus

    How can I get or listen to event when my cell lost focus ??

    The correct answer is to... well, that should be saved for the Swing forum. or alternatively, its in the text for THE FIRST google result for "jtable cell listener".

  • Catching a table cell focused event

    I have a JTable that I want users to input data into. One of the columns is a date field. In order to make sure the date is formatted and entered correctly, I've used a custom cell editor and renderer so the column looks like a DateTextField(a custom date field class). It works fine when the user clicks on the cell. But if the user hits the down arrow it doesn't set off the event that allows it to be edited as a DateTextField. Can you capture somekind of focus event on a particular cell and when you get a focus gained, programatically send the event that allows the cell to be edited? In case that didn't make sense, I'm trying to programatically simulate a mouse click on a table cell when it gets focus. Can it be done? If so, how? Thanks.

    Yes, I've tried that. The problem is what some people have described as a bug. There are two editing methods for JTable cells. One happens if the cell gets focus. There is no cursor and any underlying components are ignored. The second(the REAL edit) is when there is a cursor and the JTable understands that the cell is really a DateTextField. The only way I've found to achieve this is click on the cell. The number of clicks it takes depends on what the clickCountToStart is set to. However, if it's set to zero, it still takes one click.

  • Update jtable cell via numeric keypad

    Hi,
    I have a problem, trying to figure out how to input numbers in a jtextfield in a jtable cell, from a group of jbuttons (rendered as a numeric keypad). I can get the cell to focus, but when I click on one of the jbuttons in the keypad, the cell loses focus and nothing is printed. I can update the cell by directly typing from the keyboard; that works fine. But I'm lost when trying to do it from the touch-screen keypad. Can anyone point me in the right direction. I assume I need to attach additional listeners somewhere.
    Thanks in-advance.
    Lee

    I can get the cell to focus, Then the code for you button would need to be something like:
    String text = (String)table.getValueAt(...);
    String updated = text + button.getText();
    table.setValueAt(updated, ...);

  • Rendering multiple objects in JTable cells

    Hi,
    I wish to render in a single JTable cell (actually all cells in a Column) an ImageIcon and it's associated description string. The description string should be rendered below the ImageIcon, as it's caption. How can this be done? I assume a custom cell renderer, but the details are muddy at this point.
    thanks!
    JPL

    Thanks.
    I have looked atthe tutorial, but it focuses on a single object type per cell - I've got two different types (an ImageIcon and a String) that will occupuy a single cell.
    Taking a conceptual leap here, is it possible to create a new TableCellRenderer that houses a JPanel and GridLayout, and then place an ImageIcon and JLabel into that panel? I guess as long as things are JComponents, should I be OK with this approach?
    thanks,
    jpl

  • Making some JTable cells nonfocusable

    I have a JTable in which the TAB keys moves focus from cell to cell. Fine, but how can certain columns (or individual cells) be disabled from recieving focus ?? For "normal" JComponent-derived objects on a panel then I could call component.setFocusable(false); on the components I do not want to receive focus. What is the equivalent for a JTable cell given that it isn't a normal component: it is rendered via a TableRenderer ?

    I suppose you are using JDK 1.4 beacuse I am using it now. :-)
    I override the method:   protected boolean accept(Component aComponent) {
      } which is in the class LayoutFocusTraversalPolicy.

  • How to make Jtable cell empty onClick?

    Hi All,
    I have one requirement where I need to make the Jtable cell value empty on click or tab event. So, User does not have to do back space and delete whole string to edit that cell.
    Any idea?
    Thanks in advance.

    Hi camickr,
    Thanks for that reply. It did not work for me but Here is the thing.
    My requirement was : Client does not want to do back space in order do edit cell value when that cell clicked.
    I tried find the solution that, i can make that cell area as selected when it is clicked. my problem is solved. So, I tried to use Table select all editor.
    But here is what i found ......
    If I want that cell area selected, I need to do one more click(3 clicks at the same time) to select the value of that cell & I can put my new value without doing back space(stupid client requirement)
    Thanks for your help

  • Tab transversal while using JTextArea as a JTable cell editor..

    I'm working on a project that will use a JTable with a JTextArea cell editor to create a chart for classroom scheduling. Searching on Google, I found a way to use a JTextArea as a cell editor and render the cell properly. However, when editing a cell, pressing the Tab key inserts a tab, rather than leaving the cell and going to the next one, as happens with just a regular JTable. In fact, none of the keyboard shortcuts that work on a JTable work once the JTextArea cell editor is used. Does anyone know of any way to resolve this? Below is some code I'm using to create a sample GUI, just to verify that I can do this. Another question is would it be easier to use a bunch of JLabels and JTextAreas, remove the padding from those JTextAreas, and try to allow for Tab transversals between stand-alone JTextAreas, rather than JTextAreas as JTable cell editors?
    Thanks!
    package edu.elon.table;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class GUI
         private JFrame frame;
         private String[] columnNames = {"Classroom", "8:00-9:10", "9:25-10:35",
              "10:50-12:00", "12:15-1:25", "1:40-2:50", "1:40-3:20 (MW)",
              "3:35-5:15 (MW)", "5:30-7:10 (MW)"};
         private Object[][] data = {columnNames,
              {"ALAM 201 (42)\nENG 110 LAB", "", "", "", "", "", "", "", ""},
              {"ALAM 202 (42)\nDP/DVD", "", "", "", "", "", "", "", ""},
              {"ALAM 203 (38)\nDP/DVD", "", "", "", "", "", "", "", ""},
              {"ALAM 205 (40)\n", "", "", "", "", "", "", "", ""},
              {"ALAM 206 (39)\nSINK, TV/VCR", "", "", "", "", "", "", "", ""},
              {"ALAM 207 (40+)\nDP/DVD", "", "", "", "", "", "", "", ""},
              {"ALAM 214 (38)\nTV/VCR", "", "", "", "", "", "", "", ""},
              {"ALAM 215 (42)\nTV/VCR", "", "", "", "", "", "", "", ""},
              {"ALAM 216 (42)\n", "", "", "", "", "", "", "", ""},
              {"ALAM 301 (40)\nTV/VCR", "", "", "", "", "", "", "", ""},
              {"ALAM 302 (38)\nDP/DVD", "", "", "", "", "", "", "", ""},
              {"ALAM 304 (35)\nFRENCH", "", "", "", "", "", "", "", ""},
              {"ALAM 314 (30)\nDP, PSY, COMPUTER ASSISTED", "", "", "", "", "", "",
              {"ALAM 315 (40)\nPC LAB, DP/DVD", "", "", "", "", "", "", "", ""}};
         private JTable table;
         public GUI()
              frame = new JFrame();
              table = new JTable(data, columnNames);
              table.setRowHeight(table.getRowHeight()*2);
              TableColumnModel cModel = table.getColumnModel();
              TextAreaRenderer renderer = new TextAreaRenderer();
              TextAreaEditor editor = new TextAreaEditor();
              for (int i = 0; i < cModel.getColumnCount(); i++)
                   cModel.getColumn(i).setCellRenderer(renderer);
                   cModel.getColumn(i).setCellEditor(editor);
              frame.setLayout(new GridLayout(1,0));
              frame.add(table);
              frame.pack();
              frame.setVisible(true);
    public static void main (String[] args)
    GUI gui = new gui();
    * Written by Dr. Heinz Kabutz, found through online newsletter via Google.
    class TextAreaRenderer extends JTextArea
    implements TableCellRenderer {
    private final DefaultTableCellRenderer adaptee =
    new DefaultTableCellRenderer();
    /** map from table to map of rows to map of column heights */
    private final Map cellSizes = new HashMap();
    public TextAreaRenderer() {
    setLineWrap(true);
    setWrapStyleWord(true);
    public Component getTableCellRendererComponent(//
    JTable table, Object obj, boolean isSelected,
    boolean hasFocus, int row, int column) {
    // set the colours, etc. using the standard for that platform
    adaptee.getTableCellRendererComponent(table, obj,
    isSelected, hasFocus, row, column);
    setForeground(adaptee.getForeground());
    setBackground(adaptee.getBackground());
    setBorder(adaptee.getBorder());
    setFont(adaptee.getFont());
    setText(adaptee.getText());
    // This line was very important to get it working with JDK1.4
    TableColumnModel columnModel = table.getColumnModel();
    setSize(columnModel.getColumn(column).getWidth(), 100000);
    int height_wanted = (int) getPreferredSize().getHeight();
    addSize(table, row, column, height_wanted);
    height_wanted = findTotalMaximumRowSize(table, row);
    if (height_wanted != table.getRowHeight(row)) {
    table.setRowHeight(row, height_wanted);
    return this;
    private void addSize(JTable table, int row, int column,
    int height) {
    Map rows = (Map) cellSizes.get(table);
    if (rows == null) {
    cellSizes.put(table, rows = new HashMap());
    Map rowheights = (Map) rows.get(new Integer(row));
    if (rowheights == null) {
    rows.put(new Integer(row), rowheights = new HashMap());
    rowheights.put(new Integer(column), new Integer(height));
    * Look through all columns and get the renderer. If it is
    * also a TextAreaRenderer, we look at the maximum height in
    * its hash table for this row.
    private int findTotalMaximumRowSize(JTable table, int row) {
    int maximum_height = 0;
    Enumeration columns = table.getColumnModel().getColumns();
    while (columns.hasMoreElements()) {
    TableColumn tc = (TableColumn) columns.nextElement();
    TableCellRenderer cellRenderer = tc.getCellRenderer();
    if (cellRenderer instanceof TextAreaRenderer) {
    TextAreaRenderer tar = (TextAreaRenderer) cellRenderer;
    maximum_height = Math.max(maximum_height,
    tar.findMaximumRowSize(table, row));
    return maximum_height;
    private int findMaximumRowSize(JTable table, int row) {
    Map rows = (Map) cellSizes.get(table);
    if (rows == null) return 0;
    Map rowheights = (Map) rows.get(new Integer(row));
    if (rowheights == null) return 0;
    int maximum_height = 0;
    for (Iterator it = rowheights.entrySet().iterator();
    it.hasNext();) {
    Map.Entry entry = (Map.Entry) it.next();
    int cellHeight = ((Integer) entry.getValue()).intValue();
    maximum_height = Math.max(maximum_height, cellHeight);
    return maximum_height;
    * Written by Dr. Heinz Kabutz, found through online newsletter via Google.
    class TextAreaEditor extends DefaultCellEditor
    public TextAreaEditor() {
         super(new JTextField());
    final JTextArea textArea = new JTextArea();
    textArea.setWrapStyleWord(true);
    textArea.setLineWrap(true);
    JScrollPane scrollPane = new JScrollPane(textArea);
    scrollPane.setBorder(null);
    editorComponent = scrollPane;
    delegate = new DefaultCellEditor.EditorDelegate() {
    public void setValue(Object value)
    textArea.setText((value != null) ? value.toString() : "");
    public Object getCellEditorValue()
    return textArea.getText();
    }

    Using the KeyEvent manager and playing around with the JTextArea, I was able to get a JTable using JTextAreas as the cell editors that worked very close to the way the regular JTable works. You have to hit Tab twice to shift focus to another cell, or hit Tab once and then an arrow key. Also, Alt-Enter will allow you to enter a cell for editing. All of the changes were made to the TextAreaEditor class, which should now read as follows:
    class TextAreaEditor extends DefaultCellEditor implements KeyListener
         private int lastKeyCode;
         public TextAreaEditor(final JTable table) {
              super(new JTextField());
              lastKeyCode = KeyEvent.CTRL_DOWN_MASK;
              final JTextArea textArea = new JTextArea();
              textArea.setWrapStyleWord(true);
              textArea.setLineWrap(true);
              textArea.addKeyListener(this);
              textArea.setFocusable(true);
              textArea.setFocusAccelerator((char) KeyEvent.VK_ENTER);
              JScrollPane scrollPane = new JScrollPane(textArea);
              scrollPane.setBorder(null);
              scrollPane.setFocusable(false);
              editorComponent = scrollPane;
              delegate = new DefaultCellEditor.EditorDelegate() {
                   public void setValue(Object value) {
                        textArea.setText((value != null) ? value.toString() : "");
                   public Object getCellEditorValue() {
                        return textArea.getText();
         public void keyTyped(KeyEvent ke)
              // TODO Auto-generated method stub
         public void keyPressed(KeyEvent ke)
              if (ke.getKeyCode() == KeyEvent.VK_TAB)
                   ke.consume();
                   KeyboardFocusManager.getCurrentKeyboardFocusManager()
                             .focusNextComponent();
                   return;
              if (ke.getKeyCode() == KeyEvent.VK_TAB && ke.isShiftDown())
                   ke.consume();
                   KeyboardFocusManager.getCurrentKeyboardFocusManager()
                             .focusPreviousComponent();
                   return;
              if ((lastKeyCode == KeyEvent.CTRL_DOWN_MASK) &&
                        (ke.getKeyCode() == KeyEvent.VK_ENTER))
                   ke.consume();
                   editorComponent.requestFocus();
              else
                   lastKeyCode = ke.getKeyCode();
         public void keyReleased(KeyEvent ke)
              // TODO Auto-generated method stub
         }

  • Custom JTable cell editor problem

    I have a custom JTable cell editor which is a JPanel with 2 JtextFields, One for a name, the other for a data value. My problem lies in when the the cell is selected and then the user start typing. The JTextfield outline shows up, but there is no carat. I can only edit the cell when I click the mouse in it again. I have my isCellEditable method set to only allow editing on 2 mouse clicks, but I did try it with just returning true and had the same problem. Please help.
    Code:
    class cellValue {
    String name;
    String data;
    Color nameColor;
    Color dataColor;
    Font font;
    public cellValue(String n, String d, Color nC, Color dC, Font ff){
    name = n;
    data = d;
    nameColor = nC;
    dataColor = dC;
    font = ff;
    } //end class
    public class TextFieldCellEditor extends JPanel implements TableCellRenderer, TableCellEditor{
    private EventListenerList listenerList = new EventListenerList();
    private ChangeEvent event = new ChangeEvent(this);
    private cellValue s;
    private int e_row=0;
    private int e_col=0;
    private JTextField ta;
    private JTextField tb;
    public TextFieldCellEditor() {
    setLayout(new GridBagLayout());
    ta = new JTextField();
    tb = new JTextField();
    tb.setHorizontalAlignment(SwingConstants.RIGHT);
    add(ta, new GridBagConstraints(0,0,1,1,0.6,0.0,java.awt.GridBagConstraints.WEST,java.awt.GridBagConstraints.BOTH,new Insets(0,1,0,0),0,0));
    add(new JLabel(" "),new GridBagConstraints(1,0,1,1,0.1,0.0,java.awt.GridBagConstraints.WEST,java.awt.GridBagConstraints.BOTH,new Insets(0,1,0,0),0,0));
    add(tb, new GridBagConstraints(2,0,1,1,0.3,0.0,java.awt.GridBagConstraints.EAST,java.awt.GridBagConstraints.BOTH,new Insets(0,1,0,0),0,0));
    } //end init
    public Component getTableCellRendererComponent(JTable table, Object value,boolean isSelected,
    boolean hasFocus,int row, int column) {
    s = (cellValue)value;
    e_row = row;
    e_col = column;
    ta.setText(s.name);
    tb.setText(s.data);
    ta.setFont(s.font);
    tb.setFont(s.font);
    ta.setForeground(s.nameColor);
    tb.setForeground(s.dataColor);
    setForeground(table.getForeground());
    setBackground(table.getBackground());
    ta.setBackground(table.getBackground());
    tb.setBackground(table.getBackground());
    ta.setCaretColor(Color.WHITE);
    tb.setCaretColor(Color.WHITE);
    return (JComponent)(this);
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
    return (getTableCellRendererComponent(table, value,isSelected, true, row, column));
    public boolean isCellEditable(EventObject e) {
    if (e instanceof MouseEvent) {
    return ((MouseEvent)e).getClickCount() >= 2;
    } return true;
    // return true;
    public boolean shouldSelectCell(EventObject anEvent) {
    return (true);
    public void cancelCellEditing() {
    public boolean stopCellEditing() {
    fireEditingStopped();
    return (true);
    public Object getCellEditorValue() {
    return (ta.getText());
    public void addCellEditorListener(CellEditorListener l){
    try {
    SwingUtilities.invokeLater(
    new Runnable() {
    public void run() {requestFocus();}
    } catch (Exception e) {};
    listenerList.add(CellEditorListener.class, l);
    public void removeCellEditorListener(CellEditorListener l) {
    listenerList.remove(CellEditorListener.class, l);
    protected void fireEditingStopped(){
    Object[] listeners = listenerList.getListenerList();
    for (int i = listeners.length - 2; i >= 0; i -= 2)
    ((CellEditorListener)listeners[i+1]).editingStopped(event);
    protected void fireEditingCanceled() {
    Object[] listeners = listenerList.getListenerList();
    for (int i = listeners.length - 2; i >= 0; i -= 2)
    ((CellEditorListener)listeners[i+1]).editingCanceled(event);
    } //end class

    Thanks again for the repley.
    I tried removing the celleditorlistener and using the setSurrenderFocusOnKeystroke, but it did not work. The textfield is editable;
    I did change:
    public void addCellEditorListener(CellEditorListener l){
    try {
    SwingUtilities.invokeLater(
    new Runnable() {
    public void run() {ta.requestFocus();}
    } catch (Exception e) {};
    listenerList.add(CellEditorListener.class, l);
    }This allows the first textfield to request focus and this seems to work. But when I highlight a cell, then start typing, the first character I type puts me into the editor, but it is lost. Example:
    I type hello
    and get ello in the cell. Then when I press enter the input is excepted and the selection goes to the next cell, but I cannot move the Highlight cursor at all, seems locked. The only way I can continue to the next cell is to use the mouse.
    You said you had a cell editor working. Would you care to share as an example. This is killing me to get this to work properly.
    Thanks again
    Dave

  • Java3D in a JTable cell ?

    Hello,
    I would like to put a Canvas3D component in a JTable cell, is there a way to do that ?
    If not, I think it should be possible to only get a generated picture of the 3D scene with the off screen mode of the Canvas3D, and then put it as an ImageIcon of the JTable cell.
    I tried this, but I got this error message : "OpenGL 1.2 or better is required (GL_VERSION=1.1)" even though I have the 1.4 version...
    Anyway, I would prefer to find a way to put the Canvas3D component in the cell, in order to be able to use the mouse to change the 3D scene.
    Thank you

    Are you using an annonymous inner class for your mouse listener? I think this coudl cause some problems in your case.
    Try creating your own listener class e.g.
    class myListener extends MouseListener(){....}
    in this class, add a field such as 'name' - set with the constructor. So when you create your "outer table" write something like..
    outerTable.addMouseListener(new myListener("outer"));
    And when you create the inner table, write something like
    innerTable.addMouseListener(new myListener("inner"));
    Then when you capture Mouse click events, you can work out whether the click came from an outer table or inner table:
    public void mouseClicked(MouseEvent e){
    if(this.name.equals("inner")).....
    else.....
    In this way you should avoid the problem of knowing which table was clicked on...and still us the same mouse listener.
    I hope this is what you mean!
    Chris.

  • Insert only one character in a JTable cell

    Hi1
    Can anybody tell me how i can do in order to insert only one character in a JTable cell? For example, i'ld like that user inserts only
    a and not abcd in a JTable cell... can anyone halp me?
    Thanks

    Have you tried
    table.getColumn(0).setCellEditor(new DefaultCellEditor(new JFormattedTextField("[A-Z]")));
    I haven't tried it. You might look at some of these.
    http://search.java.sun.com/search/java/index.jsp?qp=&nh=10&qt=%2B%22new+defaultcelleditor%22+%2B%22new+jformattedtextfield%22&col=javaforums&x=39&y=17

Maybe you are looking for