JTextField in a JTable cell

Hi,
I have just started coding in Swings and would like to find out ways by which I can add JtextField in a JTable cell. Is there any?
Thanks in Advance.
Cheena

There sure is. The thing you're looking for is the cells TableCellEditor. Check out this tutorial, it will explain how to use CellEditors, you should have no diffculties adapting the example to your needs (otherwise just post again :-)
http://java.sun.com/docs/books/tutorial/uiswing/components/table.html

Similar Messages

  • Can't get focused a JTextField within a JTable cell

    I have a table and I placed a cell editor with a JText field on it for all cell editing,
    I want to do things when the focus is lost or gained and my app works fine when a cell is double clicked or f2 is pressed, but when a cell is selected (without double clicking) and just begin typing it produces no focus gained event.
    I tried by calling grabFocus method of that jTextField within the overriden prepareEditor method of the JTable but it doesn't get focus (doesn't even gains and loses it :s )
    Does anyone have an idea of how to force this component to grab focus?
    Thanks

    Hai,
    dont add the FocusListener to the EditorComponent.
    Try to use the JTable Functions - like this:
    import javax.swing.event.ChangeEvent;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.EventObject;
    import javax.swing.*;
    public class Test extends JFrame
         JTable table;
         JTextArea text;
         JScrollPane scroll;
         JTextField cellTextField;
         Test()
              DefaultTableModel model = new DefaultTableModel();
              cellTextField = new JTextField();
              text = new JTextArea();
              text.setEditable(false);
              scroll = new JScrollPane();
              scroll.setViewportView(text);
              table = new JTable(model){
                   @Override
                   public Component prepareEditor(TableCellEditor editor, int row, int column) {
                        text.append("Better use this to Start Edit!\n");
                        return super.prepareEditor(editor, row, column);
                   @Override
                   public void editingStopped(ChangeEvent e) {
                        text.append("Better use this to Stop Edit!\n");
                        super.editingStopped(e);
              model.addColumn("Column 1");
              model.addColumn("Column 2");          
              model.addRow(new String [] {"Cell 1", "Cell 2"});
              table.setCellSelectionEnabled( true );
              table.getColumnModel().getColumn(0).setCellEditor( new DefaultCellEditor(cellTextField));
              table.getColumnModel().getColumn(1).setCellEditor( new DefaultCellEditor(cellTextField));
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(table, BorderLayout.NORTH);
              getContentPane().add(scroll, BorderLayout.CENTER);
              setSize(300, 300);
              setVisible(true);
              setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
         public static void main(String[] args)
              new Test();
    }

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

  • JTextField/JTable-cell Button

    Is there any known efficient methods of creating the JTextField or JTable-cell Button as like in Forte's Component Inspector window where you click on the property value field and the value is displayed just left of a small button labelled "..." ie: [some text field with value][...] also referred to as the "ellipsis" buttons, or will most answers to this question simply describe the layout of a JField-JButton combination? The action from clicking on the [...] button aligned right of the JTextField simply invokes or displays a larger input interface in which upon completion of the entered data, returns the input to the related JTextField.
    Thanks to anybody for any help with this, and perhaps in return, I may be able to answer any non-gui java questions, or some not so unfamilliar GUI questions.

    Hello StanislavL and Lutianxiong,
    I remember asking this question some time ago, and the time has come again for me to seek this functionality. I have finally achieved the functionality and thought I would post the answer for anybody else. I had not realized that I had recieved a solution/reply to my original question as I come here to post the answer, and in fact, my solution does appear to be very similiar to your reply, StanislavL. As for you, Lutianxiong and other seekers of this info, here is my solution with a JFileChooser style input for the 3rd column which only shows gif,jpg and png files:
    <code>
    ------------- TableCellFileInput.java -------------------
    public class TableCellFileInput extends javax.swing.JPanel {
    private String extensions[];
    public TableCellFileInput(String fileExtensions[]) {
    extensions = fileExtensions;
    self = this;
    initComponents();
    private void initComponents() {
    valueField = new javax.swing.JTextField();
    fileButton = new javax.swing.JButton();
    setLayout(new java.awt.BorderLayout());
    valueField.setText("jTextField1");
    add(valueField, java.awt.BorderLayout.CENTER);
    fileButton.setText("...");
    fileButton.setMargin(new java.awt.Insets(0, 2, 0, 2));
    fileButton.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    fileButtonActionPerformed(evt);
    add(fileButton, java.awt.BorderLayout.EAST);
    private void fileButtonActionPerformed(java.awt.event.ActionEvent evt) {
    String filePath = valueField.getText();
    if(filePath != null && filePath.length() > 0) {
    filePath = new java.io.File(filePath).getParent();
    javax.swing.JFileChooser chooser
    = new javax.swing.JFileChooser(filePath);
    chooser.setFileFilter(new ImageFilter());
    int returnVal = chooser.showOpenDialog(this);
    if(returnVal == javax.swing.JFileChooser.APPROVE_OPTION) {
    valueField.setText(chooser.getSelectedFile().getAbsolutePath());
    class ImageFilter extends javax.swing.filechooser.FileFilter {
    public boolean accept(java.io.File f) {
    if(f.isDirectory()) return true;
    String fName = f.getName();
    if(extensions != null) {
    for(int i=0;i<extensions.length;i++) {
    if(fName.endsWith(extensions[ i ])) return true;
    return false;
    public String getDescription() {
    return DESCRIPTION;
    class CustomCellEditor extends javax.swing.AbstractCellEditor
    implements javax.swing.table.TableCellEditor {
    public Object getCellEditorValue() {
    return valueField.getText();
    public java.awt.Component getTableCellEditorComponent(javax.swing.JTable table, Object value, boolean isSelected, int row, int column) {
    System.out.println("fileEditor");
    if(value == null) valueField.setText("");
    else valueField.setText(value.toString());
    return self;
    public void setColumn(javax.swing.table.TableColumn column) {
    column.setCellEditor(new CustomCellEditor());
    private javax.swing.JButton fileButton;
    private javax.swing.JTextField valueField;
    private static final String DESCRIPTION = "Image File Filter";
    private java.awt.Component self;
    ------------- TestTable .java -------------------
    public class TestTable extends javax.swing.JFrame {
    public TestTable() {
    editorField = new javax.swing.JTextField();
    String fileExts[] = {"gif","jpg","png"};
    fileEditorField = new TableCellFileInput(fileExts);
    initComponents();
    javax.swing.table.TableColumn column
    = jTable1.getColumn("Title 3");
    fileEditorField.setColumn(column);
    private void initComponents() {
    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    exitForm(evt);
    jTable1.setModel(new javax.swing.table.DefaultTableModel(
    new Object [][] {
    {null, null, null, "cats"},
    {null, null, null, "dogs"},
    {null, null, null, "mice"},
    {null, null, null, "birds"}
    new String [] {
    "Title 1", "Title 2", "Title 3", "Title 4"
    Class[] types = new Class [] {
    java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.String.class
    public Class getColumnClass(int columnIndex) {
    return types [columnIndex];
    jScrollPane1.setViewportView(jTable1);
    getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
    java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    setBounds((screenSize.width-400)/2, (screenSize.height-300)/2, 400, 300);
    private void exitForm(java.awt.event.WindowEvent evt) {
    System.exit(0);
    public static void main(String args[]) {
    new TestTable().show();
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField editorField;
    private TableCellFileInput fileEditorField;
    </code>

  • Setting two JTextFields inside JTable cell

    hi,
    I am really stick trying to figure out how to set two cells inside a JTable cell. This needs to be done because if there is a value already inside the cell then i want to drop another value - this new value should be displayed inside another cell but along with the other value already in the cell.
    I assume that i would need to create two JTextFields.
    But can anyone help me further please.

    That should be a simple issue of customizing table cell editor and renderer.
    See tutorials.

  • Way to listen for change in JTable cell?

    I am having troubles trying to catch a key event while the user is entering text inside a given JTable cell (x/y location). The JTable only seems to manage String objects in it's cells so I can't place a JTextField in there with a KeyListener on it.
    Currently, I can only get control of the application once the user has left the cell they are editing.
    Does anyone have an example of a JTable 'cell KeyListener' scenario? At this point I want to see if I can print 'hello world' each time I type a character within a cell. Then I'll go from there....

    If you want to know when the contents of a cell have been updated you should use a TableModelListener.
    If you want to know when a character is added/removed from the cell editor then you need to first understand how this works with a simple text field.
    Typically you would use a DocumentListener to receive notifies of a change to the text field. However, within the DocumentEvent you wouldn't be able to change the text field as this notification comes after the text field has already been updated.
    If you need to ability to intercept changes to the text field before they happen, then you would need to use a DocumentFilter. An example of using a DocumentFilter is given in the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html#filter]Text Component Features.
    Once you get your regular text field working the way you want, the next step to create a DefaultCellEditor using this JTextField and use this editor in your JTable. The above tutorial also has a section on using editors in a table.

  • JSPinner in a JTable Cell

    Plz let me know how to add a JSpinner component in a JTable cell.I was able to add JCOmbo and Jtextfield,,but i need to add a JSpinner...how to do that...
    regds
    Subhash.K

    thank you for responce
    Object[][] data1 = {
                              {"Datum", new Spinner(new SpinnerNumberModel(200,1,255,1)),""}, //this sets the innitial value to 200
                             {"ActiveAntenna", new Boolean(true),""}
    String[] colname1 = {"Variable","Value","Unit"};do you have an idea how to set the value, min, and step in my Spinner class
    regards
    gebi

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

  • JPanel as a JTable Cell Editor

    I want to use a JPanel and as a JTable Cell Editor. The JPanel consists of a JTextField and a JButton. When I bring it up as an editor all works fine until I change the text field value and click on another line causing the editor to be stopped. Then my app seems to go into a processing frenzy which effectively stop me from doing anything else (the app has trouble repainting itself as well).
    I'm assuming I'm not passing an important message from the JPanel to the text field but am not sure. Has anyone had success in doing this? What am I missing?
    Thanks in advance,
    Phillip

    Looks like I was too quick off the draw in posting this.
    My problem was due to some old "expiremental" code that was processing key binding.
    Once I removed the unnecessary code all worked well.

  • 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

  • Cell Editor to limit characters in jtable cell

    Hello Java Gods,
    Can anyone help me or write for me a custom cell editor/renderer to limit the max number of characters in a jtable cell to be 10? By this, I mean, the user should not be able to type more than 10 characters in this particular cell.
    Any help would be greatly appreciated. I have to hand in this code before this evening. So please please help me folks.
    Thanking you all in advance.
    Warm Regards,
    Java Newbie

    Try one of these CellEditors:
    class LimitedEditor extends DefaultCellEditor {
        public LimitedEditor() {
            super(new JTextField());
        public boolean stopCellEditing() {
            String value = ((JTextField) getComponent()).getText();
            if (!value.equals("")) {
                if (value.length() > 10) {
                    ((JComponent) getComponent()).setBorder(new LineBorder(Color.red));
                    JOptionPane.showMessageDialog(null, "String length cannot be bigger than 10");
                    return false;
            return super.stopCellEditing();
        public Component getTableCellEditorComponent(final JTable table, final Object value,
                final boolean isSelected, final int row, final int column) {
            JTextField tf = ((JTextField) getComponent());
            tf.setBorder(new LineBorder(Color.black));
            if (value == null) {
                tf.setText("");
            } else {
                tf.setText(value.toString());
            return tf;
    class LimitedEditor2 extends DefaultCellEditor {
        public LimitedEditor2() {
            super(new JTextField());
            JTextField tf = ((JTextField) getComponent());
            tf.setDocument(new PlainDocument() {
                public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
                    int len = getLength();
                    if (len + str.length() > 10) {
                        Toolkit.getDefaultToolkit().beep();
                    } else {
                        super.insertString(offs, str, a);
    }Usage example:
            TableColumn tc = table.getColumnModel().getColumn(1);
            tc.setCellEditor(new LimitedEditor2());]

  • Inserting cell inside JTable cell

    Hi!
    i want to insert another cell inside a JTable cell, so that they are both displayed.
    Is it possible to do that.

    I was thinking about something like the below. I have not tested it, so let me know if it works.
    public class TwoCellTableCellRenderer extends DefaultTableCellRenderer {
         public Component getTableCellRendererComponent(JTable table,
                Object value,
                boolean isSelected,
                boolean hasFocus,
                int row,
                int column) {
              JPanel panel = new JPanel();
              panel.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
              panel.add(new JTextField(), null);
              panel.add(new JTextField(), null);
              return panel;
         protected void setValue(Object value) {
              // DO SOMETHING HERE TO PARSE YOUR TWO VALUES
    public class YourTwoCellDataClass {
    yourTable.setDefaultRenderer (YourTwoCellDataClass.class,
         new TwoCellTableCellRenderer());

  • Customized JTable cell

    Hello there:
    I want to customize the JTable cell which combines a textfield and a label. other than that, it will behave like any other Jtable component. I wrote a sample class as below, it looks ok but acts weird. Most likely my customized renderer is wrong, anyone pls revise it? thanks a lot!
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import javax.swing.BorderFactory;
    import javax.swing.BoxLayout;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JFormattedTextField;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.table.TableCellRenderer;
    public class CustomizedTable extends JFrame {
    * @param args
    CustomizedTable(){
    String[] col = new String[]{
    "col1", "col2","col3"
    Object[][] data = {
    {"1","2","3"},
    {"1","2","3"},
    {"1","2","3"},
    {"1","2","3"}
    JTable table = new JTable(data,col);
    DataColumn dc = new DataColumn();
    table.setDefaultRenderer(table.getColumnClass(0),dc);
    table.setDefaultEditor(table.getColumnClass(0),dc);
    dc = new DataColumn();
    table.setDefaultRenderer(table.getColumnClass(1),dc);
    table.setDefaultEditor(table.getColumnClass(1),dc);
    dc = new DataColumn();
    table.setDefaultRenderer(table.getColumnClass(2),dc);
    table.setDefaultEditor(table.getColumnClass(2),dc);
    JScrollPane scroll = new JScrollPane(table);
    scroll.setPreferredSize (new Dimension(300,200));
    getContentPane().add(scroll, BorderLayout.CENTER);
    pack();
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    new CustomizedTable();
    class DataColumn extends DefaultCellEditor implements TableCellRenderer {
    JFormattedTextField ftf;
    private JPanel panel = null;
    private JLabel l = new JLabel(" %");
    public DataColumn() {
    super(new JFormattedTextField());
    ftf = (JFormattedTextField) getComponent();
    ftf.setHorizontalAlignment(JTextField.RIGHT);
    ftf.setFocusLostBehavior(JFormattedTextField.PERSIST);
    ftf.setBorder(BorderFactory.createEmptyBorder());
    panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
    panel.add(ftf);
    panel.add(l);
    public Component getTableCellRendererComponent(JTable table, Object o,
    boolean isSelected, boolean hasFocus, int row, int column) {
    ftf = (JFormattedTextField) getComponent();
    ftf.setHorizontalAlignment (JTextField.RIGHT);
    ftf.setFocusLostBehavior(JFormattedTextField.PERSIST);
    ftf.setBorder(BorderFactory.createEmptyBorder());
    //panel = new JPanel();
    //panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
    //panel.add(ftf);
    //panel.add(l);
    return panel;
    public Component getTableCellEditorComponent(JTable table, Object value,
    boolean isSelected, int row, int column) {
    JFormattedTextField ftf = (JFormattedTextField) super
    .getTableCellEditorComponent(table, value, isSelected, row,
    column);
    ftf.setValue(value);
    // ftf.setBorder(BorderFactory.createEmptyBorder());
    // ftf.setHorizontalAlignment(JTextField.RIGHT);
    // panel = new JPanel();
    // panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
    // panel.add(ftf);
    // panel.add(l);
    return panel;
    }

    After 40 postings you should know how to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags.

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

Maybe you are looking for

  • Sorry if this posted upteen times-I keep getting sent to another screen.

    My question is: I have an Epson 1640xl scanner that I am trying to get to work in Photoshop CS4 Ext on a Windows 7 pro 64bit computer-any help? There are lots of comments out on the network but nothing I try seems to work. The wonderful file supposed

  • Wifi wpa

    Hello everybody, I've got a problem with wpa. At university we use edoruam network which uses wpa encoding. Through plasma widget in KDE I can find this network fill in all required information about security in a form but it doesn't connect (it fail

  • Acrobat XI IE 9 Toolbar/add-on

    I am using IE 9 (64 bit) and just installed Acrobat XI and the toolbar/add-on is missing.  Is the conversion option not available.  The only Adobe add-on that shows upis the shockwave player.

  • Mx.transitions + movieClipLoader + Crashing Flash IDE

    Well I got this code straight from the adobe site and it is suppose to show how to use the mx.transition class with a movie clip loader. When I look at the code it seems right but the flash Ide keeps crashing but before that happens it prompts me tha

  • Why would Object.clone cause IncompatibleClassChangeError

    I have 3 classes, B, A, and M public class B implements Clonable public Object clone() throws CloneNotSupportedException { return super.clone(); } // basically Object.clone() public class A extends B { ... } public class M extends A { ... } A and M d