Want to edit a JTable cell programatically

I am making use of JTable in my application. I want to start editing a cell at 5th column, prompt user to enter value, as soon as he checks the JCheckbox in the first Column. I have tried in various ways but failed to solve it. Can any one provide a solution for this.

Try something like this.
Note this is untested.
You mak not need the invokeLater.
JCheckBox xb = new JCheckBox("Check Box");
xb.addItemListener(new ItemListener() {
  public void itemStateChanged(ItemEvent ae) {
    SwingUtilities.invokeLater(new Runnable() {
      public void run(){
        table.changeSelection(lastJTable.getSelectedRow(), 5, true, true);
        table.editCellAt(lastJTable.getSelectedRow(), 5);
        Component tec = table.getEditorComponent();
        if (tec!=null){tec.requestFocus();}
        // force filed to be selected
        try {((JTextComponent)tec).selectAll();}
        catch (Exception notTextEx) {}
});rykk

Similar Messages

  • Edit a JTable cell, click save button, value isn't stored in JTable

    I'm editing a JTable cell, just using default editor provided by JTable
    I click a save button elsewhere in my GUI
    The value typed into the cell so far isn't stored in the TableModel yet and so doesn't get saved.
    How can I make sure the value gets stored in the JTable in the above scenario when the JButton is pressed but before saving.
    Preferably I'd like the code with the JButton not to have to know about the JTable at all.
    Cheers,
    D

    I the forums 100s of times.Many thanks. If they had a decent search on this forum I might have found it as I did try.
    Come to think of it - Sun have completely fcukd up this forum.

  • Edit a JTable cell by clicking at it once - is it possible?

    If I want to edit a cell in a JTable, I have to doubleclick on it. Is it possible to set the JTable cells to be in edit mode by just clicking at the cells once?

    Did you search the forums?? How about something like "jtable-edit-single-click".

  • Returning index of selected comp... jComboBox that is editing a jTable cell

    so, i'm using an array to populate the choices of a combobox
        public String[] progCodes = new String[]{"Standard","Restricted","Combined","Special"};which i'm using to edit a cell in a jtable
    baseCatTable.getColumnModel().getColumn(4).setCellEditor(new DefaultCellEditor(new JComboBox(progCodes)));and when i get the value
    System.out.println(baseCatTable.getValueAt(0, 4))i'd like to return the index of the selected item in the combo box instead of the text:
    Standard
    any suggestions?
    Edited by: hansbig on Jan 24, 2008 5:04 PM

    sorry, but i'm using an IDE and it generates a lot of fluffy code.
    * ProblemView.java
    package problem;
    import org.jdesktop.application.Action;
    import org.jdesktop.application.ResourceMap;
    import org.jdesktop.application.SingleFrameApplication;
    import org.jdesktop.application.FrameView;
    import org.jdesktop.application.TaskMonitor;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.DefaultCellEditor;
    import javax.swing.Timer;
    import javax.swing.Icon;
    import javax.swing.JComboBox;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    * The application's main frame.
    public class ProblemView extends FrameView {
        public ProblemView(SingleFrameApplication app) {
            super(app);
            initComponents();
            edit = new JComboBox(words);
            // status bar initialization - message timeout, idle icon and busy animation, etc
            ResourceMap resourceMap = getResourceMap();
            int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
            messageTimer = new Timer(messageTimeout, new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    statusMessageLabel.setText("");
            messageTimer.setRepeats(false);
            int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
            for (int i = 0; i < busyIcons.length; i++) {
                busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
            busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                    statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
            statusAnimationLabel.setIcon(idleIcon);
            progressBar.setVisible(false);
            // connecting action tasks to status bar via TaskMonitor
            TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
            taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
                public void propertyChange(java.beans.PropertyChangeEvent evt) {
                    String propertyName = evt.getPropertyName();
                    if ("started".equals(propertyName)) {
                        if (!busyIconTimer.isRunning()) {
                            statusAnimationLabel.setIcon(busyIcons[0]);
                            busyIconIndex = 0;
                            busyIconTimer.start();
                        progressBar.setVisible(true);
                        progressBar.setIndeterminate(true);
                    } else if ("done".equals(propertyName)) {
                        busyIconTimer.stop();
                        statusAnimationLabel.setIcon(idleIcon);
                        progressBar.setVisible(false);
                        progressBar.setValue(0);
                    } else if ("message".equals(propertyName)) {
                        String text = (String)(evt.getNewValue());
                        statusMessageLabel.setText((text == null) ? "" : text);
                        messageTimer.restart();
                    } else if ("progress".equals(propertyName)) {
                        int value = (Integer)(evt.getNewValue());
                        progressBar.setVisible(true);
                        progressBar.setIndeterminate(false);
                        progressBar.setValue(value);
        @Action
        public void showAboutBox() {
            if (aboutBox == null) {
                JFrame mainFrame = ProblemApp.getApplication().getMainFrame();
                aboutBox = new ProblemAboutBox(mainFrame);
                aboutBox.setLocationRelativeTo(mainFrame);
            ProblemApp.getApplication().show(aboutBox);
        /** 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() {
            mainPanel = new javax.swing.JPanel();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTable1 = new javax.swing.JTable();
            jButton1 = new javax.swing.JButton();
            menuBar = new javax.swing.JMenuBar();
            javax.swing.JMenu fileMenu = new javax.swing.JMenu();
            javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
            javax.swing.JMenu helpMenu = new javax.swing.JMenu();
            javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
            statusPanel = new javax.swing.JPanel();
            javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
            statusMessageLabel = new javax.swing.JLabel();
            statusAnimationLabel = new javax.swing.JLabel();
            progressBar = new javax.swing.JProgressBar();
            mainPanel.setName("mainPanel"); // NOI18N
            jScrollPane1.setName("jScrollPane1"); // NOI18N
            jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {null}
                new String [] {
                    "Title 1"
            jTable1.setColumnSelectionAllowed(true);
            jTable1.setName("jTable1"); // NOI18N
            jScrollPane1.setViewportView(jTable1);
            jTable1.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
            jTable1.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(edit));
            org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(problem.ProblemApp.class).getContext().getResourceMap(ProblemView.class);
            jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
            jButton1.setName("jButton1"); // NOI18N
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
            mainPanel.setLayout(mainPanelLayout);
            mainPanelLayout.setHorizontalGroup(
                mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(mainPanelLayout.createSequentialGroup()
                    .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(mainPanelLayout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(mainPanelLayout.createSequentialGroup()
                            .addGap(46, 46, 46)
                            .addComponent(jButton1)))
                    .addContainerGap(12, Short.MAX_VALUE))
            mainPanelLayout.setVerticalGroup(
                mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(mainPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(jButton1)
                    .addContainerGap(18, Short.MAX_VALUE))
            menuBar.setName("menuBar"); // NOI18N
            fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
            fileMenu.setName("fileMenu"); // NOI18N
            javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(problem.ProblemApp.class).getContext().getActionMap(ProblemView.class, this);
            exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
            exitMenuItem.setName("exitMenuItem"); // NOI18N
            fileMenu.add(exitMenuItem);
            menuBar.add(fileMenu);
            helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
            helpMenu.setName("helpMenu"); // NOI18N
            aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
            aboutMenuItem.setName("aboutMenuItem"); // NOI18N
            helpMenu.add(aboutMenuItem);
            menuBar.add(helpMenu);
            statusPanel.setName("statusPanel"); // NOI18N
            statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N
            statusMessageLabel.setName("statusMessageLabel"); // NOI18N
            statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
            statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N
            progressBar.setName("progressBar"); // NOI18N
            javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
            statusPanel.setLayout(statusPanelLayout);
            statusPanelLayout.setHorizontalGroup(
                statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(statusMessageLabel)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(statusAnimationLabel)
                    .addContainerGap())
            statusPanelLayout.setVerticalGroup(
                statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(statusPanelLayout.createSequentialGroup()
                    .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(statusMessageLabel)
                        .addComponent(statusAnimationLabel)
                        .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(3, 3, 3))
            setComponent(mainPanel);
            setMenuBar(menuBar);
            setStatusBar(statusPanel);
        }// </editor-fold>
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            System.out.println(jTable1.getValueAt(0, 0));
            System.out.println(edit.getSelectedIndex());
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTable jTable1;
        private javax.swing.JPanel mainPanel;
        private javax.swing.JMenuBar menuBar;
        private javax.swing.JProgressBar progressBar;
        private javax.swing.JLabel statusAnimationLabel;
        private javax.swing.JLabel statusMessageLabel;
        private javax.swing.JPanel statusPanel;
        // End of variables declaration
        public String[] words = new String[]{"one","two"};
        public JComboBox edit;
        private final Timer messageTimer;
        private final Timer busyIconTimer;
        private final Icon idleIcon;
        private final Icon[] busyIcons = new Icon[15];
        private int busyIconIndex = 0;
        private JDialog aboutBox;
    * ProblemApp.java
    package problem;
    import org.jdesktop.application.Application;
    import org.jdesktop.application.SingleFrameApplication;
    * The main class of the application.
    public class ProblemApp extends SingleFrameApplication {
         * At startup create and show the main frame of the application.
        @Override protected void startup() {
            show(new ProblemView(this));
         * This method is to initialize the specified window by injecting resources.
         * Windows shown in our application come fully initialized from the GUI
         * builder, so this additional configuration is not needed.
        @Override protected void configureWindow(java.awt.Window root) {
         * A convenient static getter for the application instance.
         * @return the instance of ProblemApp
        public static ProblemApp getApplication() {
            return Application.getInstance(ProblemApp.class);
         * Main method launching the application.
        public static void main(String[] args) {
            launch(ProblemApp.class, args);
    }i'm getting:
    init:
    deps-jar:
    Compiling 1 source file to C:\Documents and Settings\1\My Documents\NetBeansProjects\problem\build\classes
    compile:
    run:
    Jan 24, 2008 7:58:36 PM org.jdesktop.application.Application$1 run
    SEVERE: Application class problem.ProblemApp failed to launch
    java.lang.NullPointerException
    at javax.swing.DefaultCellEditor.<init>(DefaultCellEditor.java:117)
    at problem.ProblemView.initComponents(ProblemView.java:136)
    at problem.ProblemView.<init>(ProblemView.java:29)
    at problem.ProblemApp.startup(ProblemApp.java:19)
    at org.jdesktop.application.Application$1.run(Application.java:171)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
    Exception in thread "AWT-EventQueue-0" java.lang.Error: Application class problem.ProblemApp failed to launch
    at org.jdesktop.application.Application$1.run(Application.java:177)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
    Caused by: java.lang.NullPointerException
    at javax.swing.DefaultCellEditor.<init>(DefaultCellEditor.java:117)
    at problem.ProblemView.initComponents(ProblemView.java:136)
    at problem.ProblemView.<init>(ProblemView.java:29)
    at problem.ProblemApp.startup(ProblemApp.java:19)
    at org.jdesktop.application.Application$1.run(Application.java:171)
    ... 8 more
    BUILD SUCCESSFUL (total time: 2 seconds)
    also, I made a zip file of the project and put it up here:
    http://www.geocities.com/hansbigtree/problem.zip
    thanks.

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

  • Directly enter edit mode of JTable cell

    Hi Everyone,
    On my UI, i am showing editable JTable. When I click on table's row / cell, it selects the row. Fine.
    But I want that it should directly enter edit mode of cell and the whole text is to be selected and highlighted and focussed.
    Thus, user can directly type the new text.
    Please suggest correct approach to handle this scenario.
    Thanks in advance.
    Girish Varde.

    Here is my attempt at solving this problem:
    **  For text selection you have two choices. Remove the "xxx" from either
    **  editCellAt() or prepareEditor() method.
    **  The difference is in how mouse double clicking works
    **  To place a cell directly into edit mode, use the changeSelection() method.
    **  Be aware this will generate a TableModelEvent every time you leave a cell.
    **  You can also use either of the above text selection methods.
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.table.*;
    public class TableEditCell extends JFrame
         public TableEditCell()
              String[] columnNames = {"Number", "Letter"};
              Object[][] data = { {"1", "A"}, {"2", "B"}, {"3", "C"} };
              JTable table = new JTable(data, columnNames)
                   //  Place cell in edit mode when it 'gains focus'
                   public void xxxchangeSelection(
                        int row, int column, boolean toggle, boolean extend)
                        super.changeSelection(row, column, toggle, extend);
                        if (editCellAt(row, column))
                             getEditorComponent().requestFocusInWindow();
                   //  Select the text when the cell starts editing
                   //  a) text will be replaced when you start typing in a cell
                   //  b) text will be selected when you use F2 to start editing
                   //  c) text will be selected when double clicking to start editing
                   public boolean xxxeditCellAt(int row, int column, EventObject e)
                        boolean result = super.editCellAt(row, column, e);
                        final Component editor = getEditorComponent();
                        if (editor != null && editor instanceof JTextComponent)
                             if (e == null)
                                  ((JTextComponent)editor).selectAll();
                             else
                                  SwingUtilities.invokeLater(new Runnable()
                                       public void run()
                                            ((JTextComponent)editor).selectAll();
                        return result;
                   //  Select the text when the cell starts editing
                   //  a) text will be replaced when you start typing in a cell
                   //  b) text will be selected when you use F2 to start editing
                   //  c) caret is placed at end of text when double clicking to start editing
                   public Component xxxprepareEditor(
                        TableCellEditor editor, int row, int column)
                        Component c = super.prepareEditor(editor, row, column);
                        if (c instanceof JTextComponent)
                             ((JTextField)c).selectAll();
                        return c;
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
         public static void main(String[] args)
              TableEditCell frame = new TableEditCell();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

  • Start or stop edit jtable cell editing

    Hello,
    I got a problem with the jtable DefaultModel isCellEditable.
    If I set the IsCellEditable to false, I would not be able to enable the cell selection as and when I want it.
    What I have in mind is the add a mouselister so that if the user select a row using fast left mouse click like the procedure shown below
    private class MouseClickHandler extends MouseAdapter {
    public void mouseClicked(MouseEvent event) {
    int no_mouseclick = 0;
    no_mouseclick = event.getClickCount();
    if (no_mouseclick >= 2) {
    int cur_row = 0;
    cur_row = table.getSelectedRow();
    // table.setColumnSelectionAllowed(true);
    // table.setRowSelectionAllowed(true);
    for (int i=0;i<table.getColumnCount();i++){
    table.editCellAt(cur_row,i);
    System.out.println("mouse row--->" + cur_row);
    I could overwrite the IsCellEditable to true to enable that particular or cell contains in that row to be able to accept input and overwrite any data which in my case obtained from the Sql database a sort of like input module using tabulation . I am also thinking of using text component or combobox to display the value for user selection , but I do not know how to enable a particular cell for editing if the Jtable created is using a non-editable DefaultModel. If I set the IsCellEditable to true, every single cell would be enable for editing , and this defeat the purpose of enable user input only upon double mouseclicks.
    By the way , I am interested to know how to track the data changes in the cell within the jtable so that only those have been modified are notify from the Table model and updated into the Sql table
    Could anyone of you out there provide some hints please
    Thanks

    Hello,
    Tablemodellistener could detect the changes in the data, how about the backend database updating and transactional activity that must be associated with the data changes?
    What is on my mind is that , the moment there is changes in the data detected by the TableModellistener, whatever records associated with or brougt up by Jtable would be all deleted from the database and then follow by the new set of new records to be inserted into the database. The disadvantage of this method is that everytime the backend database connection and activity need to be executed the moment there is a change in the data in the jtable cell. For example the user may be just amendment to only one cell , but all the records associated need to be deleted and then inserted again.
    Perhaps there are better solution to deal with Jtable and JDBC backend connection where in this case, I am using JDO to undertake the database activity like the observable modelling .
    Could someone provide the hint please
    Thank

  • 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

  • Edit a cell programatically

    How to start editing a specific cell in a table view programmatically. For example, I have a table view with a column. Whenever the user clicks on any row's cell, the cell value factory is called and start edit method is invoked in that cell. Now cell's content is replaced with a text field and allows the user to edit. Now I want to do this programmtically say for example edit row 5 and column 1.
    There is API to select a particular cell. but how to invoke its startEdit method.
    getTableView().getSelectionModel().clearAndSelect(getTableView().getSelectionModel().getSelectedIndex() + 1, getTableColumn());
    any help will be very helpful.

    I found it. Thanks.
    getTableView().edit(index, tableColumn)

  • Non-editable JTable cells?

    Is there any way to make all the cells in a JTable non-editable? In the API I see the isEditable method, but no setEditable method. Any suggestions?

    You have to set it in the TableModel.
    TableModel model = new AbstractTableModel()
    public int getRowCount()
    return 10;
    public int getColumnCount()
    return 5;
    public Object getValueAt(int row, int column)
    return "( "+row+","+column+" )";
    public boolean isCellEditable(int row,int column)
    return false;
    The one given above is a sample to show you how to set a cell non-editable on the cell. You have to customize it for your table model.
    Thanks,
    Kalyan

  • How to programatically select different JTable cells

    Dear all,
    I need to programatically select different JTable cells.
    I have to make the inverse selection. So if the user has a table of one column and 10 rows, and selects rows 3,6,8, the inverse selection should select all the other remainig cells and deselect 3,6, and 8.
    I tried using the following but it does not work ?
    for (int i = 0; i < table.getRowCount(); i++) {
    table.changeSelection(i, 0, true, false);
    Hope someone can help.
    Regards,
    Kanita

    Dear all,
    I need to programatically select different JTable cells.
    I have to make the inverse selection. So if the user has a table of one column and 10 rows, and selects rows 3,6,8, the inverse selection should select all the other remainig cells and deselect 3,6, and 8.
    I tried using the following but it does not work ?
    for (int i = 0; i < table.getRowCount(); i++) {
    table.changeSelection(i, 0, true, false);
    Hope someone can help.
    Regards,
    Kanita

  • Edit Colors of Individual JTable Cells?

    I want to make a JTable that has some blank cells for a TV program I'm writing. These blank cells will be the same color as the cells to the left of them. I wrote a ColorCellRenderer to do just this, as shown:
    class ColorCellRenderer extends DefaultTableCellRenderer
        Color prevColor = Color.white;
        private Color[] colors = {Color.cyan, Color.yellow, Color.pink, Color.orange};
        public void setCellColor(JTable table, Object value, boolean isSelected,
                    boolean hasFocus, int row, int column)
            Object presValue = table.getValueAt(row,column);
            if (presValue.equals(""))
                getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column).setBackground(prevColor);
            else if (column > 0)
                getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column).setBackground(colors[column-1]);
                prevColor = colors[column-1];
    }Then, in my JTable subclass, I loop through the cells, like this:
    ColorCellRenderer ccr;
            for (int i = 0; i < getRowCount(); i++)
                Color prevColor = Color.white;
                for (int j = 1; j < getColumnCount(); j++)
                    ccr = (ColorCellRenderer)getColumnModel().getColumn(j).getCellRenderer();
                    if (j > 1 && items[i][j].equals("")) {
                        ccr.setCellColor(this, items[i][j], false, false, i, j);
                    else {
                        ccr.setCellColor(this, items[i][j], false, false, i, j);
            }And of course I added my ColorCellRenderer to the updateUI() method of this JTable subclass.
    The problem is, the JTable seems to only let me have one color per column. Here's what the result looks like:
    http://img264.imageshack.us/img264/1397/picture3vt6.png
    Anyone know why this is happening?

    Nevermind, I misread a doc. I needed to override the getTableCellRendererComponent method. Here's the method, along with a screenshot of the program in all its glory:
    class ColorCellRenderer extends DefaultTableCellRenderer
        private Color[] colors = {Color.cyan, Color.yellow, Color.pink, Color.orange};
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                    boolean hasFocus, int row, int column)
            if (value.equals(""))
                Color c = colors[column-1];
                switch (column) {
                    case 2:
                        c = colors[0];
                        break;
                    case 3:
                        c = colors[1];
                        if (table.getValueAt(row, 2).equals(""))
                            c = colors[0];
                        break;
                    case 4:
                        c = colors[2];
                        if (table.getValueAt(row, 3).equals("")) {
                            c = colors[1];
                            if (table.getValueAt(row, 2).equals(""))
                                c = colors[0];
                        break;
                super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column).setBackground(c);
            else if (column > 0)
                super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column).setBackground(colors[column-1]);
            else {
                super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column).setBackground(Color.white);
            return this;
    }Screenshot:
    http://img145.imageshack.us/img145/639/picture4mr4.png
    That's it. For some reason the Channels column will not shrink, but I'm sure I'll figure it out.

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

  • How to force check right value of a JTable cell?

    Hi,
    I have a JTable with a column that must have a value no empty and between 0 and 100. I made a sample with only one column for simplicity.
    The code works fine when the user types some value. However, when the user press ENTER to go to next column, without editing the cell, no checks run.
    I have also other column that the user may type a part of a name and the system must find the full name of a person. In this column, if user uses ENTER without editing the cell, the same problem ocurrs.
    The simplistic code is here, runnable:
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import java.text.NumberFormat;
    import java.text.ParseException;
    import javax.swing.text.DefaultFormatterFactory;
    import javax.swing.text.NumberFormatter;
    public class TableCheckCell extends JFrame {
      /** Creates a new instance of TableCheckCell */
      public TableCheckCell() {
        Object[] columnNames = {"Percents"};
        Object[][] data =
          {new Integer(-1)}, // <--- DEFAULT VALUE FORCED TO BE OUT OF RANGE...
          {new Integer(-1)},
          {new Integer(-1)},
          {new Integer(-1)}
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        JTable table = new JTable(model);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane( table );
        getContentPane().add( scrollPane );
        TableColumn col = table.getColumnModel().getColumn(0);
        col.setCellEditor(new CellIntegerEditor(CellIntegerEditor.CHECKMINMAX,0,100));
      public static void main(String[] args) {
        TableCheckCell frame = new TableCheckCell();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    * Implements a cell editor that uses a formatted text field
    * to edit Integer values.
    class CellIntegerEditor extends DefaultCellEditor {
      public static final int NOCHECK = 0;
      public static final int CHECKMINMAX = 1;
      public static final int CHECKMIN = 2;
      public static final int CHECKMAX = 3;
      JFormattedTextField ftf;
      NumberFormat integerFormat;
      private int checkinterv;
      private Integer minimum, maximum;
      private boolean DEBUG = false;
      public CellIntegerEditor(int checkinterv, int min, int max) {
        super(new JFormattedTextField());
        init(checkinterv, min, max);
      void init(int checkinterv, int min, int max) {
        ftf = (JFormattedTextField)getComponent();
        this.checkinterv = checkinterv;
        minimum = new Integer(min);
        maximum = new Integer(max);
        //Set up the editor for the integer cells.
        integerFormat = NumberFormat.getIntegerInstance();
        NumberFormatter intFormatter = new NumberFormatter(integerFormat);
        intFormatter.setFormat(integerFormat);
        if (checkinterv == CHECKMIN || checkinterv == CHECKMINMAX)
          intFormatter.setMinimum(minimum);
        if (checkinterv == CHECKMAX || checkinterv == CHECKMINMAX)
          intFormatter.setMaximum(maximum);
        ftf.setFormatterFactory(new DefaultFormatterFactory(intFormatter));
        ftf.setValue(minimum);
        ftf.setHorizontalAlignment(JTextField.TRAILING);
        ftf.setFocusLostBehavior(JFormattedTextField.PERSIST);
        //React when the user presses Enter while the editor is
        //active.  (Tab is handled as specified by
        //JFormattedTextField's focusLostBehavior property.)
        ftf.getInputMap().put(KeyStroke.getKeyStroke(
          KeyEvent.VK_ENTER, 0),
          "check");
        ftf.getActionMap().put("check", new AbstractAction() {
          public void actionPerformed(ActionEvent e) {
            if (!ftf.isEditValid()) { //The text is invalid.
              if (userSaysRevert()) { //reverted
                ftf.postActionEvent(); //inform the editor
            } else try {              //The text is valid,
              ftf.commitEdit();     //so use it.
              ftf.postActionEvent(); //stop editing
            } catch (java.text.ParseException exc) { }
      //Override to invoke setValue on the formatted text field.
      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);
        return ftf;
      //Override to ensure that the value remains an Integer.
      public Object getCellEditorValue() {
        JFormattedTextField ftf = (JFormattedTextField)getComponent();
        Object o = ftf.getValue();
        if (o instanceof Integer) {
          return o;
        } else if (o instanceof Number) {
          return new Integer(((Number)o).intValue());
        } else {
          if (DEBUG) {
            System.out.println("getCellEditorValue: o isn't a Number");
          try {
            return integerFormat.parseObject(o.toString());
          } catch (ParseException exc) {
            System.err.println("getCellEditorValue: can't parse o: " + o);
            return null;
      //Override to check whether the edit is valid,
      //setting the value if it is and complaining if
      //it isn't.  If it's OK for the editor to go
      //away, we need to invoke the superclass's version
      //of this method so that everything gets cleaned up.
      public boolean stopCellEditing() {
        JFormattedTextField ftf = (JFormattedTextField)getComponent();
        if (ftf.isEditValid()) {
          try {
            ftf.commitEdit();
          } catch (java.text.ParseException exc) { }
        } else { //text is invalid
          if (!userSaysRevert()) { //user wants to edit
            return false; //don't let the editor go away
        return super.stopCellEditing();
       * Lets the user know that the text they entered is
       * bad. Returns true if the user elects to revert to
       * the last good value.  Otherwise, returns false,
       * indicating that the user wants to continue editing.
      protected boolean userSaysRevert() {
        Toolkit.getDefaultToolkit().beep();
        ftf.selectAll();
        Object[] options = {"Corrigir"};
        String msg = "";
        if (checkinterv == CHECKMINMAX)
          msg = "Value must be between " + minimum + " and " + maximum + ".";
        else if (checkinterv == CHECKMIN)
          msg = "Value must be >= " + minimum + ".";
        else if (checkinterv == CHECKMAX)
          msg = "Value must be <= " + maximum + ".";
        JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(ftf),msg);
        ftf.setValue(ftf.getValue());
        return true;
    }Then, I'd like to know if there is any way to check the user typed ENTER to go out of the cell, check the value of the cell and, if it is wrong, to come back to the cell, forcing the user to type a right value.

    Editing to force the entry of data in a cell is typically done when you press a button to process the data. It doesn't make sense to "edit" the cell when the user presses enter to go to the next cell. What if the user never places focus on a particular cell. Then the cell will never be edited.
    To force a user to enter a valid value once they have started editing you can do something like this:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=575309
    But you can't force a user to visit every cell in the table so you need to handle that as described above.

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

Maybe you are looking for

  • Connecting iphone with computer

    Mostly when I connect my iphone with my computer itunes kicks in and syncing starts up automatically. However, sometimes nothing happens. Ive even had a screen asking me to connect the iphone to itunes when it (iphone) is already plugged into the com

  • Headphones/earbuds and carrying options when listening to music?

    How is everyone carrying their iPhone and listening to music? I see there is an earbuds option with a microphone but unlike the Nano there isn't a lanyard option. Are people putting it in their shirt pocket (what about you gals?) or clipping it on yo

  • DW CS4 Question about Moving Content to New Site

    Hi, I'm supposed to meet with a client later about creating a new website and moving all content from the old to the new.  Right now, I have no idea how many pages the old one has.  I'm assuming the worst, which means I'm assuming there will be a lot

  • Virtual PC error when trying to log off in XP Mode

    I get this error: Problem Event Name: APPCRASH   Application Name: VMWindow.exe   Application Version: 6.1.7601.17514   Application Timestamp: 4ce7b2e6   Fault Module Name: StackHash_1b78   Fault Module Version: 6.1.7601.18247   Fault Module Timestam

  • A few programs run slowly on my G4

    Hi, I have a Power Mac G4 Gigabit Ethernet with 704MB RAM dual 500MHz G4 processors and 16MB VRAM (ATI RAGE graphics card) and Mac OS X's built in Chess program and some other programs (especially iTunes while browsing in CoverFlow but other view mod