001    package org.shiftone.jrat.desktop;
002    
003    import org.jdesktop.swingx.JXHyperlink;
004    
005    import javax.swing.*;
006    import java.awt.event.ActionEvent;
007    import java.awt.event.ActionListener;
008    import java.util.TimerTask;
009    
010    /**
011     * @author (jeff@shiftone.org) Jeff Drost
012     */
013    public class Memory extends JPanel {
014    
015        private static final long MEG = 1024 * 1024;
016        private static final java.util.Timer timer = new java.util.Timer(true);
017    
018        public static JButton createMemoryButton() {
019            JButton button = new JXHyperlink();
020            button.addActionListener(new GcAction());
021            timer.schedule(new TickerTask(button), 1000, 1000);
022            return button;
023        }
024    
025        private static class GcAction implements ActionListener {
026    
027            public void actionPerformed(ActionEvent actionEvent) {
028                System.gc();
029            }
030        }
031    
032        private static class TickerTask extends TimerTask {
033    
034            private final JButton button;
035    
036            public TickerTask(JButton button) {
037                this.button = button;
038            }
039    
040            public void run() {
041    
042                Runtime runtime = Runtime.getRuntime();
043    
044                final StringBuffer sb = new StringBuffer();
045    
046                long total = runtime.totalMemory();
047                long max = runtime.maxMemory();
048                long free = runtime.freeMemory();
049    
050                sb.append(toMeg(total - free));
051                sb.append(" of ");
052                sb.append(toMeg(max));
053    
054    
055                SwingUtilities.invokeLater(new Runnable() {
056                    public void run() {
057                        button.setText(sb.toString());
058                    }
059                });
060            }
061        }
062    
063        private static String toMeg(long bytes) {
064            return (int) ((double) bytes / (double) MEG) + "M";
065        }
066    }