Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Jtable only updates at the end of a buton event.

  1. #1
    Junior Member
    Join Date
    Apr 2013
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Jtable only updates at the end of a buton event.

    My problem is the following :

    I have a jtable that displays some data in the rows.
    I have a button whose event is to loop slowly through the rows of this table and change the values of the data - in this case flip true/false .. and slowly is due to a sleep (The actual problem I have is a lengthy calculation)
    I would like the table to update after each change, as it currently only updates at the end of the button event.
    What am i doing wrong ? I have tried all sorts of combinations.


    The (self contained) code that demonstrates the problem is below -
    I have adapted the TableDemo example for the orcale/java How to Use Tables tutorial


     
    /** 
     * TableDemo is just like SimpleTableDemo, except that it
     * uses a custom TableModel.
     */
    public class TableDemo extends JPanel {
     
        private JButton looper;
        JTable table;
        MyTableModel mdl;
        private static JFrame frame;
     
        public TableDemo() {
            super(new GridLayout(2,0));
     
            looper = new JButton();
            looper.setText("Hit Me to loop thru table and flip vegetarian preference");
     
            looper.addActionListener(new java.awt.event.ActionListener() {
                @Override
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    HitButtonActionPerformed(evt);
                }
            });
     
            mdl = new MyTableModel();       
            table = new JTable(mdl);
            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);
            //add button
            add(looper);
        }
     
        public void HitButtonActionPerformed(ActionEvent e) {
     
            for (int row=0; row<table.getRowCount();row++)
            {
                try {
                    Thread.currentThread().sleep(1000);//sleep for 1000 ms
                    System.out.println("one more flip");
     
                    Object p = table.getValueAt(row, 4);
                    table.setValueAt( !((Boolean)p), row, 4);
     
                    /* no hope
                    ( (AbstractTableModel)table.getModel()).fireTableCellUpdated(row, 4);
                    mdl.fireTableCellUpdated(row, 4);
                    mdl.fireTableDataChanged();
                    table.validate();  
                    frame.repaint();
                    */
     
                } catch (InterruptedException ex) {
                    Logger.getLogger(TableDemo.class.getName()).log(Level.SEVERE, null, ex);
                }
     
            }
        }
     
        class MyTableModel extends AbstractTableModel {
            private String[] columnNames = {"First Name",
                                            "Last Name",
                                            "Sport",
                                            "# of Years",
                                            "Vegetarian"};
            private Object[][] data = {
            {"Kathy", "Smith","Snowboarding", new Integer(5), false},
            {"John", "Doe","Rowing", new Integer(3), true},
            {"Sue", "Black", "Knitting", new Integer(2), false},
            {"Jane", "White", "Speed reading", new Integer(20), true},
            {"Joe", "Brown","Pool", new Integer(10), false}
            };
     
            @Override
            public int getColumnCount() {
                return columnNames.length;
            }
     
            @Override
            public int getRowCount() {
                return data.length;
            }
     
            @Override
            public String getColumnName(int col) {
                return columnNames[col];
            }
     
            @Override
            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.
             */
            @Override
            public Class getColumnClass(int c) {
                return getValueAt(0, c).getClass();
            }
     
            /*
             * Don't need to implement this method unless your table's
             * editable.
             */
            @Override
            public boolean isCellEditable(int row, int col) {
                //Note that the data/cell address is constant,
                //no matter where the cell appears onscreen.
                if (col < 2) {
                    return false;
                } else {
                    return true;
                }
            }
     
            /*
             * Don't need to implement this method unless your table's
             * data can change.
             */
            @Override
            public void setValueAt(Object value, int row, int col) {          
                data[row][col] = value;
                fireTableCellUpdated(row, col);
            }
        }
     
        /**
         * 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.
            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();
                }
            });
        } 
    }


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,307
    Thanks
    181
    Thanked 824 Times in 767 Posts
    Blog Entries
    5

    Default Re: Jtable only updates at the end of a buton event.

    Use a Thread or a SwingWorker - any long running tasks placed on the EDT will clog up the UI.
    Worker Threads and SwingWorker (The Java™ Tutorials > Creating a GUI With JFC/Swing > Concurrency in Swing)

Similar Threads

  1. [SOLVED] How to get Progress updates from multiple threads...
    By Becca in forum Threads
    Replies: 4
    Last Post: February 7th, 2012, 12:34 PM
  2. [SOLVED] A question about updates. (Program dosent update until refreshed)
    By DusteroftheCentury in forum What's Wrong With My Code?
    Replies: 4
    Last Post: February 1st, 2012, 10:59 PM
  3. Variable updates after loop
    By tecno40 in forum Loops & Control Statements
    Replies: 1
    Last Post: November 9th, 2011, 04:34 AM
  4. [SOLVED] jTable event help
    By banny7 in forum AWT / Java Swing
    Replies: 12
    Last Post: August 1st, 2011, 07:42 AM
  5. [SOLVED] Trojans with last few updates of NetBeans
    By Melawe in forum Java IDEs
    Replies: 11
    Last Post: May 22nd, 2010, 08:33 AM