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".

Similar Messages

  • How to catch cell lost focuse event of matrix

    Dear all
    can you tell me how to catch the cell lost fouc event of matrix.
    i want to check the value is entered the that cell, which is not greter than the extising value..
    thanks in advance......

    Hi
    For that you can use either validate or lost focus event
    Private Sub SBO_Application_ItemEvent(ByVal FormUID As String, ByRef pVal As SAPbouiCOM.ItemEvent, ByRef BubbleEvent As Boolean) Handles SBO_Application.ItemEvent
            ' BubbleEvent sets the behavior of SAP Business One.
            ' False means that the application will not continue processing this event.
            ' Validate event
            If (pVal.FormType = 133) And (pVal.ItemUID = 38) And (pVal.ColUID = 1) And _
              (pVal.EventType = SAPbouiCOM.BoEventTypes.et_VALIDATE) Then
                If (pVal.Before_Action) Then
                    'write your code
                End If
            End If
            'Lost focus event
            If (pVal.FormType = 133) And (pVal.ItemUID = 38) And (pVal.ColUID = 1) And _
             (pVal.EventType = SAPbouiCOM.BoEventTypes.et_LOST_FOCUS) Then
                If (pVal.Before_Action) Then
                    'write your code
                End If
            End If
        End Sub
    Hope this helps
    Regards
    Arun

  • Change particular cell color when finised editing and when lost focus

    Hi, i want to create a table which its particular cell can change its color automatically to red if the value in cell in column in two is smaller than column cell value in column 1 when user finish typed a value or if the cell has lost focus. I've wrote a code for the renderer but how should I use action, KeyListener or MouseLister or both
    * File ColouredCellRenderer.java
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.JTable;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.DefaultTableCellRenderer;
    public class ColouredCellRenderer extends DefaultTableCellRenderer implements TableCellRenderer{
        private Object col1Value, col2Value;
        public ColouredCellRenderer(Object args1, Object args2){
            this.col1Value = args1;
            this.col2Value = args2;
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
              return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
         protected void setValue(Object v){
              super.setValue(v);
            if((col1Value != null) & (col2Value != null)){
                int x = Integer.parseInt(col1Value.toString());
                int y = Integer.parseInt(col2Value.toString());
                if(x > y){
                    this.setBackground(Color.RED);
                else{
                    this.setBackground(Color.GREEN);
    }

    All you should need is the cell renderer to achieve that effect. Whenever the table needs to render a cell it will call the method
    getTableCellRendererComponent(...);This method in turn returns a component showing what the cell should look like. The DefaultTableCellRenderer extends JLabel, so you are meant to customize the label (based on parameters that were passed) and return this* at the end of the method.
    public Component getTableCellRendererComponent(...) {
             return this;
    }This one label is used to render all the cells of all the columns that the cell renderer is assigned to. Since you want some cells too be red, you should call setBackground(Color.red)+ when the conditions are appropriate or null otherwise.

  • 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, ...);

  • 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

  • Combobox Autocomplete editor inside Jtable cell

    I have a custom combobox editor which supports the autocomplete feature as follows:
    as soon as the user keys in any character, this editor searches for the item that starts with keyed in character. This item is displayed in the editor text field and the combobox popup is set to visible and the this item is set to selected.
    this editor works fine when standalone. but the popup fails to become visible when this combobox is used as an celleditor inside jtable. infact the focus is lost from the entire table.
    can anyone suggest the possible reason (and solution if possible).
    following are the code snippets for the same: -
         private TableCellEditor addCellEditor() {
              final JComboBox myJComboBox = new PIComboBox();
              myJComboBox.setModel(new DefaultComboBoxModel(// some data model //));
              //change the size of popup window
              BasicComboPopup comboPopup = null;
              for (int i=0, n=getUI().getAccessibleChildrenCount(myJComboBox); i<n; i++) {
                  Object component = getUI().getAccessibleChild(myJComboBox, i);
                  if (component instanceof BasicComboPopup) {
                   comboPopup = (BasicComboPopup) component;
                   break;
              if(null != comboPopup)
                  comboPopup.setLayout(new GridLayout(1,1));
                  comboPopup.setPopupSize(new Dimension(200, 150));
              myJComboBox.setEditable(true);
              myJComboBox.setEditor(new ComboBoxAutoCompleteEditor(myJComboBox, 3));
              myJComboBox.setUI(new ComboBoxAutoCompleteUI());
              TableCellEditor myCellEditor = new DefaultCellEditor(myJComboBox );
              return myCellEditor;
         public class ComboBoxAutoCompleteEditor extends BasicComboBoxEditor {
         public ComboBoxAutoCompleteEditor(PIComboBox comboBox, int maxLength) {
              super();
              this.comboBox = comboBox;
              this.maxLength = maxLength;
         @Override
         public Component getEditorComponent() {
              if(null == editorComponent)
                   editorComponent = new PITextField();
                   editorComponent.setBorder(null);
                   editorComponent.setMaxLength(maxLength);
                   editorComponent.setDocument(getDocument());
              return editorComponent;
         private ComboBoxAutoCompleteDocument getDocument()
              if(null == comboBoxAutoCompleteDocument)
                   comboBoxAutoCompleteDocument = new ComboBoxAutoCompleteDocument(
                             this.comboBox.getModel());
                   comboBoxAutoCompleteDocument.addDocumentListener(new ComboBoxDocumentListener());
              return comboBoxAutoCompleteDocument;
         private class ComboBoxDocumentListener implements DocumentListener {
              public void insertUpdate(DocumentEvent e) {
                   if (updatingSelection) {
                        return;
                   SwingUtilities.invokeLater(new ScrollHandler());
              public void removeUpdate(DocumentEvent e) {
              public void changedUpdate(DocumentEvent e) {
         private class ScrollHandler implements Runnable {
              private String scrollToString;
              private int scrollToRow;
              private ScrollHandler() {
                   try {
                        int length = getDocument().getLength();
                        String text = getDocument().getText(0, length);
                        scrollToRow = -1;
                        scrollToString = (String) comboBox.getSelectedItem();
                        ComboBoxModel model = comboBox.getModel();
                        int size = model.getSize();
                        for (int i = 0;  i < size; i++) {
                             String item = model.getElementAt(i).toString();
                             if (item.startsWith(text)) {
                                  scrollToString = item;
                                  break;
                             scrollToRow++;
                   } catch (BadLocationException ble) {
                        // TODO: handle
                        ble.printStackTrace();
              public void run() {
                   final int matchCount = getDocument()
                             .getCurrentMatchCount();
                   updatingSelection = true;
                   comboBox.setSelectedItem(scrollToString);
                   if (comboBox.isDisplayable())
                        comboBox.showPopup();
                   updatingSelection = false;
                   if (scrollToRow != comboBox.getItemCount() - 1) {
                        ComboBoxAutoCompleteUI ui = (ComboBoxAutoCompleteUI) comboBox
                                  .getUI();
                        JList popupList = ui.getPopupList();
                        int rowsToAdd = Math.min(comboBox.getMaximumRowCount(), comboBox
                                  .getItemCount()
                                  - scrollToRow - 1);
                        popupList.scrollRectToVisible(popupList.getCellBounds(
                                  scrollToRow + rowsToAdd, scrollToRow + rowsToAdd));
                   if (matchCount > 0) {
                        ((PITextField)getEditorComponent()).setSelectionStart(matchCount);
                        ((PITextField)getEditorComponent()).setSelectionEnd(
                                  getDocument().getLength());
         public class ComboBoxAutoCompleteUI extends BasicComboBoxUI {
             JList getPopupList() {
                 return popup.getList();
         public class ComboBoxAutoCompleteDocument extends PlainDocument {
         public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
            currentMatchCount = getLength() + str.length();
            String currentText = getText(0, getLength());
            //search the matching string here
            offs = 0;
            remove(0, getLength());
            super.insertString(offs, str, a);
         **************

    You need to create a custom CellEditor which will prevent these problems from occurring. The explanation behind the problem and source code for the new editor can be found at Thomas Bierhance's site http://www.orbital-computer.de/JComboBox/. The description of the problem and the workaround are at the bottom of the page.

  • 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.

  • 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
         }

  • How to force a jtable to loose focus

    hi all
    i've got a jTextArea and a Jtable, and i want my jTable to loose focus when my JTextArea gains it
    i've the metod jTextAreaFocusGained(); what shall i write inside it to make the table loose focus?
    thanx
    sandro

    Hi,
    I guess, there is a missunderstanding in that, what you want to do and that, what you say, you want.
    The focus is a unique thing - only one component can have the focus at one time - so, when your textfield has gained focus, the component that formerly has had the focus, lost it already - so, there is nothing else to do.
    I guess, you want another thing, perhaps to clear the selection of the JTable or something like this.
    greetings Marsian

  • Can not show the JCheckBox in JTable cell

    I want to place a JCheckBox in one JTable cell, i do as below:
    i want the column "d" be a check box which indicates "true" or "false".
    String[] columnNames = {"a","b","c","d"};
    Object[][] rowData = {{"", "", "", Boolean.FALSE}};
    tableModel = new DefaultTableModel(rowData, columnNames);
    dataTable = new JTable(tableModel);
    dataTable.getColumnModel().getColumn(3).setCellEditor(new DefaultCellEditor(new JCheckBox()));
    But when i run it, the "d" column show the string "false" or "true", not the check box i wanted.
    I do not understand it, can you help me?
    Thank you very much!
    coral9527

    Do not use DefaultTableModel, create your own table model and you should implement the method
    getColumnClass to display the boolean as checkbox ...
    I hope the following colde snippet helps you :
    class MyModel extends AbstractTableModel {
              private String[] columnNames = {"c1",
    "c2"};
    public Object[][] data ={{Boolean.valueOf(true),"c1d1"}};
         public int getColumnCount() {
         //System.out.println("Calling getColumnCount");
         return columnNames.length;
    public int getRowCount() {
    //System.out.println("Calling row count");
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    return true;
    * Don't need to implement this method unless your table's
    * data can change.
    public void setValueAt(Object value, int row, int col) {
    data[row][col] = value;
    fireTableCellUpdated(row, col);

  • Shading part of a JTable Cell dependent upon the value of the cell

    Hi
    Was hoping some one woudl be able to provide some help with this. I'm trying to create a renderer that will "shade" part of a JTable cell's background depending upon the value in the cell as a percentage (E.g. if the cell contains 0.25 then a quarter of the cell background will be shaded)
    What I've got so far is a renderer which will draw a rectangle whose width is the relevant percentage of the cell's width. (i.e. the width of the column) based on something similar I found in the forum but the part I'm struggling with is getting it to draw this rectangle in any cell other than the first cell. I've tried using .getCellRect(...) to get the x and y position of the cell to draw the rectangle but I still can't make it work.
    The code for my renderer as it stands is:
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.table.TableCellRenderer;
    public class PercentageRepresentationRenderer extends JLabel implements TableCellRenderer{
         double percentageValue;
         double rectWidth;
         double rectHeight;
         JTable table;
         int row;
         int column;
         int x;
         int y;
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
              if (value instanceof Number)
                   this.table = table;
                   this.row = row;
                   this.column = column;
                   Number numValue = (Number)value;
                   percentageValue = numValue.doubleValue();
                   rectHeight = table.getRowHeight(row);
                   rectWidth = percentageValue * table.getColumnModel().getColumn(column).getWidth();
              return this;
         public void paintComponent(Graphics g) {
            x = table.getCellRect(row, column, false).x;
            y = table.getCellRect(row, column, false).y;
              setOpaque(false);
            Graphics2D g2d = (Graphics2D)g;
            g2d.fillRect(x,y, new Double(rectWidth).intValue(), new Double(rectHeight).intValue());
            super.paintComponent(g);
    }and the following code produces a runnable example:
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    public class PercentageTestTable extends JFrame {
         public PercentageTestTable()
              Object[] columnNames = new Object[]{"A","B"};
              Object[][] tableData = new Object[][]{{0.25,0.5},{0.75,1.0}};
              DefaultTableModel testModel = new DefaultTableModel(tableData,columnNames);
              JTable test = new JTable(testModel);
              test.setDefaultRenderer(Object.class, new PercentageRepresentationRenderer());
              JScrollPane scroll = new JScrollPane();
              scroll.getViewport().add(test);
              add(scroll);
         public static void main(String[] args)
              PercentageTestTable testTable = new PercentageTestTable();
              testTable.pack();
              testTable.setVisible(true);
              testTable.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }If anyone could help or point me in the right direction, I'd appreciate it.
    Ruanae

    This is an example I published some while ago -
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Fred120 extends JPanel
        static final Object[][] tableData =
            {1, new Double(10.0)},
            {2, new Double(20.0)},
            {3, new Double(50.0)},
            {4, new Double(10.0)},
            {5, new Double(95.0)},
            {6, new Double(60.0)},
        static final Object[] headers =
            "One",
            "Two",
        public Fred120() throws Exception
            super(new BorderLayout());
            final DefaultTableModel model = new DefaultTableModel(tableData, headers);
            final JTable table = new JTable(model);
            table.getColumnModel().getColumn(1).setCellRenderer( new LocalCellRenderer(120.0));
            add(table);
            add(table.getTableHeader(), BorderLayout.NORTH);
        public class LocalCellRenderer extends DefaultTableCellRenderer
            private double v = 0.0;
            private double maxV;
            private final JPanel renderer = new JPanel(new GridLayout(1,0))
                public void paintComponent(Graphics g)
                    super.paintComponent(g);
                    g.setColor(Color.CYAN);
                    int w = (int)(getWidth() * v / maxV + 0.5);
                    int h = getHeight();
                    g.fillRect(0, 0, w, h);
                    g.drawRect(0, 0, w, h);
            private LocalCellRenderer(double maxV)
                this.maxV = maxV;
                renderer.add(this);
                renderer.setOpaque(true);
                renderer.setBackground(Color.YELLOW);
                renderer.setBorder(null);
                setOpaque(false);
                setHorizontalAlignment(JLabel.CENTER);
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col)
                final JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
                if (value instanceof Double)
                    v = ((Double)value).doubleValue();
                return renderer;
        public static void main(String[] args) throws Exception
            final JFrame frame = new JFrame("Fred120");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(new Fred120());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
    }

  • Text Input header render lost focus on grid data refresh

    I have create a text input  type header render for datagrid as a filter.  On change event I am dispatching my custom event which refresh the datagrid from
    server side filter but in this the text input in which I am typing lost focus and gain it again on mouce click
    Alreadt tried setFocus and focusManager
    Thanks
    Abha

    I'd probably wait for updateComplete and then call setFocus again.  And/or
    use callLater to defer setting focus.

  • JTable Cell text selection Problem.

    I am using Tab key while navigating with the Cells.While focus reaches into a cell,the cell is selected but not the cell content.So I use BACKSPACE to delete each word of the cell.I want to Select a cell content(i.e. Text) when I am move Tab keys to select cells.Please help me..........,u may send a mail at [email protected]

    Do u need this feature to the whole table or else for the perticular cell in the table?
    Are you using your own renderer or editor to the perticular cell ?,
    this issue is related to Renderer and Editor, so if i know your requirement , then only it is easy to implement.

  • How to write an element in a  JTable Cell

    Probably it's a stupid question but I have this problem:
    I have a the necessity to build a JTable in which, when I edit a cell and I push a keyboard button, a new Frame opens to edit the content of the cell.
    But the problem is how to write something in the JTable cell, before setting its model. Because, I know, setCellAT() method of JTree inserts the value in the model and not in the table view. And repainting doesn't function!
    What to do??
    Thanks

    Hi there
    Depending on your table model you should normally change the "cell value" of the tablemodel.
    This could look like:
    JTable table = new JTable();
    TableModel model = table.getModel();
    int rowIndex = 0, columnIndex = 0;
    model.setValueAt("This is a test", rowIndex, columnIndex);
    The tablemodel should then fire an event to the view (i.e. JTable) and the table should be updated.
    Hope this helps you

Maybe you are looking for

  • HT201269 Re-backed up an empty phone during a restore. Help!

    During a restore and back up, it re backed up with an empty phone. Now I am unable to put everything i had back on my phone. Help ? surely its hidden in a folder on my PC somewhere. I thought you could restore from previous backups but its not an opt

  • GRC10: Mandatory Comments on SPM Log Review

    Gurus, is there a way to make comments mandatory when approving the SPM Log Report that the controller reviews? I have set the Task Setting to Comments Mandatory -> Approval (activated the workflow). Yet this has no impact. The controller is not forc

  • How do I open the new (orange) Firefox menu via the keyboard?

    Its not listed in the keyboard shortcuts page! That page also includes Alt-F10, which no longer does anything.

  • Importing of PSDs and others

    I have a large number of older (pre digital camera) image files organized in the finder. When navigating to these folders via Aperture/import many, many of the image files do not even show up. Of course, many of these files are layered PSDs and/or va

  • Why do I need to install Office a second time?

    I have a Mac 27' and its great! I love it lol but I have a little problem. I've installed Microsoft office 365 on my computer and my brother made another account for the house to keep separate from his account. When I go to the house account I have t