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 7 of 7

Thread: revalidate, repaint to refresh JTable

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

    Question revalidate, repaint to refresh JTable

    my jSlider1StateChanged is supposed to update the DefaultTableModel, however the changes are never reflected in the GUI. Do I have the correct approach for this method?


    package net.bounceme.dur.nntp;
     
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.table.DefaultTableModel;
     
    public class MessagesJFrame extends javax.swing.JFrame {
     
        private static final long serialVersionUID = 1L;
        private static final Logger LOG = Logger.getLogger(MessagesJFrame.class.getName());
        private DefaultTableModel defaultTableModel = new DefaultTableModel();
     
        public MessagesJFrame() throws Exception {
            MessageUtils.init();
            defaultTableModel = MessageUtils.getDataTableModel();
            initComponents();
        }
     
        /**
         * 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() {
     
            jScrollPane1 = new javax.swing.JScrollPane();
            jTableMessages = new javax.swing.JTable();
            jScrollPane2 = new javax.swing.JScrollPane();
            jTextPaneContent = new javax.swing.JTextPane();
            jSlider1 = new javax.swing.JSlider();
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setAlwaysOnTop(true);
     
            jTableMessages.setModel(defaultTableModel);
            jTableMessages.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
            jTableMessages.setShowHorizontalLines(false);
            jTableMessages.setShowVerticalLines(false);
            jTableMessages.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    jTableMessagesMouseClicked(evt);
                }
            });
            jTableMessages.addKeyListener(new java.awt.event.KeyAdapter() {
                public void keyPressed(java.awt.event.KeyEvent evt) {
                    jTableMessagesKeyPressed(evt);
                }
            });
            jScrollPane1.setViewportView(jTableMessages);
     
            jScrollPane2.setViewportView(jTextPaneContent);
     
            jSlider1.setMaximum(MessageUtils.getMax());
            jSlider1.addChangeListener(new javax.swing.event.ChangeListener() {
                public void stateChanged(javax.swing.event.ChangeEvent evt) {
                    jSlider1StateChanged(evt);
                }
            });
     
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jSlider1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 905, Short.MAX_VALUE)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING))
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap())
            );
     
            pack();
        }// </editor-fold>
     
        private void jTableMessagesMouseClicked(java.awt.event.MouseEvent evt) {                                            
            int row = jTableMessages.rowAtPoint(evt.getPoint());
            setText(row);
        }                                           
     
        private void jTableMessagesKeyPressed(java.awt.event.KeyEvent evt) {                                          
            //int row = jTableMessages.rowAtPoint(evt.getKeyLocation());
            //setJFrame(row);
        }                                         
     
        private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {                                      
            int index = jSlider1.getValue();
            MessageUtils.setIndex(index);
            defaultTableModel = MessageUtils.getDataTableModel();
            revalidate();
            repaint();
        }                                     
     
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            /*
             * Set the Nimbus look and feel
             */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /*
             * If Nimbus (introduced in Java SE 6) is not available, stay with the
             * default look and feel. For details see
             * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(MessagesJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(MessagesJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(MessagesJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(MessagesJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
     
            /*
             * Create and display the form
             */
            java.awt.EventQueue.invokeLater(new Runnable() {
     
                public void run() {
                    try {
                        new MessagesJFrame().setVisible(true);
                    } catch (Exception ex) {
                        Logger.getLogger(MessagesJFrame.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });
        }
        // Variables declaration - do not modify
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JScrollPane jScrollPane2;
        private javax.swing.JSlider jSlider1;
        private javax.swing.JTable jTableMessages;
        private javax.swing.JTextPane jTextPaneContent;
        // End of variables declaration
     
        private void setText(int row) {
            MessageBean mb = MessageUtils.getMessageBean(row);
            jTextPaneContent.setText(mb.getContent());
            jTextPaneContent.setContentType("text/html");
        }
    }



    As can be seen in this console output, the DefaultTableModel is actually getting logged and passed to the JFrame:


    Apr 25, 2012 3:14:37 AM net.bounceme.dur.nntp.MessageUtils setIndex
    INFO: MessageUtils.setIndex..trying 100
    Apr 25, 2012 3:14:37 AM net.bounceme.dur.nntp.MessageUtils setIndex
    INFO: just right, setting..100
    Apr 25, 2012 3:14:37 AM net.bounceme.dur.nntp.MessageUtils getDataTableModel
    INFO: Thu Apr 19 09:58:24 PDT 2012North Korea’s prison camps: The gulag behind the goose-steps
    Apr 25, 2012 3:14:37 AM net.bounceme.dur.nntp.MessageUtils getDataTableModel
    INFO: Thu Apr 19 09:58:24 PDT 2012Attacks in Afghanistan: Spectacular
    Apr 25, 2012 3:14:37 AM net.bounceme.dur.nntp.MessageUtils getDataTableModel
    INFO: Thu Apr 19 09:58:25 PDT 2012Pakistan and alcohol: Hope in the hops
    Apr 25, 2012 3:14:37 AM net.bounceme.dur.nntp.MessageUtils getDataTableModel
    INFO: Thu Apr 19 09:58:25 PDT 2012Banyan: Mischief Minister
    Apr 25, 2012 3:14:37 AM net.bounceme.dur.nntp.MessageUtils getDataTableModel
    INFO: Sun Apr 22 02:58:20 PDT 2012GDP forecasts
    Apr 25, 2012 3:14:37 AM net.bounceme.dur.nntp.MessageUtils getDataTableModel
    INFO: Sun Apr 22 02:58:21 PDT 2012Trade, exchange rates, budget balances and interest rates
    Apr 25, 2012 3:14:37 AM net.bounceme.dur.nntp.MessageUtils getDataTableModel


    which originates with the log message in getDataTableModel:

    package net.bounceme.dur.nntp;
     
    import java.util.Iterator;
    import java.util.List;
    import java.util.Vector;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.mail.Message;
    import javax.swing.table.DefaultTableModel;
     
    public class MessageUtils {
     
        private static final long serialVersionUID = 1L;
        private static final Logger LOG = Logger.getLogger(MessageUtils.class.getName());
        private static DefaultTableModel defaultTableModel = new DefaultTableModel();
        private static EnumNNTP nntp = EnumNNTP.INSTANCE;
        private static Vector messages = new Vector();
        private static int pageSize = 10;
        private static int index;
        private static int max;
     
        public static void init() {
            setMax(nntp.getSize());
            setIndex(getMax() - 10);
            loadMessages();
        }
     
        private static void loadMessages() {
            List<Message> listOfMessages = nntp.getMessages(getIndex() - pageSize, getIndex());
            for (Message m : listOfMessages) {
                MessageBean messageBean = null;
                try {
                    messageBean = new MessageBean(m);
                } catch (Exception ex) {
                    Logger.getLogger(MessageUtils.class.getName()).log(Level.SEVERE, null, ex);
                }
                messages.add(messageBean);
            }
            loadTableModel();
        }
     
        private static void loadTableModel() {
            defaultTableModel = new DefaultTableModel();
            defaultTableModel.addColumn("sent");
            defaultTableModel.addColumn("subject");
            for (Object o : messages) {  //awkward Vector manipulation
                MessageBean messageBean = (MessageBean) o;
                Vector messageBeanAsVector = messageBean.getVector();
                defaultTableModel.addRow(messageBeanAsVector);
            }
        }
     
        public static DefaultTableModel getDataTableModel() {
            Vector vector = defaultTableModel.getDataVector();
            Iterator it = vector.iterator();
            while (it.hasNext()) {
                Vector v = (Vector) it.next();
                Iterator i = v.iterator();
                StringBuilder row = new StringBuilder();
                while (i.hasNext()) {
                    row.append(i.next());
                }
                LOG.info(row.toString());
            }
            return defaultTableModel;
        }
     
        public static void setDataTableModel(DefaultTableModel dataTableModel) {
            MessageUtils.defaultTableModel = dataTableModel;
        }
     
        public static Vector getMessages() {
            return messages;
        }
     
        public static void setMessages(Vector messages) {
            MessageUtils.messages = messages;
        }
     
        public static MessageBean getMessageBean(int row) {
            MessageBean messageBean = (MessageBean) messages.elementAt(row);
            return messageBean;
        }
     
        public static int getIndex() {
            return index;
        }
     
        public static void setIndex(int aIndex) {
            LOG.log(Level.INFO, "MessageUtils.setIndex..trying {0}", aIndex);
            if (aIndex < pageSize + 1) {  //goldilocks check on aIndex
                aIndex = pageSize + 1;
                LOG.log(Level.INFO, "too small, setting default..{0}", aIndex);
            } else if (aIndex >= getMax() - pageSize) {
                aIndex = getMax() - pageSize;
                LOG.log(Level.INFO, "too big, setting default..{0}", aIndex);
            } else {
                LOG.log(Level.INFO, "just right, setting..{0}", aIndex);
            }
            index = aIndex;
            loadMessages();
        }
     
        public static int getMax() {
            return max;
        }
     
        public static void setMax(int aMax) {
            max = aMax;
        }
    }


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,462
    My Mood
    Hungover
    Thanks
    144
    Thanked 639 Times in 547 Posts

    Default Re: revalidate, repaint to refresh JTable

    That's quite a bit of code to go through, so I would suggest boiling this down to an SSCCE that demonstrates the problem that we can just copy and paste to run and see what you're talking about.

    So just guessing at your actual problem, I'll remind you that the view isn't automatically updated when the model changes. You have to tell the view to update itself. There are a few methods to do that. I would check out the API for AbstractTableModel for some useful methods: Java Platform SE 6
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    Junior Member
    Join Date
    Apr 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: revalidate, repaint to refresh JTable

    Quote Originally Posted by KevinWorkman View Post
    That's quite a bit of code to go through, so I would suggest boiling this down to an SSCCE that demonstrates the problem that we can just copy and paste to run and see what you're talking about.

    So just guessing at your actual problem, I'll remind you that the view isn't automatically updated when the model changes. You have to tell the view to update itself. There are a few methods to do that. I would check out the API for AbstractTableModel for some useful methods: Java Platform SE 6

    Could you be more specific about how tell a JTable to "renew" itself? I specifically want to populate the model outside of the JFrame, which happens, but how do I trigger the JTable to refresh? There are many methods in AbstractTableModel.

  4. #4
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,337
    Thanks
    182
    Thanked 830 Times in 773 Posts
    Blog Entries
    5

    Default Re: revalidate, repaint to refresh JTable

    Look at the all the methods in that class that begin with fire...for instance, fireTableDataChanged()

  5. #5
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,462
    My Mood
    Hungover
    Thanks
    144
    Thanked 639 Times in 547 Posts

    Default Re: revalidate, repaint to refresh JTable

    Quote Originally Posted by THUFIR View Post
    Could you be more specific about how tell a JTable to "renew" itself? I specifically want to populate the model outside of the JFrame, which happens, but how do I trigger the JTable to refresh? There are many methods in AbstractTableModel.
    I'm not sure what you mean by the model outside of the JFrame. But there really aren't that many methods in AbstractTableModel (heck, they all fit on a single page), so reading through them shouldn't be THAT much to ask, especially since you should become more familiar with the model/view/controller relationship anyway.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  6. #6
    Junior Member
    Join Date
    Apr 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: revalidate, repaint to refresh JTable

    Quote Originally Posted by KevinWorkman View Post
    I'm not sure what you mean by the model outside of the JFrame.
    What I mean is the DefaultTableModel instance in the controller, can MessageUtils
    defaultTableModel.fireTableDataChanged();
    cause changes to the JList?

  7. #7
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,462
    My Mood
    Hungover
    Thanks
    144
    Thanked 639 Times in 547 Posts

    Default Re: revalidate, repaint to refresh JTable

    Quote Originally Posted by THUFIR View Post
    What I mean is the DefaultTableModel instance in the controller, can MessageUtils
    defaultTableModel.fireTableDataChanged();
    cause changes to the JList?
    Huh? What changes? What happened when you tried?
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

Similar Threads

  1. Refresh/reload only a specific <div>
    By figge88 in forum Other Programming Languages
    Replies: 2
    Last Post: April 7th, 2012, 02:12 PM
  2. 60FPS refresh loop
    By Joe Moer in forum What's Wrong With My Code?
    Replies: 41
    Last Post: December 6th, 2010, 07:22 AM
  3. JTable refresh with Hibernate
    By Scott.Anthony in forum JDBC & Databases
    Replies: 2
    Last Post: October 12th, 2010, 04:19 AM
  4. GUI - refresh problem
    By Shnkc in forum AWT / Java Swing
    Replies: 5
    Last Post: April 2nd, 2010, 06:11 AM
  5. revalidate() JPanel outside of class it resides
    By Deadbob in forum What's Wrong With My Code?
    Replies: 4
    Last Post: February 9th, 2010, 04:14 PM

Tags for this Thread