Progressbar in JTable

Hi
I have added a progressbar to a jtable. but when i add a new record, the earlier record's progressbars are edited. the rows/records are added at random, as the download progresses.
how do i tackle this problem?
Pls help me out. i have only 3 days left to complete my project.

I am not able to understand what u r asking ?
But I think you problem is you are not able to edit all table cell.
I think for JTable u have implemented Renderer and Editor than in Editor's
isCellEditable(java.util.EventObject eventObject)
u need to return true than only you will be able to edit all cells.

Similar Messages

  • Implementar progressbar en jtable

    Me gustaria ver si podria facilitarme un ejemplo en netbeans de un progressbar dentro de un jtable

    Duplicate of Progress Bar in a JTable
    Mod: locking

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

  • Progress bar in JTable?

    Hi,
    I have written a cell renderer for a progress bar but I can't set its string or make it indeterminate. Has anybody done this before? Should I write my own, or use JProgressBar (currently using JProgressBar).
    any help would be brilliant

    Here is a little example I made which shows the JProgressBar being updated.
    Everytime a row is clicked the progress bar adds one percent
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    public class TableProgress extends JFrame{
         public TableProgress(){
              super("Table Progress");
              setSize(500,115);
              Container theContainer = getContentPane();
              String[] headers = {"Name", "Percent Complete", "Progress"};
              Object[][] data = {
                   {"John Adams","50",createBar(50, "50%")},
                   {"Ben Franklin","75",createBar(75, "75%")},
                   {"Karl Marx","0",createBar(0, "0%")},
                   {"Gandalf","20",createBar(20, "20%")},
                   {"Clint Eastwood","55",createBar(55, "55%")}
              final JTable theTable = new JTable(data, headers);
              theTable.setPreferredSize(new Dimension(500,100));
              theTable.getColumn("Progress").setCellRenderer(new ProgRenderer());
              ListSelectionModel rowSM = theTable.getSelectionModel();
              rowSM.addListSelectionListener(new ListSelectionListener() {
                  public void valueChanged(ListSelectionEvent e) {
                      //Ignore extra messages.
                      if (e.getValueIsAdjusting()) return;
                      ListSelectionModel lsm =
                          (ListSelectionModel)e.getSource();
                      if (lsm.isSelectionEmpty()) {
                      } else {
                          int selectedRow = lsm.getMinSelectionIndex();
                          JProgressBar theBar = (JProgressBar)theTable.getValueAt(selectedRow, 2);
                          theBar.setValue(theBar.getValue()+1);
                          theBar.setString(String.valueOf(theBar.getValue()));
                          System.out.println(selectedRow);
              theContainer.add(theTable);
              setVisible(true);
              show();
         public JProgressBar createBar(int percentDone, String text){
              JProgressBar progressBar = new JProgressBar(0, 100);
              progressBar.setStringPainted(true);
              progressBar.setValue(percentDone);
              progressBar.setString(text);
              return progressBar;
         private class ProgRenderer implements TableCellRenderer{
              public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column){
                   return (JProgressBar)value;
         public static void main(String[] args){
              TableProgress theTable = new TableProgress();
    }

  • JComboBox, JTable, cellRendering CHALLENGE

    Hi all,
    I would like to ask a question of the resident guru concerning a Netbeans/MYSQL application. I based it on a tutorial found here: [http://www.netbeans.org/kb/61/java/gui-db-custom.html].
    I have two seperate JDialogs that write data to a master table. One of the JDialogs is called "Customer Editor" and it contains various text fields bound to cells on the masterTable, no big deal.
    Also in the "Customer Editor" JDialog there is a JComboBox that has a list of four values to choose from which are "Good", "Standby", "Failed", and "Complete".
    I would like the data selected from the JComboBox to color itself when it writes to the JTable row/cell on the masterTable. For example if the user selects "Good" from the list, in the masterTable the font color of the String will be GREEN. Similarly, if the user selects "Failed" from the JComboBox I would like the String to return RED...following on "Standby" - BLUE, "Complete" - no color change.
    Question: How do I write code that allows me to change the color of text in a cell when it comes from a JComboBox list?
    If anyone out there picks up this thread, I will of course supply the code I have so far. I won't do it now as I am not sure even where the code should go. I think it would go in the source code for the masterTable view but I am not certain.
    Any Java masters out there?
    David

    Thanks for the reply. I have been writing different cell renderers to get it working. Where should the code reside?
    This is my operations view class. Should it be in here.
    /CODE/
    package operationsrecords;
    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 org.jdesktop.application.Task;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Iterator;
    import java.util.LinkedList;
    import java.util.List;
    import javax.persistence.RollbackException;
    import javax.swing.Timer;
    import javax.swing.Icon;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import org.jdesktop.beansbinding.AbstractBindingListener;
    import org.jdesktop.beansbinding.Binding;
    import org.jdesktop.beansbinding.PropertyStateEvent;
    * The application's main frame.
    public class OperationsRecordsView extends FrameView {
    public OperationsRecordsView(SingleFrameApplication app) {
    super(app);
    initComponents();
    // 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);
    // tracking table selection
    masterTable.getSelectionModel().addListSelectionListener(
    new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
    firePropertyChange("recordSelected", !isRecordSelected(), isRecordSelected());
    detailTable.getSelectionModel().addListSelectionListener(
    new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
    firePropertyChange("detailRecordSelected", !isDetailRecordSelected(), isDetailRecordSelected());
    // tracking changes to save
    bindingGroup.addBindingListener(new AbstractBindingListener() {
    @Override
    public void targetChanged(Binding binding, PropertyStateEvent event) {
    // save action observes saveNeeded property
    setSaveNeeded(true);
    // have a transaction started
    entityManager.getTransaction().begin();
    public boolean isSaveNeeded() {
    return saveNeeded;
    private void setSaveNeeded(boolean saveNeeded) {
    if (saveNeeded != this.saveNeeded) {
    this.saveNeeded = saveNeeded;
    firePropertyChange("saveNeeded", !saveNeeded, saveNeeded);
    public boolean isRecordSelected() {
    return masterTable.getSelectedRow() != -1;
    public boolean isDetailRecordSelected() {
    return detailTable.getSelectedRow() != -1;
    @Action
    public void newRecord() {
    operationsrecords.Customers c = new operationsrecords.Customers();
    entityManager.persist(c);
    list.add(c);
    int row = masterTable.getRowCount() - 1;
    masterTable.setRowSelectionInterval(row, row);
    masterTable.scrollRectToVisible(masterTable.getCellRect(row, 0, true));
    setSaveNeeded(true);
    JFrame mainFrame = OperationsRecordsApp.getApplication().getMainFrame();
    CustomerEditor ce = new CustomerEditor(mainFrame, false);
    ce.setCurrentRecord(c);
    ce.setVisible(true);
    if (ce.isCustomerConfirmed()) {
    save().run();
    } else {
    refresh().run();
    @Action(enabledProperty = "recordSelected")
    public void deleteRecord() {
    Object[] options = {"OK", "Cancel"};
    int n = JOptionPane.showConfirmDialog(null, "Delete the records permanently?", "Warning",
    JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null);
    if (n == JOptionPane.YES_OPTION) {
    int[] selected = masterTable.getSelectedRows();
    List<operationsrecords.Customers> toRemove = new ArrayList<operationsrecords.Customers>(selected.length);
    for (int idx = 0; idx < selected.length; idx++) {
    operationsrecords.Customers c = list.get(masterTable.convertRowIndexToModel(selected[idx]));
    toRemove.add(c);
    entityManager.remove(c);
    list.removeAll(toRemove);
    save().run();
    } else {
    refresh().run();
    @Action(enabledProperty = "recordSelected")
    public void newDetailRecord() {
    int index = masterTable.getSelectedRow();
    operationsrecords.Customers c = list.get(masterTable.convertRowIndexToModel(index));
    Collection<operationsrecords.Orders> os = c.getOrdersCollection();
    if (os == null) {
    os = new LinkedList<operationsrecords.Orders>();
    c.setOrdersCollection(os);
    operationsrecords.Orders o = new operationsrecords.Orders();
    o.setShipDate(new java.util.Date());
    entityManager.persist(o);
    o.setCustomerId(c);
    os.add(o);
    masterTable.clearSelection();
    masterTable.setRowSelectionInterval(index, index);
    int row = os.size()-1;
    detailTable.setRowSelectionInterval(row, row);
    detailTable.scrollRectToVisible(detailTable.getCellRect(row, 0, true));
    setSaveNeeded(true);
    JFrame mainFrame = OperationsRecordsApp.getApplication().getMainFrame();
    OrderEditor oe = new OrderEditor(mainFrame, false);
    oe.setCurrentOrderRecord(o);
    oe.setVisible(true);
    if (oe.isOrderConfirmed()) {
    save().run();
    } else {
    refresh().run();
    @Action(enabledProperty = "detailRecordSelected")
    public void deleteDetailRecord() {
    Object[] options = {"OK", "Cancel"};
    int n = JOptionPane.showConfirmDialog(null, "Delete the records permanently?", "Warning",
    JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null);
    if (n == JOptionPane.YES_OPTION) {
    int index = masterTable.getSelectedRow();
    operationsrecords.Customers c = list.get(masterTable.convertRowIndexToModel(index));
    Collection<operationsrecords.Orders> os = c.getOrdersCollection();
    int[] selected = detailTable.getSelectedRows();
    List<operationsrecords.Orders> toRemove = new ArrayList<operationsrecords.Orders>(selected.length);
    for (int idx = 0; idx < selected.length; idx++) {
    selected[idx] = detailTable.convertRowIndexToModel(selected[idx]);
    int count = 0;
    Iterator<operationsrecords.Orders> iter = os.iterator();
    while (count++ < selected[idx]) {
    iter.next();
    operationsrecords.Orders o = iter.next();
    toRemove.add(o);
    entityManager.remove(o);
    os.removeAll(toRemove);
    masterTable.clearSelection();
    masterTable.setRowSelectionInterval(index, index);
    list.removeAll(toRemove);
    save().run();
    } else {
    refresh().run();
    @Action(enabledProperty = "saveNeeded")
    public Task save() {
    return new SaveTask(getApplication());
    private class SaveTask extends Task {
    SaveTask(org.jdesktop.application.Application app) {
    super(app);
    @Override protected Void doInBackground() {
    try {
    entityManager.getTransaction().commit();
    entityManager.getTransaction().begin();
    } catch (RollbackException rex) {
    rex.printStackTrace();
    entityManager.getTransaction().begin();
    List<operationsrecords.Customers> merged = new ArrayList<operationsrecords.Customers>(list.size());
    for (operationsrecords.Customers c : list) {
    merged.add(entityManager.merge(c));
    list.clear();
    list.addAll(merged);
    return null;
    @Override protected void finished() {
    setSaveNeeded(false);
    * An example action method showing how to create asynchronous tasks
    * (running on background) and how to show their progress. Note the
    * artificial 'Thread.sleep' calls making the task long enough to see the
    * progress visualization - remove the sleeps for real application.
    @Action
    public Task refresh() {
    return new RefreshTask(getApplication());
    private class RefreshTask extends Task {
    RefreshTask(org.jdesktop.application.Application app) {
    super(app);
    @SuppressWarnings("unchecked")
    @Override protected Void doInBackground() {
    setProgress(0, 0, 4);
    setMessage("Rolling back the current changes...");
    setProgress(1, 0, 4);
    entityManager.getTransaction().rollback();
    setProgress(2, 0, 4);
    setMessage("Starting a new transaction...");
    entityManager.getTransaction().begin();
    setProgress(3, 0, 4);
    setMessage("Fetching new data...");
    java.util.Collection data = query.getResultList();
    for (Object entity : data) {
    entityManager.refresh(entity);
    setProgress(4, 0, 4);
    list.clear();
    list.addAll(data);
    return null;
    @Override protected void finished() {
    setMessage("Done.");
    setSaveNeeded(false);
    @Action
    public void showAboutBox() {
    if (aboutBox == null) {
    JFrame mainFrame = OperationsRecordsApp.getApplication().getMainFrame();
    aboutBox = new OperationsRecordsAboutBox(mainFrame);
    aboutBox.setLocationRelativeTo(mainFrame);
    OperationsRecordsApp.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.
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
    mainPanel = new javax.swing.JPanel();
    masterScrollPane = new javax.swing.JScrollPane();
    masterTable = new javax.swing.JTable();
    newButton = new javax.swing.JButton();
    deleteButton = new javax.swing.JButton();
    detailScrollPane = new javax.swing.JScrollPane();
    detailTable = new javax.swing.JTable();
    deleteDetailButton = new javax.swing.JButton();
    newDetailButton = new javax.swing.JButton();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jLabel2 = new javax.swing.JLabel();
    menuBar = new javax.swing.JMenuBar();
    javax.swing.JMenu fileMenu = new javax.swing.JMenu();
    javax.swing.JMenuItem newRecordMenuItem = new javax.swing.JMenuItem();
    javax.swing.JMenuItem deleteRecordMenuItem = new javax.swing.JMenuItem();
    jSeparator1 = new javax.swing.JSeparator();
    javax.swing.JMenuItem saveMenuItem = new javax.swing.JMenuItem();
    javax.swing.JMenuItem refreshMenuItem = new javax.swing.JMenuItem();
    jSeparator2 = new javax.swing.JSeparator();
    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();
    entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("OperationsRecordsPU").createEntityManager();
    org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(operationsrecords.OperationsRecordsApp.class).getContext().getResourceMap(OperationsRecordsView.class);
    query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery(resourceMap.getString("query.query")); // NOI18N
    list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
    rowSorterToStringConverter1 = new operationsrecords.RowSorterToStringConverter();
    mainPanel.setBackground(resourceMap.getColor("mainPanel.background")); // NOI18N
    mainPanel.setName("mainPanel"); // NOI18N
    masterScrollPane.setName("masterScrollPane"); // NOI18N
    masterTable.setBackground(resourceMap.getColor("masterTable.background")); // NOI18N
    masterTable.setGridColor(resourceMap.getColor("masterTable.gridColor")); // NOI18N
    masterTable.setName("masterTable"); // NOI18N
    masterTable.setShowVerticalLines(false);
    org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list, masterTable);
    org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${jobId}"));
    columnBinding.setColumnName("Job Id");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${statusId.status}"));
    columnBinding.setColumnName("Status Id.status");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${company}"));
    columnBinding.setColumnName("Company");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${rig}"));
    columnBinding.setColumnName("Rig");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${well}"));
    columnBinding.setColumnName("Well");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${county}"));
    columnBinding.setColumnName("County");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${state}"));
    columnBinding.setColumnName("State");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${companyMan}"));
    columnBinding.setColumnName("Company Man");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${phone}"));
    columnBinding.setColumnName("Phone");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${fax}"));
    columnBinding.setColumnName("Fax");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${emailAddress}"));
    columnBinding.setColumnName("Email Address");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    bindingGroup.addBinding(jTableBinding);
    jTableBinding.bind();
    masterScrollPane.setViewportView(masterTable);
    masterTable.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("masterTable.columnModel.title0")); // NOI18N
    masterTable.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("masterTable.columnModel.title1")); // NOI18N
    masterTable.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("masterTable.columnModel.title2")); // NOI18N
    masterTable.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("masterTable.columnModel.title3")); // NOI18N
    masterTable.getColumnModel().getColumn(4).setHeaderValue(resourceMap.getString("masterTable.columnModel.title4")); // NOI18N
    masterTable.getColumnModel().getColumn(5).setHeaderValue(resourceMap.getString("masterTable.columnModel.title5")); // NOI18N
    masterTable.getColumnModel().getColumn(6).setHeaderValue(resourceMap.getString("masterTable.columnModel.title6")); // NOI18N
    masterTable.getColumnModel().getColumn(7).setHeaderValue(resourceMap.getString("masterTable.columnModel.title7")); // NOI18N
    masterTable.getColumnModel().getColumn(8).setHeaderValue(resourceMap.getString("masterTable.columnModel.title8")); // NOI18N
    masterTable.getColumnModel().getColumn(9).setHeaderValue(resourceMap.getString("masterTable.columnModel.title9")); // NOI18N
    masterTable.getColumnModel().getColumn(10).setHeaderValue(resourceMap.getString("masterTable.columnModel.title10")); // NOI18N
    javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(operationsrecords.OperationsRecordsApp.class).getContext().getActionMap(OperationsRecordsView.class, this);
    newButton.setAction(actionMap.get("newRecord")); // NOI18N
    newButton.setBackground(resourceMap.getColor("newButton.background")); // NOI18N
    newButton.setName("newButton"); // NOI18N
    deleteButton.setAction(actionMap.get("deleteRecord")); // NOI18N
    deleteButton.setBackground(resourceMap.getColor("jButton1.background")); // NOI18N
    deleteButton.setName("deleteButton"); // NOI18N
    detailScrollPane.setName("detailScrollPane"); // NOI18N
    detailTable.setGridColor(resourceMap.getColor("detailTable.gridColor")); // NOI18N
    detailTable.setName("detailTable"); // NOI18N
    detailTable.setShowVerticalLines(false);
    detailTable.getTableHeader().setReorderingAllowed(false);
    org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${selectedElement.ordersCollection}");
    jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, eLProperty, detailTable);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${shipDate}"));
    columnBinding.setColumnName("Ship Date");
    columnBinding.setColumnClass(java.util.Date.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${tool}"));
    columnBinding.setColumnName("Tool");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${collar}"));
    columnBinding.setColumnName("Collar");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${xo}"));
    columnBinding.setColumnName("Xo");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${xo2}"));
    columnBinding.setColumnName("Xo2");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${surfaceKit}"));
    columnBinding.setColumnName("Surface Kit");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${comments}"));
    columnBinding.setColumnName("Comments");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${directions}"));
    columnBinding.setColumnName("Directions");
    columnBinding.setColumnClass(String.class);
    columnBinding.setEditable(false);
    jTableBinding.setSourceUnreadableValue(java.util.Collections.emptyList());
    bindingGroup.addBinding(jTableBinding);
    jTableBinding.bind();
    detailScrollPane.setViewportView(detailTable);
    detailTable.getColumnModel().getColumn(0).setResizable(false);
    detailTable.getColumnModel().getColumn(0).setPreferredWidth(10);
    detailTable.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("detailTable.columnModel.title0")); // NOI18N
    detailTable.getColumnModel().getColumn(1).setResizable(false);
    detailTable.getColumnModel().getColumn(1).setPreferredWidth(5);
    detailTable.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("detailTable.columnModel.title1")); // NOI18N
    detailTable.getColumnModel().getColumn(2).setResizable(false);
    detailTable.getColumnModel().getColumn(2).setPreferredWidth(5);
    detailTable.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("detailTable.columnModel.title2")); // NOI18N
    detailTable.getColumnModel().getColumn(3).setResizable(false);
    detailTable.getColumnModel().getColumn(3).setPreferredWidth(5);
    detailTable.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("detailTable.columnModel.title3")); // NOI18N
    detailTable.getColumnModel().getColumn(4).setResizable(false);
    detailTable.getColumnModel().getColumn(4).setPreferredWidth(5);
    detailTable.getColumnModel().getColumn(4).setHeaderValue(resourceMap.getString("detailTable.columnModel.title4")); // NOI18N
    detailTable.getColumnModel().getColumn(5).setResizable(false);
    detailTable.getColumnModel().getColumn(5).setPreferredWidth(5);
    detailTable.getColumnModel().getColumn(5).setHeaderValue(resourceMap.getString("detailTable.columnModel.title5")); // NOI18N
    detailTable.getColumnModel().getColumn(6).setResizable(false);
    detailTable.getColumnModel().getColumn(6).setPreferredWidth(300);
    detailTable.getColumnModel().getColumn(6).setHeaderValue(resourceMap.getString("detailTable.columnModel.title6")); // NOI18N
    detailTable.getColumnModel().getColumn(7).setResizable(false);
    detailTable.getColumnModel().getColumn(7).setPreferredWidth(300);
    detailTable.getColumnModel().getColumn(7).setHeaderValue(resourceMap.getString("detailTable.columnModel.title7")); // NOI18N
    deleteDetailButton.setAction(actionMap.get("deleteDetailRecord")); // NOI18N
    deleteDetailButton.setBackground(resourceMap.getColor("jButton1.background")); // NOI18N
    deleteDetailButton.setName("deleteDetailButton"); // NOI18N
    newDetailButton.setAction(actionMap.get("newDetailRecord")); // NOI18N
    newDetailButton.setBackground(resourceMap.getColor("jButton1.background")); // NOI18N
    newDetailButton.setName("newDetailButton"); // NOI18N
    jButton1.setAction(actionMap.get("editCustomer")); // NOI18N
    jButton1.setBackground(resourceMap.getColor("jButton1.background")); // NOI18N
    jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
    jButton1.setName("jButton1"); // NOI18N
    jButton2.setAction(actionMap.get("editOrder")); // NOI18N
    jButton2.setBackground(resourceMap.getColor("jButton1.background")); // NOI18N
    jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
    jButton2.setName("jButton2"); // NOI18N
    jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
    jLabel1.setName("jLabel1"); // NOI18N
    jTextField1.setName("jTextField1"); // NOI18N
    org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${rowSorter}"), jTextField1, org.jdesktop.beansbinding.BeanProperty.create("text"));
    binding.setConverter(rowSorterToStringConverter1);
    bindingGroup.addBinding(binding);
    jLabel2.setIcon(resourceMap.getIcon("jLabel2.icon")); // NOI18N
    jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
    jLabel2.setName("jLabel2"); // NOI18N
    javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
    mainPanel.setLayout(mainPanelLayout);
    mainPanelLayout.setHorizontalGroup(
    mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(mainPanelLayout.createSequentialGroup()
    .addContainerGap()
    .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(detailScrollPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 1057, Short.MAX_VALUE)
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
    .addComponent(newDetailButton)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jButton2)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(deleteDetailButton))
    .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT

  • How to save from a JTable to .CSV file format?

    i am building a client sever model in which the client will send the details to the server...
    the server will take all the details and display it in a jtable..
    now, after sorting it using autorowsorter(..), how can i save the data from table to a .CSV file???
    Thanks in advance..

    Here is one code from my own my application. It should compile straight away, but if there are any compile time bugs, you can easily fix them. Pls do read the comments at the top.
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.filechooser.*;
    import javax.swing.table.*;
    * This class is now JDK 1.6 Dependent, with the addition of the use of the Desktop
    * class instead of the default application launch procedure, and the use of the new
    * FileNameExtensionFilter class introduced under javax.swing.filechooser.
    * This class can be used in one line of code by passing the appropriate JTable to the
    * desired constructor.
    public class ExcelExporter extends Object {
        public JTable source;
        public JFileChooser chooser;
        public File csvFile;
        private boolean cancelOp = false, isDefault = true;
        private String topText = "";
        public ExcelExporter(JTable source) {
            this(source, "");
        public ExcelExporter(JTable source, String topText) {
            this(source, topText, true);
        public ExcelExporter(JTable source, String topText, boolean isDefault, File target, JProgressBar bar) {
            super();
            this.source = source;
            this.topText = topText;
            this.isDefault = isDefault;
            new ProgressDialog(source, target, bar);
        public ExcelExporter(JTable source, String topText, boolean isDefault) {
            super();
            this.source = source;
            this.topText = topText;
            this.isDefault = isDefault;
            obtainFileName();
        public void obtainFileName() {
            cancelOp = false;
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel Format (CSV)", "csv");
            if(chooser == null) {
                chooser = new JFileChooser();
                chooser.setDialogTitle("Saving Database");
                chooser.setFileFilter(filter);
                chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                chooser.setSelectedFile( new File("database.csv") );
                chooser.setAcceptAllFileFilterUsed(false);                     
            int val = chooser.showSaveDialog((Component)null);
            if(val == JFileChooser.APPROVE_OPTION) {
                csvFile = chooser.getSelectedFile();
                boolean fixed = fixExtension(csvFile, "csv");
                if(!fixed && !cancelOp) {
                    JOptionPane.showMessageDialog(null,"File Name Specified Not Supported",
                    "File Name Error", JOptionPane.ERROR_MESSAGE);
                    obtainFileName();
                    return;
                if(!cancelOp) {
                    //storeTableAsCSV(csvFile, source);
                    new ProgressDialog(source, csvFile).setVisible(true);
        public boolean fixExtension(File file, String prefExt) {
            String fileName = file.getName();
            String dir = file.getParentFile().getAbsolutePath();
            String ext = null;
            try {
                ext = fileName.substring( fileName.lastIndexOf("."), fileName.length() );
                System.out.println("Original File Extension: " + ext);
            } catch(StringIndexOutOfBoundsException e) {
                ext = null;
            if(ext != null && !ext.equalsIgnoreCase("."+prefExt)) {
                return false;
            String csvName = null;
            if(ext == null || ext.length() == 0) {
                csvName = fileName + "." + prefExt;
            } else {
                csvName = fileName.substring(0, fileName.lastIndexOf(".") + 1) + prefExt;
            System.out.println("Corrected File Name: " + csvName);
            File csvCert = new File(dir, csvName);
            if(csvCert.exists()) {
                int val = JOptionPane.showConfirmDialog(null, "Replace Existing File?", "File Exists",
                            JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
                if(val == JOptionPane.NO_OPTION) {
                    obtainFileName();
                    cancelOp = true;
                    return false;
                } else if(val == JOptionPane.CANCEL_OPTION) {
                    cancelOp = true;
                    return false;              
            if(!file.renameTo(csvCert)) {
                file = new File(dir, csvName);
                try {
                    file.createNewFile();
                } catch(IOException ioe) {}
            System.out.println("Exporting as: " + file.getAbsolutePath() );
            return true;
        public void storeTableAsCSV(File target, JTable src) {
            String csvData = topText + "\n\n";
            for(int i = 0; i < src.getModel().getRowCount(); i++) {
                for(int x = 0; x < src.getModel().getColumnCount(); x++) {
                    int col = src.convertColumnIndexToView(x);
                    String curVal = (String)src.getModel().getValueAt(i,col);
                    if(curVal == null) {
                        curVal = "";
                    csvData = csvData + removeAnyCommas(curVal) + ",";
                    if(isDefault) {
                        if(x == src.getModel().getColumnCount() - 3) {
                            csvData = csvData + "\n";
                            continue;
                    } else {
                        if(x == src.getModel().getColumnCount() - 1) {
                            csvData = csvData + "\n";                      
            try {
                FileWriter writer = new FileWriter(target);
                    writer.write(csvData);
                    writer.flush();
                    writer.close();
                writer = null;
                csvData = null;
            } catch(IOException ioe) {
                JOptionPane.showMessageDialog(source, "Error Writing File.\nFile may be in use by another application."
                + "\nCheck and try re-exporting", "Export Error", JOptionPane.ERROR_MESSAGE);
        public String removeAnyCommas(String src) {
            if(src == null) {
                return "";
            for(int i = 0; i < src.length(); i++) {
                if(src.charAt(i) == ',') {
                    src = src.substring(0,i) + src.substring(i+1, src.length());
            return src;
        class ProgressDialog extends JDialog {
            JProgressBar progress;
            JLabel progressLabel;
            javax.swing.Timer timer;
            int rowPoint = -1;
            StringBuffer data;
            JTable srcTable;       
            DefaultTableModel srcModel;
            File targetFile;
            public ProgressDialog(JTable src, File target) {
                super( new JDialog(), "Exporting", true);
                createUI();
                setLocationRelativeTo(null);
                srcTable = src;
                srcModel = (DefaultTableModel)src.getModel();
                targetFile = target;
                exportDataProgressively();
            public ProgressDialog(JTable src, File target, JProgressBar progress) {
                super();
                srcTable = src;
                srcModel = (DefaultTableModel)src.getModel();
                targetFile = target;
                setProgressBar(progress);
                exportDataProgressively();
            public void createUI() {
                progress = new JProgressBar(0, 100);
                progress.setIndeterminate(true);
                progress.setValue(0);
                progress.setBorder( BorderFactory.createCompoundBorder(
                                        BorderFactory.createEmptyBorder(10,10,10,10),
                                    UIManager.getBorder("ProgressBar.border") ) );
                progress.setPreferredSize( new Dimension(300, 38) );
                progressLabel = new JLabel("Writing Excel Format. Please Wait...");
                progressLabel.setFont( new Font("Verdana", Font.PLAIN, 11) );
                progressLabel.setBorder( BorderFactory.createEmptyBorder(10,10,10,10) );
                JPanel progressPanel = new JPanel( new BorderLayout() );
                    progressPanel.add(progressLabel, BorderLayout.NORTH );
                    progressPanel.add(progress, BorderLayout.CENTER);
                    progressPanel.setBorder( BorderFactory.createEmptyBorder(10,10,10,10) );
                setContentPane(progressPanel);         
                pack();
            public void exportDataProgressively() {
                //progress.setString("");
                progress.setMaximum(srcModel.getRowCount());
                progress.setIndeterminate(false);
                data = new StringBuffer("Autogenerated Excel Format"
                     + topText + "\n\n");          
                timer = new javax.swing.Timer(15, new ActionListener() {
                    public void actionPerformed(ActionEvent e) {                   
                        if(rowPoint > -1 && srcModel.getValueAt(rowPoint,0) == null) {
                            timer.stop();
                        progress.setValue(rowPoint);
                        appendData();
                timer.setRepeats(false);
                timer.start();
            public void appendData() {
                timer.stop();
                for(int j = 0; j < srcModel.getColumnCount(); j++) {
                    int col = srcTable.convertColumnIndexToView(j);
                    if(rowPoint == -1) {
                        data.append(removeAnyCommas((String)srcModel.getColumnName(col)).toUpperCase());
                    } else if(col != -1){
                        String text = (String)srcModel.getValueAt(rowPoint,col);
                        if(srcModel.getColumnName(col).equalsIgnoreCase("Phone Number(s)") && !isPrintableText(text) ) {
                            text = "\'" + getPrintableText(text);
                        } else if( srcModel.getColumnName(col).equalsIgnoreCase("Phone Number(s)") && isPrintableText(text)  ) {
                            text = "\'" + removeAnyCommas(text);
                        } else {
                            text = removeAnyCommas(text);
                        data.append(text);
                    if(isDefault) {
                        if(j != srcModel.getColumnCount() - 3 ){
                            data.append(",");
                        } else {
                            data.append("\n");
                            break;
                    } else {
                        if(j != srcModel.getColumnCount() - 1 ){
                            data.append(",");
                        } else {
                            data.append("\n");
                rowPoint++;
                if(rowPoint < srcModel.getRowCount()) {
                    timer.start();
                } else {
                    try {
                        if(!targetFile.exists())
                            targetFile.createNewFile();
                        FileWriter writer = new FileWriter(targetFile);
                            writer.write(data.toString());
                            writer.close();
                            progress.setValue(progress.getMaximum());
                            progress.setStringPainted(true);
                            progress.setString("Done");
                            openFile(targetFile);                      
                            setVisible(false);
                            data = null;
                    } catch(IOException ioe) {
                        JOptionPane.showMessageDialog(source, "Error Writing File. Try Resaving",
                        "Save Error", JOptionPane.ERROR_MESSAGE);
                    } catch(Exception exc) {
                        System.out.println(exc);
            public void setProgressBar(JProgressBar bar) {
                progress = bar;
            public boolean isPrintableText(String text) {
                return !text.contains("::");
            public String getPrintableText(String text) {          
                try {
                    text = text.substring(2);
                } catch(StringIndexOutOfBoundsException sie) {
                    System.out.println(sie);
                String generated = "";
                StringTokenizer st = new StringTokenizer(text, ",");
                try {
                    for(int i = 0; st.hasMoreTokens(); i++ ) {
                        if(i > 0) {
                            generated = generated + " / ";
                        String token = st.nextToken();
                        generated = generated + token.substring( token.indexOf("-") + 2 );
                } catch(NoSuchElementException nse) {}
                return generated;
            public void openFile(File file) {
                int val = JOptionPane.showConfirmDialog(null, "Would You Like To View The File Right Now?",
                "View File", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
                try {
                    if(val == JOptionPane.YES_OPTION) {
                        if(Desktop.isDesktopSupported()) {
                            Desktop.getDesktop().open(file);
                        } else {
                            new ExcelExecutor(file.getAbsolutePath());
                } catch(IOException ioe) {
                    JOptionPane.showMessageDialog(null, "Failed to Open File", "Error",
                     JOptionPane.ERROR_MESSAGE);
    }ICE

  • Keep track of reference of a row added to Jtable

    Hello All,
    I need to keep track of reference of a row which is being added in JTable.
    Let suppose that I adds a row in JTable based on an object (instantiated of a class say FileUploader class). Now I adds a row whenever FileUploader class is being instantiated. The FileUploader Class is responsible to upload a file.
    1) Now suppose that there are 100 rows (of course based on 100 object of FileUploader class).
    2) User can remove single or multiple row (by means of cancel the process of upload or clear the row in the JTable for which file has successfully uploaded).
    3) I need to update a particular cell of JTable based on the status of a particular object of class FileUploader.
    One way of doing this is by using for loop on whole table to find out the corresponding row (based on some key taken from table). But this will make the application very slow.
    So, to do this, I need to have the reference of the row when it is being added in the JTable.
    How can I make it working? Please suggest.
    Thank you

    You are right that iterating over 100 times is not slow. But what will happen if there are 10000 rows.
    I am new to JTable. In my application, when user drag and drop some files / folder, a row is being added in the JTable to show the status of process (pending, ProgressBar, Completed or Error in one cell based on the current status of file / folder ) along with some more info in other cell ( like fileName, FromDir, ToDir, Size, and a hyperlink type text for action - clear, cancel, retry).
    Now FileUploader is an class which is responsible for uploading (it has a method upload() in it which is called by a daemon thread).
    So to update a particular cell (in which pending / ProgressBar/ etc is shown), I need to find the particular row which is showing the status of a file / folder.
    How can I do it (without iterating over these no. of times again and again).
    Is there any better approach to do this.

  • How do I get at a JTable on a JInternalFrame?

    I've been working on this Multiple Document Interface application, and things have been great up to this point. The user chooses to run a "report" and then selects an entity to get the info for. I then hit the database. Each row returned from the database query goes into it's own data object, which is added to an ArrayList in my custom table model, and that ArrayList is used to generate the JTable, which is then added to a ScrollPane, which is then added to the JInternalFrame, which is then added to the JDesktop pane. Good stuff, right?
    I'm now trying to add Print functionality, and I'm at a loss. What I want to do is have the user do the standard File->Print, which will print out the JTable on the currently selected inner frame. I can get a JTable to print using JTable.print(). What I can't do is find a way to get the JTable from the selected frame.
    I can get the selected frame using desktop.getSelectedFrame(), but I'm at a loss as to what to do next. I've played around with .getComponent, but I'm not having any luck. the components returned don't seem to do me any good...for example, JViewPort?
    Am I going about this the wrong way? Have I poorly designed this? Am I missing the obvious?
    Thanks,
    -Adam

    Well, if you only have a single component on the internal frame then you can use getComponent(0). But then you need to go up the parent chain to get the actual table. You will initially get the JScrollPane, then use that to get the JViewport and then use that to get the viewport component.
    Another option is to extend the JInternalFrame class and insted using the add method to add a component you create get/setTable(...) methods. Then you can save the table as a class variable before adding it the scrollpane and adding the scrollpane to the internal frame.

  • JTable - Can I change the color of the text on a row by row basis?

    Hi All,
    I'm redoing a bit of old uni coursework (to model a stockmarket, stock ticker server & stock ticker application) to brush up my Java skills (esp Swing and Event Handling) and am programming the UI by hand using Swing (its the only way to learn something....(I've certianly nailed Layout Management!!))
    In the stocktickerserver GUI I'm using a JTable to display the details about stocks.
    The user can select a stock and view the details of the stock in another frame. In one panel in the JFrame I've got a JTable listing the history items for the stock (Price, Change, Date).
    Is it possible to color the rows of the JTable according to the value of the change column (or at least the value I insert there)?
    e.g
    if (change > 0){
    Blue;
    else{
    if (change < 0){
    Red;
    else{
    Green;
    I'm completly ignorant on how to achieve this (or even if its possible at all) so all your ideas welcome.
    Any help much appreciated
    Pete
    P.S.
    The Stock History is a class that I store in a [private] Vector in the Stock Class.
    For the selected Stock I loop through this vector getting the items (using various accessor methods)
    I extract the values from the return StockHistory object and build a DefaultTableModel from these
    Then I call JTable.setModel(theModel) to build the table

    implement TableCellRenderer and change foreground of the Renderer in the method getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) . Install this renderer to your table.

  • How to select a specific cell in a JTable?

    Hi there,
    in a JTable, I would like to select a specific cell (to highlight it) from a JButton.
    Here a sample code...
    Who could help me to fill it?
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TableSelection{
        public static void main (String args[]) {
          JFrame frame = new MyFrame();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.show();
    class MyFrame extends JFrame{
      public MyFrame(){
        setTitle("TableSelection");
        setSize(WIDTH,HEIGHT);
        DefaultTableModel myModel = new DefaultTableModel(2,2);
        JTable myTable = new JTable(myModel);
        myTable.setCellSelectionEnabled(true);
        JButton button00 = new JButton("select 0,0");
        button00.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent event){
         System.out.println("selection of cell (0,0)");
         //--- what code is required to select the cell(0,0)?
        JButton button11 = new JButton("select 1,1");
        button11.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent event){
         System.out.println("selection of cell (1,1)");
         //--- what code is required to select the cell(1,1)?
        Box myBox = new Box(BoxLayout.Y_AXIS);
        myBox.add(new JScrollPane(myTable));
        myBox.add(button00);
        myBox.add(button11);
        getContentPane().add(myBox, BorderLayout.CENTER);
      private static final int WIDTH=200;
      private static final int HEIGHT=200;
    }Thanks a lot for your help.
    Denis

    Use the addColumnSelectionInterval(int index1, int index2)method ~ http://java.sun.com/j2se/1.4/docs/api/javax/swing/JTable.html#addColumnSelectionInterval(int,%20int)
    and the addRowSelectionInterval(int index1, int index2) method ~ http://java.sun.com/j2se/1.4/docs/api/javax/swing/JTable.html#addRowSelectionInterval(int,%20int)
    Hope that helped.
    afotoglidis

  • Create a JTable based on an ArrayList containing instances of a class.

    I have a class, IncomeBudgetItem, instances of which are contained in an ArrayList. I would like to create a JTable, based on this ArrayList. One variable is a string, while others are type double. Not all variables are to appear in the JTable.
    The internal logic of my program is already working. And my GUI is largely constructed. I'm just not sure how to make them talk to each other. The actually creation of the JTable is my biggest problem right now.

    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.util.ArrayList;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    public class TableDemo extends JPanel {
         private boolean DEBUG = false;
         public TableDemo() {
              super(new GridLayout(1, 0));
              ArrayList<MyObject> list = new ArrayList<MyObject>();
              list.add(new MyObject("Kathy", "Smith", "Snowboarding", new Integer(5),
                        new Boolean(false)));
              list.add(new MyObject("John", "Doe", "Rowing", new Integer(3),
                        new Boolean(true)));
              list.add(new MyObject("Sue", "Black", "Knitting", new Integer(2),
                        new Boolean(false)));
              list.add(new MyObject("Jane", "White", "Speed reading",
                        new Integer(20), new Boolean(true)));
              JTable table = new JTable(new MyTableModel(list));
              table.setPreferredScrollableViewportSize(new Dimension(500, 70));
              table.setFillsViewportHeight(true);
              // Create the scroll pane and add the table to it.
              JScrollPane scrollPane = new JScrollPane(table);
              // Add the scroll pane to this panel.
              add(scrollPane);
         class MyObject {
              String firstName;
              String lastName;
              String sport;
              int years;
              boolean isVeg;
              MyObject(String firstName, String lastName, String sport, int years,
                        boolean isVeg) {
                   this.firstName = firstName;
                   this.lastName = lastName;
                   this.sport = sport;
                   this.years = years;
                   this.isVeg = isVeg;
         class MyTableModel extends AbstractTableModel {
              private String[] columnNames = { "First Name", "Last Name", "Sport",
                        "# of Years", "Vegetarian" };
              ArrayList<MyObject> list = null;
              MyTableModel(ArrayList<MyObject> list) {
                   this.list = list;
              public int getColumnCount() {
                   return columnNames.length;
              public int getRowCount() {
                   return list.size();
              public String getColumnName(int col) {
                   return columnNames[col];
              public Object getValueAt(int row, int col) {
                   MyObject object = list.get(row);
                   switch (col) {
                   case 0:
                        return object.firstName;
                   case 1:
                        return object.lastName;
                   case 2:
                        return object.sport;
                   case 3:
                        return object.years;
                   case 4:
                        return object.isVeg;
                   default:
                        return "unknown";
              public Class getColumnClass(int c) {
                   return getValueAt(0, c).getClass();
          * Create the GUI and show it. For thread safety, this method should be
          * invoked from the event-dispatching thread.
         private static void createAndShowGUI() {
              // Create and set up the window.
              JFrame frame = new JFrame("TableDemo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // Create and set up the content pane.
              TableDemo newContentPane = new TableDemo();
              newContentPane.setOpaque(true); // content panes must be opaque
              frame.setContentPane(newContentPane);
              // Display the window.
              frame.pack();
              frame.setVisible(true);
         public static void main(String[] args) {
              // Schedule a job for the event-dispatching thread:
              // creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        createAndShowGUI();
    }

  • Error in updating Jtable Database

    package desktopapplication1; import java.util.*; import java.sql.*; import javax.swing.JOptionPane; import javax.swing.table.*; public class Datab extends DefaultTableModel { private Connection conn; private Statement st; private ResultSet rs; private ResultSetMetaData rsmd; private int rows; public Datab(String driver, String url, String query) throws SQLException, ClassNotFoundException { Class.forName(driver); conn = DriverManager.getConnection(url); st = conn.createStatement(rs.TYPE_SCROLL_SENSITIVE,rs.CONCUR_UPDATABLE); if ( query.substring(0,3).equalsIgnoreCase("INS") ) { st.executeUpdate(query); } else if ( query.substring(0,3).equalsIgnoreCase("DEL") ) { st.executeUpdate(query); } else { rs = st.executeQuery(query); rsmd = rs.getMetaData(); rs.last(); rows = rs.getRow(); } fireTableStructureChanged(); } public String getColumnName(int column){ try{ return rsmd.getColumnName(column+1); }catch(Exception e){ e.printStackTrace(); } return ""; } public int getColumnCount(){ try{ return rsmd.getColumnCount(); }catch(Exception e){ e.printStackTrace(); } return 0; } public int getRowCount(){ try{ return rows; }catch(Exception e){ e.printStackTrace(); } return 0; } public Object getValueAt(int row, int column){ try{ rs.absolute(row+1); return rs.getObject(column+1); }catch(Exception e){ e.printStackTrace(); } return ""; } public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } public boolean isCellEditable(int row, int column) { if (column < 0) { return false; } else { return true; } } public void setValueAt(Object value, int row, int column){ try{ int conf = JOptionPane.showConfirmDialog(null,"You wanna reaplace "+getValueAt(row,column)+" with "+value+"?", null, 2); if ( conf == 0 ) { rs.absolute(row+1); System.out.println("ROW = "+row+"CURSOR = "+(row+1)+""+rs.getString(1)+column); rs.updateString("Recipe","test"); //i tried to use a simple update cause the normal was not running but same error+ rs.updateRow(); }else { System.out.println("0"); } }catch(SQLException sqle){ System.err.println("Error setting value at row "+row+" column "+column+" with value "+value); sqle.printStackTrace(); } } }
    hi, when i click on my table to edit a value, it give me an error and sometimes fill the cell with a value like [B@341j0j
    Error setting value at row 1 column 0 with value soup2
    java.sql.SQLException: [Microsoft][Driver ODBC Microsoft Access]Error in row
    at sun.jdbc.odbc.JdbcOdbcResultSet.setPos(JdbcOdbcResultSet.java:5271)
    at sun.jdbc.odbc.JdbcOdbcResultSet.updateRow(JdbcOdbcResultSet.java:4171)
    at desktopapplication1.Datab.setValueAt(Datab.java:104)
    at javax.swing.JTable.setValueAt(JTable.java:2719)
    at javax.swing.JTable.editingStopped(JTable.java:4721)
    at javax.swing.AbstractCellEditor.fireEditingStopped(AbstractCellEditor.java:125)
    at javax.swing.DefaultCellEditor$EditorDelegate.stopCellEditing(DefaultCellEditor.java:350)
    at javax.swing.DefaultCellEditor.stopCellEditing(DefaultCellEditor.java:215)
    at javax.swing.JTable$GenericEditor.stopCellEditing(JTable.java:5475)
    at javax.swing.DefaultCellEditor$EditorDelegate.actionPerformed(DefaultCellEditor.java:367)
    at javax.swing.JTextField.fireActionPerformed(JTextField.java:492)
    at javax.swing.JTextField.postActionEvent(JTextField.java:705)
    at javax.swing.JTextField$NotifyAction.actionPerformed(JTextField.java:820)
    at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1636)
    at javax.swing.JComponent.processKeyBinding(JComponent.java:2851)
    at javax.swing.JComponent.processKeyBindings(JComponent.java:2886)
    at javax.swing.JComponent.processKeyEvent(JComponent.java:2814)
    at java.awt.Component.processEvent(Component.java:6040)
    at java.awt.Container.processEvent(Container.java:2041)
    at java.awt.Component.dispatchEventImpl(Component.java:4630)
    at java.awt.Container.dispatchEventImpl(Container.java:2099)
    at java.awt.Component.dispatchEvent(Component.java:4460)
    at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1848)
    at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:704)
    at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:969)
    at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:841)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:668)
    at java.awt.Component.dispatchEventImpl(Component.java:4502)
    at java.awt.Container.dispatchEventImpl(Container.java:2099)
    at java.awt.Window.dispatchEventImpl(Window.java:2475)
    at java.awt.Component.dispatchEvent(Component.java:4460)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
    my db is like
    RecipeName intvalue1 intvalue2 intvalue3 stringvalue4
    soup 3 2 11 fish
    chocolate 3 2 44 dessert
    Edited by: kainard on Aug 1, 2010 2:31 PM
    Edited by: kainard on Aug 1, 2010 2:37 PM

    Can you explain why you declare
    private Connection conn;
    private Statement st;
    private ResultSet rs;
    private ResultSetMetaData rsmd;
    as private

  • URGENT HELP NEEDED FOR JTABLE PROBLEM!!!!!!!!!!!!!!!!!

    firstly i made a jtable to adds and deletes rows and passes the the data to the table model from some textfields. then i wanted to add a tablemoselistener method in order to change the value in the columns 1,2,3,4 and set the result of them in the column 5. when i added that portion of code the buttons that added and deleted rows had problems to function correctly..they dont work at all..can somebody have a look in my code and see wot is wrong..thanx in advance..
    below follows the code..sorry for the mesh of the code..you can use and run the code and notice the problem when you press the add button..also if you want delete the TableChanged method to see that the add button works perfect.
    * Created on 03-Aug-2005
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    * @author Administrator
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import java.io.*;
    public class NodesTable extends JFrame implements TableModelListener, ActionListener {
    JTable jt;
    DefaultTableColumnModel dtcm;
    TableColumn column[] = new TableColumn[100];
    DefaultTableModel dtm;
    JLabel Name,m1,w1,m2,w2;
    JTextField NameTF,m1TF,w1TF,m2TF,w2TF;
    String c [] ={ "Name", "Assessment1", "Weight1" , "Assessment2","Weight2 ","TotalMark"};
    float x=0,y=0,tMark=0,z = 0;
    float j=0;
    int i;
         JButton DelButton;
         JButton AddButton;
         JScrollPane scrollPane;
         JPanel mainPanel,buttonPanel;
         JFrame frame;
         Object[][] data =
              {"tami", new Float(1), new Float(1.11), new Float(1.11),new Float(1),new Float(1)},
              {"tami", new Float(1), new Float(2.22), new Float(2.22),new Float(1),new Float(1)},
              {"petros", new Float(1), new Float(3.33), new Float(3.33),new Float(1),new Float(1)},
              {"petros", new Float(1), new Float(4.44), new Float(4.44),new Float(1),new Float(1)}
    public NodesTable() {
    super("Student Marking Spreadsheet");
    this.AddNodesintoTable();
    setSize(400,250);
    setVisible(true);
    public void AddNodesintoTable(){
    // Create a vector object and load them with the data
    // to be placed on each row of the table
    dtm = new DefaultTableModel(data,c);
    dtm.addTableModelListener( this );
    jt = new JTable(dtm){
         // Returning the Class of each column will allow different
              // renderers to be used based on Class
              public Class getColumnClass(int column)
                   return getValueAt(0, column).getClass();
              // The Cost is not editable
              public boolean isCellEditable(int row, int column)
                   int modelColumn = convertColumnIndexToModel( column );
                   return (modelColumn == 5) ? false : true;
    //****************************User Input**************************
    //Add another node
    //Creating and setting the properties
    //of the panel's component (panels and textfields)
    Name = new JLabel("Name");
    Name.setForeground(Color.black);
    m1 = new JLabel("Mark1");
    m1.setForeground(Color.black);
    w1 = new JLabel("Weigth1");
    w1.setForeground(Color.black);
    m2= new JLabel("Mark2");
    m2.setForeground(Color.black);
    w2 = new JLabel("Weight2");
    w2.setForeground(Color.black);
    NameTF = new JTextField(5);
    NameTF.setText("Node");
    m1TF = new JTextField(5);
    w1TF = new JTextField(5);
    m2TF=new JTextField(5);
    w2TF=new JTextField(5);
    //creating the buttons
    JPanel buttonPanel = new JPanel();
    AddButton=new JButton("Add Row");
    DelButton=new JButton("Delete") ;
    buttonPanel.add(AddButton);
    buttonPanel.add(DelButton);
    //adding the components to the panel
    JPanel inputpanel = new JPanel();
    inputpanel.add(Name);
    inputpanel.add(NameTF);
    inputpanel.add(m1);
    inputpanel.add(m1TF);
    inputpanel.add(w1);
    inputpanel.add(w1TF);
    inputpanel.add(m2);
    inputpanel.add(m2TF);
    inputpanel.add(w2TF);
    inputpanel.add(w2);
    inputpanel.add(AddButton);
    inputpanel.add(DelButton);
    //creating the panel and setting its properties
    JPanel tablepanel = new JPanel();
    tablepanel.add(new JScrollPane(jt, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED
    , JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
    getContentPane().add(tablepanel, BorderLayout.CENTER);
    getContentPane().add(inputpanel, BorderLayout.SOUTH);
    //Method to add row for each new entry
    public void addRow()
    Vector r=new Vector();
    r=createBlankElement();
    dtm.addRow(r);
    jt.addNotify();
    public Vector createBlankElement()
    Vector t = new Vector();
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    return t;
    // Method to delete a row from the spreadsheet
    void deleteRow(int index)
    if(index!=-1) //At least one Row in Table
    dtm.removeRow(index);
    jt.addNotify();
    // Method that adds and deletes rows
    // from the table by pressing the
    //corresponding buttons
    public void actionPerformed(ActionEvent ae){
         Float z=new Float (m2TF.getText());
    String Name= NameTF.getText();
    Float x= new Float(m1TF.getText());
    Float y= new Float(w1TF.getText());
    Float j=new Float (w2TF.getText());
    JFileChooser jfc2 = new JFileChooser();
    String newdata[]= {Name,String.valueOf(x),String.valueOf(y),
    String.valueOf(z),String.valueOf(j)};
    Object source = ae.getSource();
    if(ae.getSource() == (JButton)AddButton)
    addRow();
    if (ae.getSource() ==(JButton) DelButton)
    deleteRow(jt.getSelectedRow());
    //method to calculate the total mark in the TotalMark column
    //that updates the values in every other column
    //It takes the values from the column 1,2,3,4
    //and changes the value in the column 5
    public void tableChanged(TableModelEvent e) {
         System.out.println(e.getSource());
         if (e.getType() == TableModelEvent.UPDATE)
              int row = e.getFirstRow();
              int column = e.getColumn();
              if (column == 1 || column == 2 ||column == 3 ||column == 4)
                   TableModel model = jt.getModel();
              float     q= ((Float)model.getValueAt(row,1)).floatValue();
              float     w= ((Float)model.getValueAt(row,2)).floatValue();
              float     t= ((Float)model.getValueAt(row,3)).floatValue();
              float     r= ((Float)model.getValueAt(row,4)).floatValue();
                   Float tMark = new Float((q*w+t*r)/(w+r) );
                   model.setValueAt(tMark, row, 5);
    // Which cells are editable.
    // It is only necessary to implement this method
    // if the table is editable
    public boolean isCellEditable(int row, int col)
    { return true; //All cells are editable
    public static void main(String[] args) {
         NodesTable t=new NodesTable();
    }

    There are too many mistakes in your program. It looks like you are new to java.
    Your add and delete row buttons are not working because you haven't registered your action listener with these buttons.
    I have modifide your code and now it works fine. Just put some validation code for the textboxes becuase it throws exception when user presses add button without entering anything.
    Here is the updated code: Do the diff and u will know my changes
    * Created on 03-Aug-2005
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    * @author Administrator
    * TODO To change the template for this generated type comment go to Window -
    * Preferences - Java - Code Style - Code Templates
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    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.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.DefaultTableColumnModel;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableModel;
    public class NodesTable extends JFrame implements TableModelListener,
              ActionListener {
         JTable jt;
         DefaultTableColumnModel dtcm;
         TableColumn column[] = new TableColumn[100];
         DefaultTableModel dtm;
         JLabel Name, m1, w1, m2, w2;
         JTextField NameTF, m1TF, w1TF, m2TF, w2TF;
         String c[] = { "Name", "Assessment1", "Weight1", "Assessment2", "Weight2 ",
                   "TotalMark" };
         float x = 0, y = 0, tMark = 0, z = 0;
         float j = 0;
         int i;
         JButton DelButton;
         JButton AddButton;
         JScrollPane scrollPane;
         JPanel mainPanel, buttonPanel;
         JFrame frame;
         public NodesTable() {
              super("Student Marking Spreadsheet");
              this.AddNodesintoTable();
              setSize(400, 250);
              setVisible(true);
         public void AddNodesintoTable() {
              // Create a vector object and load them with the data
              // to be placed on each row of the table
              dtm = new DefaultTableModel(c,0);
              dtm.addTableModelListener(this);
              jt = new JTable(dtm) {
                   // The Cost is not editable
                   public boolean isCellEditable(int row, int column) {
                        int modelColumn = convertColumnIndexToModel(column);
                        return (modelColumn == 5) ? false : true;
              //****************************User Input**************************
              //Add another node
              //Creating and setting the properties
              //of the panel's component (panels and textfields)
              Name = new JLabel("Name");
              Name.setForeground(Color.black);
              m1 = new JLabel("Mark1");
              m1.setForeground(Color.black);
              w1 = new JLabel("Weigth1");
              w1.setForeground(Color.black);
              m2 = new JLabel("Mark2");
              m2.setForeground(Color.black);
              w2 = new JLabel("Weight2");
              w2.setForeground(Color.black);
              NameTF = new JTextField(5);
              NameTF.setText("Node");
              m1TF = new JTextField(5);
              w1TF = new JTextField(5);
              m2TF = new JTextField(5);
              w2TF = new JTextField(5);
              //creating the buttons
              JPanel buttonPanel = new JPanel();
              AddButton = new JButton("Add Row");
              AddButton.addActionListener(this);
              DelButton = new JButton("Delete");
              DelButton.addActionListener(this);
              buttonPanel.add(AddButton);
              buttonPanel.add(DelButton);
              //adding the components to the panel
              JPanel inputpanel = new JPanel();
              inputpanel.add(Name);
              inputpanel.add(NameTF);
              inputpanel.add(m1);
              inputpanel.add(m1TF);
              inputpanel.add(w1);
              inputpanel.add(w1TF);
              inputpanel.add(m2);
              inputpanel.add(m2TF);
              inputpanel.add(w2TF);
              inputpanel.add(w2);
              inputpanel.add(AddButton);
              inputpanel.add(DelButton);
              //creating the panel and setting its properties
              JPanel tablepanel = new JPanel();
              tablepanel.add(new JScrollPane(jt,
                        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                        JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
              getContentPane().add(tablepanel, BorderLayout.CENTER);
              getContentPane().add(inputpanel, BorderLayout.SOUTH);
         //Method to add row for each new entry
         public void addRow() {
              Float z = new Float(m2TF.getText());
              String Name = NameTF.getText();
              Float x = new Float(m1TF.getText());
              Float y = new Float(w1TF.getText());
              Float j = new Float(w2TF.getText());
              String newdata[] = { Name, String.valueOf(x), String.valueOf(y),
                        String.valueOf(z), String.valueOf(j) };
              dtm.addRow(newdata);
         // Method to delete a row from the spreadsheet
         void deleteRow(int index) {
              if (index != -1) //At least one Row in Table
                   dtm.removeRow(index);
                   jt.addNotify();
         // Method that adds and deletes rows
         // from the table by pressing the
         //corresponding buttons
         public void actionPerformed(ActionEvent ae) {
              Object source = ae.getSource();
              if (ae.getSource() == (JButton) AddButton) {
                   addRow();
              if (ae.getSource() == (JButton) DelButton) {
                   deleteRow(jt.getSelectedRow());
         //method to calculate the total mark in the TotalMark column
         //that updates the values in every other column
         //It takes the values from the column 1,2,3,4
         //and changes the value in the column 5
         public void tableChanged(TableModelEvent e) {
              System.out.println(e.getSource());
              //if (e.getType() == TableModelEvent.UPDATE) {
                   int row = e.getFirstRow();
                   int column = e.getColumn();
                   if (column == 1 || column == 2 || column == 3 || column == 4) {
                        TableModel model = jt.getModel();
                        float q = (new Float(model.getValueAt(row, 1).toString())).floatValue();
                        float w = (new Float(model.getValueAt(row, 2).toString())).floatValue();
                        float t = (new Float(model.getValueAt(row, 3).toString())).floatValue();
                        float r = (new Float(model.getValueAt(row, 4).toString())).floatValue();
                        Float tMark = new Float((q * w + t * r) / (w + r));
                        model.setValueAt(tMark, row, 5);
         // Which cells are editable.
         // It is only necessary to implement this method
         // if the table is editable
         public boolean isCellEditable(int row, int col) {
              return true; //All cells are editable
         public static void main(String[] args) {
              NodesTable t = new NodesTable();
    }

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

  • Display data in JTable

    I am trying to display data from database into the JTable swing component. I can see the table and the heading coming from the vector. I cannot see why the data from the databse table is not loaded on to the Jtable. I just get a table with 6 rows blank.
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    public class dataTable extends JApplet
    String dbdriver="jdbc:oracle:thin:@ds1.ctateu.edu:1521:wpac";
    String dbuser="system";
    String dbpass="pass";
    Container c;
    JScrollPane jsp;
    JTable table;
    int v,h;
    Connection connection;
    Statement stmt;
    ResultSet rs;
    String param_start,param_end, param_disp_start, param_disp_end,param_shortdesc, param_longdesc;
    public void init()
    c= getContentPane();
    c.setLayout (new BorderLayout());
    v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
    h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
    Vector heading = new Vector();
    heading.addElement("Event Start Date");
    heading.addElement("Event End Date");
    heading.addElement("Display Start Date");
    heading.addElement("Display End Date");
    heading.addElement("Short Description");
    heading.addElement("Long Description");
    Vector data = new Vector();
    try
    Class.forName("oracle.jdbc.driver.OracleDriver");
    connection=DriverManager.getConnection(dbdriver,dbuser,dbpass);
    stmt=connection.createStatement();
    rs= stmt.executeQuery("select * from univevents");
    while(rs.next())
    param_start = rs.getString("start_date");
    param_end = rs.getString("end_date");
    param_disp_start = rs.getString("display_start");
    param_disp_end =rs.getString("display_end");
    param_shortdesc = rs.getString("short_desc");
    param_longdesc = rs.getString("long_desc");
    catch (Exception e)
    //JOptionPane.showMessageDialogue("Exception: "+e.getMessage());
    data.addElement(param_start);
    data.addElement(param_end);
    data.addElement(param_disp_start);
    data.addElement(param_disp_end);
    data.addElement(param_shortdesc);
    data.addElement(param_longdesc);
    table = new JTable(data, heading);
    jsp = new JScrollPane(table,v,h);
    //Add scrollpane to container
    c.add("Center",jsp);
    }//init
    }//JApplet

    Your data vector should be a Vector of Vectors.
    I think you need to change your loop to look something like this:
    while(rs.next())
        Vector row = new Vector();
        row.addElement( rs.getString("start_date") );
        row.addElement( rs.getString("end_date") );
        row.addElement( rs.getString("display_start") );
        row.addElement( rs.getString("display_end") );
        row.addElement( rs.getString("short_desc") );
        row.addElement( rs.getString("long_desc") );
        data.addElement( row );
    } Then remove your data.addElement() statements found outside the loop.

Maybe you are looking for

  • Can't get ipod to show up...

    I'm sure this sort of question has been posted before, but I have an annoying problem with my ipod. Long story short, I got a new computer and hooked my ipod up to it and everything. I downloaded itunes and even bought a couple songs, but I can't tra

  • Payment Transfer Prinitng using Z-script

    Dear All, I am trying to print Payment transfer form from the transactions FB60 and F110. Here I have taken the Z-copy of the Script form "F110_D_AVIS" and modified the script to my requirement. Then I assigned the Z-form in the FBZP transaction. But

  • Crystal Reports error on Digital Dashboard not on Dev

    Created a report to access some large text fields in a SQL Server 2000 table. Original data connection was ODBC which truncated field at 255. Moved to OLEDB and all was well, text field printed fine in dev and Digital Dashboard. Modified report and s

  • Can't see smb shares in Mountain Lion

    If I go to Go and go to network I can see the currently powered computers on my network. We have (from left to right) WinXP, Linux (embedded), and Vista. If I explore into one of them, I can see its shares: If I open a share then it appears to mount

  • Having problem with the sync on iPhone 6, anyone know the solution

    Why is iPhone 6 taking so long to sync?