How to use Jtable cell Editor

HI,
Here trying to populate the ImageIcon using JLabel in Jtable cell. For that I used DefaultCellRenderer. For implement the mouseListener to label I used the DefaultCellEditor. I am facing one problem here. After editing the label I selected the second row of the table, the first row image is not displaying. Can any one help on this issue?
public class LabelCellEditor extends DefaultCellEditor {
public LabelCellEditor(final JCheckBox checkBox) {
super(checkBox);
public Component getTableCellEditorComponent(final JTable table, final Object value,
final boolean isSelected, final int row, final int column) {
Color background = null;
background = ColorManager.SELECTED_ROW_BGCOLOR;
labelVal = (JLabel) value;
labelVal.setOpaque(true);
labelVal.setFont(FontManager.TABLE_DATA_FONT);
labelVal.setBackground(background);
labelPanel = new JPanel();
labelPanel.setOpaque(true);
labelPanel.setBackground(background);
labelPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
labelPanel.setBorder(new EmptyBorder(5, 0, 0, 0));
labelPanel.add(labelVal);
return this.labelPanel;
public Object getCellEditorValue() {
return this.labelPanel;
public class LabelCellRenderer extends DefaultTableCellRenderer {
public LabelCellRenderer(final int alignment) {
//setHorizontalAlignment(alignment);
this.align = alignment;
public Component getTableCellRendererComponent(final JTable table, final Object value,
final boolean isSelected, final boolean hasFocus, final int row, final int column) {
if (value != null) {
if (value instanceof JLabel) {
labelVal = (JLabel) value;
labelVal.setOpaque(true);
labelVal.setFont(FontManager.TABLE_DATA_FONT);
labelVal.setBackground(background);
labelVal.setHorizontalAlignment(this.align);
labelVal.setBorder(new EmptyBorder(0, LRPADD, 0, LRPADD));
JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBackground(background);
panel.setLayout(new FlowLayout(FlowLayout.LEFT));
panel.setBorder(new EmptyBorder(5, 0, 0, 0));
panel.add(labelVal);
return panel;
return this;
}

With more than 30 postings you should know by now how to use the "Code" tags when posting code so the code reatains its original formatting and is therefore more readable.
There is no need to create a custom editor, here is a simple example.

Similar Messages

  • How to use the cell editor in FICO reports for YTD

    HI experts,
    I am working with BI7.0, in the below report, i have displayed result based on user input.but how to calculate the YTD values. User will give the input like 072007, results will be display one year from 072007 to 062006 (one yearback) and one more column is YTD
    Report structure is :
         user input(single value): 072007
              AUG06....JAN07....JULY07....YTD
    KEYFIGURE-1        453      -
    777     -
       232       -
      777 (Only Jan07 value of Keyfigure-1)   
    KEYFIGURE-2        879      -
    233        -
    123       -
      ???? (only sum from Jan07 to July07)
    KEYFIGURE-3        212            -
    879      -
    989                -
    KEYFIGURE-4        234            -
    656      -
    788                   -
    KEYFIGURE-5        345            -
    878      -
    878                 -
    KEYFIGURE-6        767            -
    767       -
    323                 -
    KEYFIGURE-7        879            -
    878     -
    999                -
    999 (Only last value of keyfigure-7 (July07)
    in the above report, total 7 keyfigures so 7rows of YTD column
    1) in the first YTD column, how will display only one value (keyfigure-1) of Jan07?
    2) in the last YTD Column, how will display only one value (keyfigure-7) of July07?
    3) from 2 to 6 columns of YTD, how will display the sum from Jan07 to July07?
    Note: months will be changed based on user input(single Value)
    how can use cell editor for above the senior.
    if any option is availabel please let me know
    Thanks
    kishore

    I think the following should work:
    Context:
    Rows (node,c=0:n)
    --- rowIndex (integer)
    selectedRowIndex (integer)
    Bind the "selectedKey" property of the radio button (cell editor) to attribute "selectedRowIndex" (outside table data source node) and bind "keyToSelect" to attribute "Rows.rowIndex". Make sure that the "rowIndex" attribute will contain the index of the node element in node "Rows".
    Armin

  • How to use Radiobutton Cell Editor in Table using Master Column

    Hi Guys,
    I have a Table that uses a Master Column.  I need to have a field that uses a Radio Button type cell editor.  A user should only be ably to select ONE row via the Radio Button at a time.
    I have done all this but I only seem to be able to select multiple radio buttons instead of only one.  It is like the radio buttons do not get "regognised" as a group.  Could you please advise as I probably set the "keyToSelect" and "selectedKey" properties incorrectly.
    tks
    Christiaan

    I think the following should work:
    Context:
    Rows (node,c=0:n)
    --- rowIndex (integer)
    selectedRowIndex (integer)
    Bind the "selectedKey" property of the radio button (cell editor) to attribute "selectedRowIndex" (outside table data source node) and bind "keyToSelect" to attribute "Rows.rowIndex". Make sure that the "rowIndex" attribute will contain the index of the node element in node "Rows".
    Armin

  • How to make JPanel as JTable Cell Editor (Urgent help needed)

    Hi!
    I want to make JPanel (with a JTextField, 3 JLabels and 1 JTextArea) as cell editor for one column. Can somebody help me on this?
    Does anybody have any sample code? I will greatly appreciate ur help.
    Thanks,
    Snehal

    Okie. In "How to use JTables" page found in the JAVA website (there is a link from the JTable section of the JAVA API documentation), there is a sample code for a sample color chooser. What this does is, adds a button with its action listener set to pop up a color chooser window. In this, rendering is still through a JLabel.
    This example would be of good help to you. Plus, this example gives me a feeling that what u ask is possible.

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

  • JTable Cell Editor For Decimal Input

    Hi friends in my program i am using jtable, in that table two columns are decimal value. I am using defaultcelleditor for to check the user input but it does not work. so how can i check the user input, ie number or string using the cell editor. My aim is to check the user input, if the user give the wrong value, ie string input the warning message want to be displayed and the editor color also want to change. Please help me.
    I refer some tutorials and get some source code and i used but it does not work. this is the code.
    DecimalFormat format=new DecimalFormat("######0.00");
    tableField=new JFormattedTextField();
    tab_Bill.getColumnModel().getColumn(3).setCellRenderer(new DecimalRenderer(format)); tab_Bill.getColumnModel().getColumn(3).setCellEditor(new ProblemEditor(tableField));
    class DecimalRenderer extends DefaultTableCellRenderer {
      DecimalFormat formatter;
      DecimalRenderer(String pattern) {
        this(new DecimalFormat(pattern));
      DecimalRenderer(DecimalFormat formatter) {
        this.formatter = formatter;
        setHorizontalAlignment(JLabel.RIGHT);
        @Override
      public void setValue(Object value) {
       /* setText((value == null) ? "" : formatter.format(((Double) value)
            .doubleValue()));*/
    setText((value == null) ? "" : formatter.format(Double.parseDouble(value.toString())));      
         class ProblemEditor extends DefaultCellEditor implements TableCellEditor{
       private JFormattedTextField ftf;
       public ProblemEditor(JFormattedTextField myfield) {
           super(myfield);
            @Override
       public Component getTableCellEditorComponent(JTable table,
               Object value, boolean isSelected, int row, int column) {
           ftf = (JFormattedTextField) super.getTableCellEditorComponent(table, value, isSelected, row, column);
            Double d = null;
           try
                    if(value!=null)
            d=Double.parseDouble(value.toString());   
            catch(Exception e)
               // JOptionPane.showMessageDialog(null,"Wrong");
               d=0.0;
           ftf.setValue(d); // remove and okay
           ftf.setCaretPosition(ftf.getText().length());
           return ftf;
    }

    You might find it easer to use on of the [Table Format Renderers|http://www.camick.com/java/blog.html?name=table-format-renderers].

  • Custom JTable cell editors and persistence

    I have a JTable with an underlying data model (an extension of AbstractTableModel) that uses custom cell editors in the last column. The cell editor in that column, for a given row, depends on the value selected in another column of the same row. The cell editors include text, date, list, and tree editors (the last one in a separate dialogue). The number of rows is changeable.
    I have need to persist the data for a populated table from time to time, for restoration later on. I've achieved that, such that the data model is recreated, the table appears correct, and the appropriate cell editors activated (by creating new instances of the editors' classes).
    However, my problem is that the (custom) cell editors do not reflect the data in the model when editing mode is begun the first time after restoration. Eg. the text editor is always empty, the list editor shows the first item, and no node is selected in the tree editor.
    If I've restored the model correctly, should the editors properly reflect the underlying data when they are set to editing mode?
    I suspected not, and thus tried to explicitly 'set' the correct values immediately after each editor is recreated ... but to no avail.
    Does anyone have any thoughts, or experience with something similar? I'm happy to supply code.

    You can use html tags within Swing, so I think you can do the following:
    * MyRenderer.java
    * Created on 26 April 2007, 10:27
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package newpackage;
    import java.awt.Component;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.SwingConstants;
    import javax.swing.table.TableCellRenderer;
    * @author CS781RJ
    public class MyRenderer extends JLabel implements TableCellRenderer
        public MyRenderer()
            setHorizontalTextPosition(SwingConstants.RIGHT);
            setIconTextGap(3);
            setOpaque(true);
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean cellHasFocus, int row, int column)
            if (isSelected)
                setBackground(table.getSelectionBackground());
                setForeground(table.getSelectionForeground());
            else
                setBackground(table.getBackground());
                setForeground(table.getForeground());
            if (value instanceof String)
                if ((value != null) && (value.toString().length() > 0))
                    System.out.println("Value: " + value.toString());
                    setFont(new java.awt.Font("Tahoma", 0, 11));
                    setText("<html>" + value.toString().replaceAll("\n", "<br>") + "</html>");
            return this;
    }In the class that has the JTable, use the code AFTER declaring the values, columns, etc:
    jTable1.getColumnModel().getColumn(0).setCellRenderer(new MyRenderer());
    jTable1.setValueAt("Riz\nJavaid", 0, 0);One thing I haven't done is to resize the cell heights, make sure this is done.
    Hope this helps
    Riz

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

  • AutoComplete JComboBox As JTable cell editor

    Hello, when I try to use AutoComplete JComboBox as my JTable cell editor, I facing the following problem
    1) Exception thrown when show pop up. - Exception in thread "AWT-EventQueue-0" java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
    2) Unable to capture enter key event.
    Here is my complete working code. With the same JComboBox class, I face no problem in adding it at JFrame. But when using it as JTable cell editor, I will have the mentioned problem.
    Any advice? Thanks
    import javax.swing.*;
    import javax.swing.JTable.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    * @author  yccheok
    public class NewJFrame extends javax.swing.JFrame {
        /** Creates new form NewJFrame */
        public NewJFrame() {
            initComponents();
                    /* Combo Box Added In JFrame. Work as expected. */
                    final JComboBox comboBox = new JComboBox();
                    comboBox.addItem("Snowboarding");
                    comboBox.addItem("Rowing");
                    comboBox.addItem("Chasing toddlers");   
                    comboBox.setEditable(true);
                    comboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
                       public void keyReleased(KeyEvent e) {
                           if(e.getKeyCode() == KeyEvent.VK_ENTER) {
                               System.out.println("is enter");
                               return;
                           System.out.println("typed");
                           comboBox.setSelectedIndex(0);
                           comboBox.showPopup();
                    getContentPane().add(comboBox, java.awt.BorderLayout.SOUTH);
        public JTable getMyTable() {
            return new JTable() {
                 Combo Box Added In JTable as cell editor. Didn't work as expected:
                 1. Exception thrown when show pop up.
                 2. Unable to capture enter key event.
                public TableCellEditor getCellEditor(int row, int column) {
                    final JComboBox comboBox = new JComboBox();
                    comboBox.addItem("Snowboarding");
                    comboBox.addItem("Rowing");
                    comboBox.addItem("Chasing toddlers");   
                    comboBox.setEditable(true);
                    comboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
                       public void keyReleased(KeyEvent e) {
                           if(e.getKeyCode() == KeyEvent.VK_ENTER) {
                               System.out.println("is enter");
                               return;
                           System.out.println("typed");
                           comboBox.setSelectedIndex(0);
                           comboBox.showPopup();
                    return new DefaultCellEditor(comboBox);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            jScrollPane1 = new javax.swing.JScrollPane();
            jTable1 = getMyTable();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4"
            jScrollPane1.setViewportView(jTable1);
            getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
            pack();
        }// </editor-fold>                       
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NewJFrame().setVisible(true);
        // Variables declaration - do not modify                    
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTable jTable1;
        // End of variables declaration                  
    }

    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.

  • 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

  • When do I need to use a cell editor in a JTree?

    I'm currently trying to add checkboxes to nodes in a JTree. I use a panel containing the check box and a label for rendering. I did this because I want only the checkbox to respond to a mouse click and not the text associated with it. I've read several articles online (including the tutorial) and seen sample code as well. Do I need a cell editor or just have a cell renderer with a mouse listener? I've seen it done both ways.

    Let me rephrase the question.
    If I want to display a checkbox and a label as a node in a Jtree, which way should this be done (with or without a cell editor)? What are the advantages/disadvantages to each approach and what is recommended by Sun?
    I ended up not using a cell editor, but I've read posts on various sites where it was stated that if the user has interaction with the node then an editor should be used (with no other explanation as to why). I guess my main concern is that there might be a down side from not using a cell editor that I'm not aware of.

  • How i use jtable

    hi master
    sir how i use jtable
    please send me any detail sample with swing interfas and code
    thank's
    aamir

    Did you read the JTable API???
    You will find a link titled "How to Use Tables" that takes you to the Swing tutorial.

  • Problem using an editable JComboBox as JTable cell editor

    Hi,
    i have a problem using an editable JComboBox as cell editor in a JTable.
    When i edit the combo and then I press the TAB or ENTER key then all works fine and the value in the TableModel is updated with the edited one, but if i leave the cell with the mouse then the value is not passed to the TableModel. Why ? Is there a way to solve this problem ?
    Regards
    sergio sette

    if (v1.4) [url
    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JTa
    le.html#setSurrendersFocusOnKeystroke(boolean)]go
    hereelse [url
    http://forum.java.sun.com/thread.jsp?forum=57&thread=43
    440]go here
    Thank you. I've also found this one (the first reply): http://forum.java.sun.com/thread.jsp?forum=57&thread=124361 Works fine for me.
    Regards
    sergio sette

  • I am really stuck with JCheckBox using it as a JTable cell editor...

    i need to focus next table cell, when user press a key on JcheckBox used in JTable as a cell editor.
    Especially i need to bind "ENTER" key with this action. I tried to addKeyListener do checkbox, tried to add action into input maps of jatble, and also to input map of checkbox. But really nothing works. Please help....
    Mathew, HSIGP

    and yes your code works well with any key, but when i want to assign something to "ENTER", it doesnt work. F.ex. if i assign something to "A" key
    like>
    InputMap m=table.getInputMap(WHEN_ANCETSTOR...);
    m.put(KeyStroke.get("A"),m.get(KeyStroke.get("TAB"));
    it works fine, and when i press "a" key it work as a "tab" key in table.
    But when i am doing same with "enter" instead of "a" it doesnt work.
    btw. there is action "actionselectNextCollumn..." assigned by default to enter
    why??

  • JTable Cell Editor Problems

    Hi All,
    I have a problem concerning the editing for my table. When I click on a column a dialog box opens up and the user picks the values he wants. But after he presses ok in the dialog box the user again has to press enter in the selected cell or click on another cell in the table for the selected cell to lose focus.I am using a textfield as the returning component in the getcomponent method for the the table cell editor. Is there a way I can force the textfield to register an enter automatically so it loses focus or is there another way?
    Thanks, in advance.

    this is how my code is structured:
    public class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor,
         ActionListener{
         private static final long serialVersionUID = 0;
         private int clickCountToStart = 2; // Default value is double click
         private JFrame editingFrame;
         // This is the component that will handle the editing of the cell value
         JTextField txtresult = new JTextField(10);
         String result = null;
         public MyTableCellEditor(JFrame jframe){
              //txtresult.addActionListener(this);       
              editingFrame = jframe;
        public int getClickCountToStart(){
            return clickCountToStart;
        public int setClickCountToStart(int c){
            clickCountToStart = c;
             return clickCountToStart;
        public boolean isCellEditable(EventObject e){
            if(e instanceof MouseEvent){
                 if(((MouseEvent)e).getClickCount()>=this.getClickCountToStart()){
                      return true;
            return false;
        public boolean stopCellEditing(){
             fireEditingStopped();
             return true;
        // This method is called when a cell value is edited by the user.
        public Component getTableCellEditorComponent(JTable table, Object value,
                boolean isSelected, int row, int col) {
             // Make certain columns non editable
             if(table.getColumnName(col).equals("Sub Number")){
                  return null;
             else if(table.getColumnName(col).equals("Transmitter#/Receiver#")){
                  return null;
             if(table.getColumnName(col).equals("TOOLMODE")){
                  result = toolModeModify();
                 if(result==null){
                      result = value.toString();
                  if(result != null){
                      txtresult.setText(result);
                 else{
                      txtresult.setText(value.toString());
            else{
                 result = ModifyCell();
                 if(result != null){
                      txtresult.setText(result);
                 else{
                      if(value != null){
                           txtresult.setText(value.toString());
             txtresult.setEditable(false);
             return txtresult;
        public void actionPerformed(ActionEvent e) {
            //stopCellEditing(); //Make the renderer reappear.
        // This method is called when editing is completed.
        // It must return the new value to be stored in the cell.
        public Object getCellEditorValue() {
             try{
                 return txtresult.getText();
             }catch(NullPointerException ne){
                  return null;
        private String toolModeModify(){
             Object[] possibilities = {"0", "1", "2","3"};
             String number = (String)JOptionPane.showInputDialog(
                                 editingFrame,
                                 "Option 0: Receiver\n"
                                 + "Option 1: UDT\n"
                                 + "Option 2: TRX/UDR\n" +
                                 "Option 3: OFF\n",
                                 "Select Mode",
                                 JOptionPane.PLAIN_MESSAGE,
                                 null,
                                 possibilities,
                                 "0");
             return number;
        private String ModifyCell(){
              String editCell = "Edit Cell Value";
              String s;
              s = JOptionPane.showInputDialog(editingFrame, editCell, null,
                        JOptionPane.PLAIN_MESSAGE);
              if(s != null){
                   return s;
              else{
                   return null;
    }I dont know what I am doing wrong.

Maybe you are looking for

  • Interest Calculation on posting date and due date

    Hi I want vendor interest calculation on due date as well as posting date. Let me know how to get it. According to me only its possible on the basis of one date only.

  • CcmEval Scheduled task not being created with "Access Denied" error 0x80070005 only on XP machines

    Before coming on here I checked out http://social.technet.microsoft.com/Forums/en-US/ddbfe6c3-ee54-4b2a-a3a7-a6515d974f76/client-check-failed-on-xpserver-2003-systems-onlyccmeval-is-not-being-scheduled?forum=configmanagerdeployment (GPO to allow sche

  • Creation of Stand Alone prompt in OLAP universe

    Hi, I am creating a webi report from universe build from Bex query. I have to catch a user response so i am creating a stand alone prompt in the universe but when i am parsing it, it's giving error. <FILTER KEY="[Level Object definition]"><CONDITION

  • MM overflow in goods receipt

    hie guys im experiencing a field overflow in program LFMOIF02 line 121 were im trying to post a goods receipt for a figure obove 10 billion, however i identified the amount field referencing the domain VVWERT7V and extended it to 17 from 13 chars but

  • Uneditable art on tracks with missing art

    Hi, I have a small problem with some of my albums, for one or two random tracks I am unable to add / edit arkwork... if I right click on the track "Get Info", I am given four tabs - Summary, Info, Sorting & Options... usually there is a fith tab for