Capturing JCheckBox edit from within a JTable cell

Hey,
I've gone through as many posts as i can from this forum and i have managed to understand quite a bit but there is just this one probelm that i have.
What i have is a checkbox in a cell in a jtable that causes the a jpanel elsewhere to repaint in various ways depending on whether the checkbok is checked or not.
The code below is for the table editor. The model is my table model. aCanvas is the panel being repainted. completeVisible is the array that aCanvas accesses to repaint the panel.
The code below works perfectly after the but only after the second click. the first 2 times i click the checkbox the value printed is true and then afterwards it starts alternating and working correctly... can anyone please tell me why this is?
thanks in andvance... :o)
private class TSPCellEditor extends AbstractCellEditor implements TableCellEditor, ActionListener {
          Boolean visible;
          JCheckBox check;
          String TEST = "TEST";
          public TSPCellEditor() {
               check = new JCheckBox();
               check.setActionCommand(TEST);
               check.addActionListener(this);
          public void actionPerformed(ActionEvent e) {
               if(TEST.equals(e.getActionCommand())) {
                    visible = new Boolean(check.isSelected());
                    fireEditingStopped();
          public Object getCellEditorValue() {
               return visible;
          public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
               visible = (Boolean)(value);
               //boolean temp = visible.booleanValue();
               //temp = !temp;
               //visible = Boolean.valueOf(temp);
               check.setSelected(visible.booleanValue());
System.out.println(completeVisible[row]+" "+row);               
               completeVisible[row] = visible.booleanValue();
               model.setValueAt(visible, row, column);
               aCanvas.repaint();
               return check;
     }

I can't answer your question, but I think a better way to implement your solution is to use a TableModelListener. An event is fired whenver the contents of the table model are changed so you can do your processing here. This [url http://forum.java.sun.com/thread.jsp?forum=57&thread=418560]thread gives a simple example.

Similar Messages

  • Rendering a JTable within a JTable Cell

    How can one render a JTable within another JTable cell?

    You could return JTable in your TableCellRenderer.
    Denis Krukovsky
    http://sourceforge.net/projects/dotuseful/

  • Fragment fields suddenly become editable from within the FORM

    When we added a schema to a form that contains fragments, suddenly the fragment fields became visible and editable from the FORM.  The fields in the fragment are normally not editable unless you edit the fragment. (Designer)
    This is a huge concern for us, especially as we have new developers coming and going on this project.  It is my understanding that fragments should only be editable within the fragment xdp, not from within a form that the fragment is on.
    This is a problem that we can repeat / reproduce.  Would like to know if it's a bug.
    Please advise,
    Thanks,
    Elaine

    Hi Elaine,
    I thought this was a good thing that you can override fragment properties in the document that uses it.  Do you get a message "This fragment reference has local overrides to one or more properties of the source fragment" in the Warnings tab.
    If you don't want the fragments properties to be override you could wrap the fragment in a custom object.
    We have a fragment that has a multiline textfield with a character count and we use the ability to override the properties to update the databinding, caption, traversal, etc., this is then wrapped in a custom object so they can't update what they shouldn't.
    The custom object looks something like this;
    <subform usehref="..\..\Fragments\MultiLineTextField.xdp#som($template.form1.multiLineTextField)" name="name" x="0in" y="0in">
      <bind match="dataRef" ref="$"/>
      <draw name="questionNumber">
      </draw>
      <field name="value">
      <traversal>
        <traverse operation="next" ref="$"/>
      </traversal>
      </field>
    </subform>
    Bruce

  • Image editing from within DWCS3

    Greetings~
    For some reason I can not edit images from within DWCS3. Any time I try to launch the "inhouse" editing tools from the "Properties" pannel I get an error that reads:
         "Unable to launch C:\Program Files\Adobe\Adobe Photoshop CS3\Photoshop.exe. Please be sure that this application exsists and that there is enough memory to run it."
    The strangest part about it is I have removed Photo Shop from my list of Editors through the Preferences. The only editor that I have in the "Editors" list is Fireworks which is set to Primary).
    Any ideas? Thanks guys/gals!

    Which operating system are you on?
    Can you launch Fireworks the conventional way, via a shortcut?
    Nancy O.
    Alt-Web Design & Publishing
    Web | Graphics | Print | Media  Specialists
    www.alt-web.com/
    www.twitter.com/altweb

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

  • Cell Editor for a JTable within A JTable Cell

    My individual cells each contain a seperate JTable and I need to write a cell editor for it. I'm not really sure how to write one so if someone show me where I can find some useful examples of such a cell editor I would greatly appreciate it. Thank you for your time. :-)

    So, you have a big table whose cells each contain a little table. I assume you already have the little tables working correctly with cell editors and so on, and you want to write a cell editor for the big table. Correct?
    My problem with this is that I can't imagine how this would actually work in practice. Suppose I click on a cell in the big table; then the cell renderer displays the appropriate little table. At this point should I see one of the cells in that little table selected, and should I be able to use the Tab key to move around the little table? And if so, then I can't use the Tab key to move around the big table. Next, suppose I press F2 indicating that I want to edit the little table. What should change? Should I now be able to tab around the little table, whereas I couldn't before? And if so, how do I indicate that I have stopped editing the little table? Pressing Enter indicates to the little table's cell editor that its editing is finished, but how should I tell the big table's cell editor that its editing is finished?
    Perhaps if you can answer this, you may have a better idea of how to solve your problem. Sorry I only have questions and not answers.

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

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

  • Opening an image to edit from within Lightroom

    Hi there
    I have just installed Lightroom 5 on my iMac running Yosemite.
    When I click on 'edit in', I have the option of opening PS CS5 or Elements 13, both of which are installed.
    If I choose CS5, the image opens OK.  When I choose Elements, the image doesn't open for editing.
    Any suggestions?
    Thanks
    Peter

    Go to Preferences, then click on the External Editing tab, then under Additional External Editor click on "Choose" and then (remember, this is on Windows, not Mac) point to PhotoshopElementsEditor.exe

  • Edit option not enabled for workflow content from within Content Presenter in Webcenter Spaces

    I have a webcenter spaces portal page with a content presenter displaying a html page using the default out of the box template. The html page is located in webcenter content / UCM under a folder on which the " All Reviewer" seeded workflow is enabled. The issue i am seeing is when the file is in workflow the edit option is not being enabled even though the reviewer should be able to edit/approve the content in this step. The other functions like workflow approve or reject and switching between workflow version and published version are all enabled. Also when rejected the content does not show edit option from the content presenter (cntrl-C option) for the original author to make any updates.
    What would need to be done to enable editing from within the content presenter for workflow content?
    Thanks for your help

    Hi Sreedhar
    We are using WCP 11.1.1.8.5
    To recreate the issue
    1)  Login to WCC Portal: Spaces as admin user , create a New Page under a webcenter spaces portal
    2)  Under the space , Pages Section , select the page and click edit
    3) In Design mode , choose Content Management and Add Document Explorer and Add Content Presenter on the page
    4)  The Document Explorer will default to the Current Space/portal directory under MyWebcenterSpaces in UCM
    5) Create a directory "content" under the Portal space using the document explorer.
    6) Right Click on Content folder and choose details. In Details view , go to File->workflow settings and pick a seeded workflow -> MyWCSAllReviewer. Add a user as workflow approver
    7) After workflow is enabled on this folder upload a basic html page with simple text into this folder
    8) Now in the design mode choose edit in the content presenter and select the "single content view" with default template to display an Image or HTML. Click browse and select the html that was added to workflow
    9) Save the Page and view the portal. Workflow should now be enabled for any content changes to that html page.
    10) Click Cntrl-shift-c in portal/space as an authenticated user with edit access to content and make an edit to content , this will trigger worklow . The author currently will see edit option get disabled once content enters workflow
    11)  Login as approver to the portal and cntrl-shift-C to the portal and workflow options(approve and reject) are enabled but the edit option is not. If you reject content , the author should be able to edit content in the content presenter mode, this also is not available. The issue is the content is now no longer available for editing from wthin content presenter if it is in workflow to either the approver or the original author depending on workflow step. If you check the same content under the document explorer the option to edit is enabled. Is this a bug /issue with content Presenter or some option needs enabled?

  • MouseListener for JTable cells using html

    Hello,
    I'm trying to write a MouseListener that determines whether the cursor is positioned over a certain string within a JTable cell. The cell contains an html string to allow for some formatting.
    For instance, the table data for a certain cell could be "<html><b>SomeBoldText</b>moreText<html>". I would like to detect when a mouse click occurs on the bold text.
    My current solution is to create the glyph vector corresponding to the cell content stripped of all html tags and then check if the cursor position is within one of the glyphs that form the string. However, that obviously doesn't take into account the formatting done by html, so its not working very well.
    Any suggestions?

    the only way you could possibly do this, if you used JEditorPane as a renderer. even then i'm not sure.

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

  • JTable cell edits return to original values

    Hi
    I am making some progress with using AbstractTableModel, however I have a problem whereby any edits that I make to cells within the table are being lost when I add a new row��the original values are re-appearing.
    I have searched through the forum looking for a solution but with no success thus far.
    I believe that the solution lies with the fireTableDataChanged() method but thus far I have had no success. My problem (I believe) is that I cannot work out how to fire it when a user leaves the newly edited cell.
    The method that adds the new rows is shown below and is called from a button on the Frame that houses the jTable. I have tried firing the method from here, hoping that all table edits will persist, but unfortunately they still disappear.
    public void fillTable()
            if(c > 0)
                for (int i = 0; i < c; i = i + 1)
                    this.setValueAt(((JobItemClass) items.get(i)).getItemNumber(), i, 0);
                    this.setValueAt(((JobItemClass) items.get(i)).getDescription(), i, 1);
                    this.setValueAt(((JobItemClass) items.get(i)).getCostPerItem(), i, 2);
                    this.setValueAt(((JobItemClass) items.get(i)).getQuantity(), i, 3);
        public void addRow()
            newItem = new JobItemClass();   //Create an object to hold the new row defsault values
            newItem.setItemNumber(c + 1);
            newItem.setDescription("");
            newItem.setCostPerItem(0.0);
            newItem.setQuantity(0);
            items.add(c, newItem);          //Add the default object to the array
            c = c + 1;                      //Update the variable holding the array size
            table = new Object[c][4];       //Increase the size of the object that acts as the table
            fireTableRowsInserted(c, c);    //Alert the object acting as the table that there is a new row
            fillTable();                    //Refresh the display to reflect the new row default values      
        }As always, any help greatly appreciated
    GB

    Thanks again for the replies people.
    I decided to edit this message and post updated code which can be seen below. This is a result of re-reading the helpfull advice from both azukov and camickr who took the time to respond to my initial request for help. I still have to work out how to validate user input but am sure that the tableChanged method will be the key.
    A simple tutorial also provided great assistance, especially helping eith the implementation of the TableModelListener. I have provided a link to the tutorial here:
    http://www.javalobby.org/articles/jtable/
    The coding was carried out in netbeans 5.5, libraries have not been included.
    Here is my updated code......table model first:
    public class MyJobItemTableModel extends AbstractTableModel
        JobItemClass newItem;   //Procides a default record when nothing available
        int jobNo;
        int c;
        ArrayList items;        //Stores the objects that provide the records
        public MyJobItemTableModel(int j)
            jobNo = j;
            items = (new JobAllItems(jobNo)).getItems();
            c = items.size();
        String columnName[] = { "Item Number", "Item Description", "Cost per item", "Quantity" };       
        Class columnType[] = { Integer.class, String.class, Double.class, Integer.class };
        /**************************This method probably now redundant************************
        public void storeCellValue(int row, int col)
            if(col == 0)
                ((JobItemClass) items.get(row)).setItemNumber((Integer) this.getValueAt(row, col));
            if(col == 1)
                ((JobItemClass) items.get(row)).setDescription((String) this.getValueAt(row, col));
            if(col == 2)
                ((JobItemClass) items.get(row)).setCostPerItem((Double) this.getValueAt(row, col));
            if(col == 3)
                ((JobItemClass) items.get(row)).setQuantity((Integer) this.getValueAt(row, col));
        public void addRow()
            c = c + 1;                          //Update the variable holding the array size
            newItem = new JobItemClass();       //Create a default object to fill the new row
            newItem.setItemNumber(c);
            newItem.setDescription("");
            newItem.setCostPerItem(0.0);
            newItem.setQuantity(0);
            items.add(c-1, newItem);
            this.fireTableRowsInserted(c, c);   //Update the display to show the added row.
        public int getColumnCount()
            return 4;
        public int getRowCount()
            return items.size();
        public Object getValueAt(int r, int c)
            JobItemClass jic = (JobItemClass) items.get(r);
            switch(c)
                case 0:
                    return jic.getItemNumber();
                case 1:
                    return jic.getDescription();
                case 2:
                    return jic.getCostPerItem();
                case 3:
                    return jic.getQuantity();
                default:
                    return new Object();               
        public String getColumnName(int column)
            return columnName[column];
        public Class getColumnClass(int c)
            return columnType[c];
        public boolean hasNoItems()
            if(items.size() == 0)
                return true;
            else
                return false;
        public boolean isCellEditable(int r, int c)
            return true;
        public void setValueAt(Object aValue, int r, int c)
            JobItemClass jic = (JobItemClass) items.get(r);
            switch(c)
                case 0:
                    jic.setItemNumber((Integer)aValue);
                    break;
                case 1:
                    jic.setDescription((String)aValue);
                    break;
                case 2:
                    jic.setCostPerItem((Double)aValue);
                    break;
                case 3:
                    jic.setQuantity((Integer)aValue);
                    break;              
            fireTableCellUpdated(r, c);
    }......and now the view (what the user sees)
    public class ViewItems extends javax.swing.JPanel
        protected MyJobItemTableModel myModel;
        /** Creates new form ViewItems */
        public ViewItems()
            initComponents();
        public void createTable(int jobNo)
            myModel = new MyJobItemTableModel(jobNo);
            myModel.addTableModelListener(new ViewItems.ViewItemsTableModelListener());
            jTable1.setModel(myModel);
            //jTable1.setSurrendersFocusOnKeystroke(true);  //not sure what this does
            if (myModel.hasNoItems())
                myModel.addRow();          
            public void run(int jobNo)
                createTable(jobNo);
                try
                    UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
                    JFrame frame = new JFrame("Invoice Breakdown");
                    frame.addWindowListener(new WindowAdapter()
                        public void windowClosing(WindowEvent evt)
                            setVisible(false);
                    frame.getContentPane().add(this);
                    frame.pack();
                    frame.setVisible(true);
                catch (Exception e)
                    e.printStackTrace();
            /**This class is required in order to respond to any changes that happen
             * to the table or data within, i.e. the user editing data in a cell.
             * The tablemodel (MyJobItemTableModel) will 'fire' the event and the
             * tableChanged() method will be executed.
            public class ViewItemsTableModelListener implements TableModelListener
                public void tableChanged(TableModelEvent evt)
                    if (evt.getType() == TableModelEvent.UPDATE)
                        int column = evt.getColumn();
                        int row = evt.getFirstRow();
                        System.out.println("row: " + row + " column: " + column);
                        jTable1.setColumnSelectionInterval(column + 1, column + 1);
                        jTable1.setRowSelectionInterval(row, row);
            /** 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 = new javax.swing.JTable();
            btnAddItem = new javax.swing.JButton();
            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);
            btnAddItem.setText("Add Item");
            btnAddItem.addActionListener(new java.awt.event.ActionListener()
                public void actionPerformed(java.awt.event.ActionEvent evt)
                    btnAddItemActionPerformed(evt);
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
            this.setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(layout.createSequentialGroup()
                            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 589, Short.MAX_VALUE)
                            .addContainerGap())
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                            .add(btnAddItem)
                            .add(264, 264, 264))))
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 163, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(49, 49, 49)
                    .add(btnAddItem)
                    .addContainerGap(54, Short.MAX_VALUE))
        }// </editor-fold>                       
        private void btnAddItemActionPerformed(java.awt.event.ActionEvent evt)                                          
            ViewItems.this.myModel.addRow();
        // Variables declaration - do not modify                    
        private javax.swing.JButton btnAddItem;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTable jTable1;
        // End of variables declaration                  
        }Edited by: greenockboy on Oct 15, 2007 8:17 PM

  • 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

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

Maybe you are looking for